1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.statementservice.retriever;
18
19import org.json.JSONObject;
20
21/**
22 * Factory to create asset from JSON string.
23 */
24/* package private */ final class AssetFactory {
25
26    private static final String FIELD_NOT_STRING_FORMAT_STRING = "Expected %s to be string.";
27
28    private AssetFactory() {}
29
30    /**
31     * Checks that the input is a valid asset with purposes.
32     *
33     * @throws AssociationServiceException if the asset is not well formatted.
34     */
35    public static AbstractAsset create(JSONObject asset)
36            throws AssociationServiceException {
37        String namespace = asset.optString(Utils.NAMESPACE_FIELD, null);
38        if (namespace == null) {
39            throw new AssociationServiceException(String.format(
40                    FIELD_NOT_STRING_FORMAT_STRING, Utils.NAMESPACE_FIELD));
41        }
42
43        if (namespace.equals(Utils.NAMESPACE_WEB)) {
44            return WebAsset.create(asset);
45        } else if (namespace.equals(Utils.NAMESPACE_ANDROID_APP)) {
46            return AndroidAppAsset.create(asset);
47        } else {
48            throw new AssociationServiceException("Namespace " + namespace + " is not supported.");
49        }
50    }
51}
52