001package com.box.sdk.internal.utils;
002
003import java.util.ArrayList;
004import java.util.HashMap;
005import java.util.List;
006import java.util.Map;
007
008import com.box.sdk.Metadata;
009import com.box.sdk.Representation;
010import com.eclipsesource.json.JsonObject;
011import com.eclipsesource.json.JsonValue;
012
013/**
014 * Utility class for constructing metadata map from json object.
015 */
016public class Parsers {
017
018    /**
019     * Only static members.
020     */
021    protected Parsers() {
022    }
023
024    /**
025     * Creates a map of metadata from json.
026     * @param jsonObject metadata json object for metadata field in get /files?fileds=,etadata.scope.template response
027     * @return Map of String as key a value another Map with a String key and Metadata value
028     */
029    public static Map<String, Map<String, Metadata>> parseAndPopulateMetadataMap(JsonObject jsonObject) {
030        Map<String, Map<String, Metadata>> metadataMap = new HashMap<String, Map<String, Metadata>>();
031        //Parse all templates
032        for (JsonObject.Member templateMember : jsonObject) {
033            if (templateMember.getValue().isNull()) {
034                continue;
035            } else {
036                String templateName = templateMember.getName();
037                Map<String, Metadata> scopeMap = metadataMap.get(templateName);
038                //If templateName doesn't yet exist then create an entry with empty scope map
039                if (scopeMap == null) {
040                    scopeMap = new HashMap<String, Metadata>();
041                    metadataMap.put(templateName, scopeMap);
042                }
043                //Parse all scopes in a template
044                for (JsonObject.Member scopeMember : templateMember.getValue().asObject()) {
045                    String scope = scopeMember.getName();
046                    Metadata metadataObject = new Metadata(scopeMember.getValue().asObject());
047                    scopeMap.put(scope, metadataObject);
048                }
049            }
050
051        }
052        return metadataMap;
053    }
054
055    /**
056     * Parse representations from a file object response.
057     * @param jsonObject representations json object in get response for /files/file-id?fields=representations
058     * @return list of representations
059     */
060    public static List<Representation> parseRepresentations(JsonObject jsonObject) {
061        List<Representation> representations = new ArrayList<Representation>();
062        for (JsonValue representationJson : jsonObject.get("entries").asArray()) {
063            Representation representation = new Representation(representationJson.asObject());
064            representations.add(representation);
065        }
066        return representations;
067    }
068}