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 
17 package com.android.statementservice.retriever;
18 
19 import com.android.statementservice.utils.StatementUtils;
20 
21 import org.json.JSONObject;
22 
23 /**
24  * Factory to create asset from JSON string.
25  */
26 public final class AssetFactory {
27 
28     private static final String FIELD_NOT_STRING_FORMAT_STRING = "Expected %s to be string.";
29 
AssetFactory()30     private AssetFactory() {}
31 
32     /**
33      * Checks that the input is a valid asset with purposes.
34      *
35      * @throws AssociationServiceException if the asset is not well formatted.
36      */
create(JSONObject asset)37     public static AbstractAsset create(JSONObject asset)
38             throws AssociationServiceException {
39         String namespace = asset.optString(StatementUtils.NAMESPACE_FIELD, null);
40         if (namespace == null) {
41             throw new AssociationServiceException(String.format(
42                     FIELD_NOT_STRING_FORMAT_STRING, StatementUtils.NAMESPACE_FIELD));
43         }
44 
45         if (namespace.equals(StatementUtils.NAMESPACE_WEB)) {
46             return WebAsset.create(asset);
47         } else if (namespace.equals(StatementUtils.NAMESPACE_ANDROID_APP)) {
48             return AndroidAppAsset.create(asset);
49         } else {
50             throw new AssociationServiceException("Namespace " + namespace + " is not supported.");
51         }
52     }
53 }
54