Example usage for com.google.gson JsonArray iterator

List of usage examples for com.google.gson JsonArray iterator

Introduction

In this page you can find the example usage for com.google.gson JsonArray iterator.

Prototype

public Iterator<JsonElement> iterator() 

Source Link

Document

Returns an iterator to navigate the elements of the array.

Usage

From source file:org.slc.sli.dashboard.security.SLIAuthenticationEntryPoint.java

License:Apache License

private SLIPrincipal completeSpringAuthentication(String token) {

    // Get authentication information
    JsonObject json = restClient.sessionCheck(token);

    LOG.debug(json.toString());//  ww w. j a  va2 s  .  com

    // If the user is authenticated, create an SLI principal, and authenticate
    JsonElement authElement = json.get(Constants.ATTR_AUTHENTICATED);
    if ((authElement != null) && (authElement.getAsBoolean())) {

        // Setup principal
        SLIPrincipal principal = new SLIPrincipal();
        principal.setId(token);

        // Extract user name from authentication payload
        String username = "";
        JsonElement nameElement = json.get(Constants.ATTR_AUTH_FULL_NAME);
        if (nameElement != null) {
            username = nameElement.getAsString();
            if (username != null && username.contains("@")) {
                username = username.substring(0, username.indexOf("@"));
                if (username.contains(".")) {
                    String first = username.substring(0, username.indexOf('.'));
                    String second = username.substring(username.indexOf('.') + 1);
                    username = first.substring(0, 1).toUpperCase()
                            + (first.length() > 1 ? first.substring(1) : "")
                            + (second.substring(0, 1).toUpperCase()
                                    + (second.length() > 1 ? second.substring(1) : ""));
                }
            }
        } else {
            LOG.error(LOG_MESSAGE_AUTH_EXCEPTION_INVALID_NAME);
        }

        // Set principal name
        principal.setName(username);

        // Extract user roles from authentication payload
        LinkedList<GrantedAuthority> authList = new LinkedList<GrantedAuthority>();
        JsonArray grantedAuthorities = json.getAsJsonArray(Constants.ATTR_AUTH_ROLES);
        if (grantedAuthorities != null) {

            // Add authorities to user principal
            Iterator<JsonElement> authIterator = grantedAuthorities.iterator();
            while (authIterator.hasNext()) {
                JsonElement nextElement = authIterator.next();
                authList.add(new GrantedAuthorityImpl(nextElement.getAsString()));
            }
        } else {
            LOG.error(LOG_MESSAGE_AUTH_EXCEPTION_INVALID_ROLES);
        }
        if (json.get(Constants.ATTR_USER_TYPE).getAsString().equals(Constants.ROLE_TEACHER)) {
            authList.add(new GrantedAuthorityImpl(Constants.ROLE_EDUCATOR));
        }

        if (json.get(Constants.ATTR_ADMIN_USER).getAsBoolean()) {
            authList.add(new GrantedAuthorityImpl(Constants.ROLE_IT_ADMINISTRATOR));
        }

        SecurityContextHolder.getContext()
                .setAuthentication(new PreAuthenticatedAuthenticationToken(principal, token, authList));

        return principal;
    } else {
        LOG.error(LOG_MESSAGE_AUTH_EXCEPTION_INVALID_AUTHENTICATED);
    }

    return null;
}

From source file:org.socraticgrid.kmrolib.SPARQLQueryUtil.java

License:Apache License

/**
 * //from  www  . ja  v a2s  .  c om
 * Utility - turns JsonObject list into List of Maps. All values become Strings.
 *
 * TBD: could type the values
 */
protected List<Map<String, String>> processListReply(JsonObject listReply) {
    JsonObject results = listReply.getAsJsonObject("results");
    JsonArray bindings = results.getAsJsonArray("bindings");

    Iterator<JsonElement> bindingsIterator = bindings.iterator();
    List<Map<String, String>> typedBindingList = new ArrayList<Map<String, String>>();
    while (bindingsIterator.hasNext()) {
        JsonObject binding = bindingsIterator.next().getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> bindingEntries = binding.entrySet();
        Map<String, String> typedBinding = new HashMap<String, String>();
        for (Map.Entry<String, JsonElement> bindingEntry : bindingEntries) {
            String key = bindingEntry.getKey();
            JsonElement value = bindingEntry.getValue();
            String stringValue = value.getAsJsonObject().getAsJsonPrimitive("value").getAsString();
            typedBinding.put(key, stringValue);
        }
        typedBindingList.add(typedBinding);
    }
    return typedBindingList;
}

From source file:org.socraticgrid.kmrolib.SPARQLQueryUtil_KMRO10.java

License:Apache License

/**
 * By domain, return distinct dates where a patient has data
 *
 * Date xmlDateIn = sdf.parse(value)//from   www.  ja  v  a2  s.  com
 */
public List<String> getDatesOfPatientByDomain(String patientId, String domain) throws Exception {
    String query = String.format(QUERY_SDATES_BYPATIENTANDTYPE, patientId, domain);

    JsonObject listReply = this.requestJSON(query);

    JsonObject results = listReply.getAsJsonObject("results");
    JsonArray bindings = results.getAsJsonArray("bindings");
    Iterator<JsonElement> bindingsIterator = bindings.iterator();
    List<String> singleValues = new ArrayList<String>();
    while (bindingsIterator.hasNext()) {
        JsonObject binding = bindingsIterator.next().getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> bindingEntries = binding.entrySet();
        for (Map.Entry<String, JsonElement> bindingEntry : bindingEntries) {
            String key = bindingEntry.getKey();
            JsonElement value = bindingEntry.getValue();
            String stringValue = value.getAsJsonObject().getAsJsonPrimitive("value").getAsString();
            singleValues.add(stringValue);
        }
    }
    return singleValues;
}

From source file:org.socraticgrid.kmrolib.SPARQLQueryUtil_KMRO10.java

License:Apache License

private List<Map<String, String>> processListReply(JsonObject listReply) {
    JsonObject results = listReply.getAsJsonObject("results");
    JsonArray bindings = results.getAsJsonArray("bindings");
    Iterator<JsonElement> bindingsIterator = bindings.iterator();
    List<Map<String, String>> typedBindingList = new ArrayList<Map<String, String>>();
    while (bindingsIterator.hasNext()) {
        JsonObject binding = bindingsIterator.next().getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> bindingEntries = binding.entrySet();
        Map<String, String> typedBinding = new HashMap<String, String>();
        for (Map.Entry<String, JsonElement> bindingEntry : bindingEntries) {
            String key = bindingEntry.getKey();
            JsonElement value = bindingEntry.getValue();
            String stringValue = value.getAsJsonObject().getAsJsonPrimitive("value").getAsString();
            typedBinding.put(key, stringValue);
        }/*from w w  w  .  j a va  2  s .  co m*/
        typedBindingList.add(typedBinding);
    }
    return typedBindingList;
}

From source file:org.socraticgrid.kmrolib.SPARQLQueryUtil_KMRO10.java

License:Apache License

private String xmlResourceDescr(String resourceURI, JsonObject resourceDescrs, String indent, String tagAs,
        String globalId, HashMap<String, String> urisDescribed, boolean shallowOnly) throws Exception {
    String xmlReply = "";
    String oindent = indent;//from   ww w.  j a  va2 s .  co  m
    JsonObject resourceDescr = resourceDescrs.getAsJsonObject(resourceURI);
    if (resourceDescr == null)
        return "";
    Set<Map.Entry<String, JsonElement>> predValueMap = resourceDescr.entrySet();

    // rdf:type get special treatment - a processor version of this
    // dumper would key off type
    String pred = "rdf:type";
    // Assuming resource have only one type
    String value = resourceDescr.getAsJsonArray("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").get(0)
            .getAsJsonObject().getAsJsonPrimitive("value").getAsString();

    String typeValue = value.split("#")[1];

    if (tagAs == "IMPL")
        // no indent if standalone and this needs full xmlns
        if (indent == "")
            xmlReply += "\n" + indent + "<" + typeValue + "Impl xmlns=\"fact.adapter.nhinc.fha.hhs.gov.urn\">";
        else
            xmlReply += "\n" + indent + "<" + typeValue + "Impl>";
    else if (tagAs == "CONTAINS")
        xmlReply += "\n" + indent + "<contains xsi:type=\"" + typeValue
                + "\" xsi=\"http://www.w3.org/2001/XMLSchema-instance\">";

    indent += "\t";

    xmlReply += this.xmlDyInfo(indent, typeValue, globalId, false);
    urisDescribed.put(globalId, typeValue);

    for (Map.Entry<String, JsonElement> pvme : predValueMap) {

        // Handled rdf:type above.
        if (pvme.getKey().startsWith("http://www.w3.org"))
            continue;

        // take off: urn:gov:hhs:fha:nhinc:adapter
        pred = pvme.getKey().split("#")[1];

        // Assuming can have > 1 value
        // TBD: must add configuration file to dictate whether multiple values allowed or not.
        JsonArray values = pvme.getValue().getAsJsonArray();

        // All values in array have same type so just get from first
        // value
        JsonObject firstValue = values.get(0).getAsJsonObject();
        String valueType = firstValue.getAsJsonPrimitive("type").getAsString();
        String dataType = "";
        if (firstValue.has("datatype")) {
            dataType = firstValue.getAsJsonPrimitive("datatype").getAsString();
        }

        Iterator<JsonElement> valuesIterator = values.iterator();
        while (valuesIterator.hasNext()) {
            xmlReply += "\n" + indent + "<" + pred + ">";

            JsonObject sparqlValue = valuesIterator.next().getAsJsonObject();
            value = sparqlValue.getAsJsonPrimitive("value").getAsString();

            // A date - then type it (java.util.date?)
            if (dataType.matches("http://www.w3.org/2001/XMLSchema#dateTime")) {
                // Reverting to XML time but for reference leaving what
                // KMR wanted ("E, dd MMM yyyy HH:mm:ss.SSS Z");
                // Day, dayno month no year no hour min sec ...SSS? Z
                // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                // Date xmlDateIn = sdf.parse(value);
                // sdf.applyPattern("E, dd MMM yyyy HH:mm:ss.SSS Z");
                // xmlReply += sdf.format(xmlDateIn).toString();
                xmlReply += value;
            }
            // If reference to Blank Node/struct then recurse
            else if (valueType.matches("bnode")) {
                // Needs a global id
                String bnodeGlobalId = UUID.randomUUID().toString();
                String bnodeId = value;
                // as not explicitly tagging, don't indent for it
                xmlReply += xmlResourceDescr(bnodeId, resourceDescrs, indent, "", bnodeGlobalId, urisDescribed,
                        shallowOnly) + "\n" + indent;
            }
            // Distinguish pointers/references
            // 200 (Agent) and 2 (Patient) are exs of referenced things.
            else if (valueType.matches("uri")) {
                if (urisDescribed.get(value) != null)
                    xmlReply += this.xmlDyInfo(indent + "\t", urisDescribed.get(value), value, true);
                // will fetch: always dy info
                else if (shallowOnly) {
                    JsonObject listReply = this.requestJSON("SELECT ?t WHERE {<" + value + "> a ?t}");
                    JsonObject results = listReply.getAsJsonObject("results");
                    JsonArray bindings = results.getAsJsonArray("bindings");
                    JsonObject binding = bindings.get(0).getAsJsonObject();
                    String tValue = binding.getAsJsonObject("t").getAsJsonPrimitive("value").getAsString()
                            .split("#")[1];
                    xmlReply += this.xmlDyInfo(indent + "\t", tValue, value, true);
                    urisDescribed.put(value, tValue);
                } else {
                    JsonObject reply = this.requestJSON("DESCRIBE <" + value + ">");
                    // TBD: raise exception if no reply!
                    String processedReply = this.xmlDescriptions(reply, indent, "", false, "", urisDescribed,
                            shallowOnly);
                    xmlReply += processedReply;
                }
                xmlReply += "\n" + indent;
            }
            // Inlined values: string or Integer (KMR doesn't distinguish)
            else
                xmlReply += value;

            xmlReply += "</" + pred + ">";

        }
    }

    if (tagAs == "IMPL")
        xmlReply += "\n" + oindent + "</" + typeValue + "Impl" + ">";
    else if (tagAs == "CONTAINS")
        xmlReply += "\n" + oindent + "</contains>";

    return xmlReply;
}

From source file:org.socraticgrid.kmrolib.SPARQLQueryUtil_KMRO10.java

License:Apache License

private String xmlListOfType(JsonObject listReply, String type) throws Exception {

    String xmlReply = "";

    xmlReply = "<FactListImpl xmlns=\"fact.adapter.nhinc.fha.hhs.gov.urn\">\n";

    String indent = "\t";

    xmlReply += this.xmlDyInfo(indent, type, UUID.randomUUID().toString(), false) + "\r";

    JsonObject results = listReply.getAsJsonObject("results");
    JsonArray bindings = results.getAsJsonArray("bindings");
    Iterator<JsonElement> bindingsIterator = bindings.iterator();
    Object[] resourceDescriptions;
    while (bindingsIterator.hasNext()) {
        JsonObject binding = bindingsIterator.next().getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> bindingEntries = binding.entrySet();
        for (Map.Entry<String, JsonElement> bindingEntry : bindingEntries) {
            xmlReply += "\t<contains xsi:type=\"" + type
                    + "\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">";
            String key = bindingEntry.getKey();
            JsonElement value = bindingEntry.getValue();
            String stringValue = value.getAsJsonObject().getAsJsonPrimitive("value").getAsString();
            xmlReply += this.xmlDyInfo(indent + "\t", type, stringValue, true);
            xmlReply += "\n\t</contains>\n";
        }//  w  w  w.  ja  v a2s.c om
    }

    xmlReply += "\n</FactListImpl>\n";

    return xmlReply;
}

From source file:org.socraticgrid.workitemhandlers.communication.CommunicationHandlerConfigurationParser.java

License:Apache License

public CommunicationHandlerConfiguration parseString(String configString) {

    if (configString == null || !configString.contains(CONFIGURATION_SEPARATOR_STRING)) {
        throw new IllegalArgumentException("Malformed 'configuration' parameter: " + configString);
    }/*from  w  w  w  . j av  a 2s.c o  m*/

    //replace separator string
    //"[{"receiver": "actor1", "channel": "ALERT", "template": "template1", "timeout": "0s"}, {"receiver": "actor2", "channel": "ALERT", "template": "template2", "timeout": "120s"}]"
    configString = configString.replaceAll(CONFIGURATION_SEPARATOR_STRING, ",");

    CommunicationHandlerConfiguration configuration = new CommunicationHandlerConfiguration();
    List<String> receivers = new ArrayList<String>();
    List<String> channels = new ArrayList<String>();
    List<String> templates = new ArrayList<String>();
    List<String> timeouts = new ArrayList<String>();

    //parse the string
    JsonParser parser = new JsonParser();
    JsonElement parsedContent = parser.parse(configString);

    JsonArray array = parsedContent.getAsJsonArray();
    Iterator<JsonElement> iterator = array.iterator();
    while (iterator.hasNext()) {
        JsonObject jsonObject = (JsonObject) iterator.next();
        receivers.add(jsonObject.get("receiver").getAsString());
        channels.add(jsonObject.get("channel").getAsString());
        templates.add(jsonObject.get("template").getAsString());
        timeouts.add(jsonObject.get("timeout").getAsString());
    }

    configuration.setReceivers(receivers);
    configuration.setChannels(channels);
    configuration.setTemplates(templates);
    configuration.setTimeouts(timeouts);

    return configuration;
}

From source file:org.structr.web.auth.GitHubAuthClient.java

License:Open Source License

@Override
public String getCredential(final HttpServletRequest request) {

    OAuthResourceResponse userResponse = getUserResponse(request);

    if (userResponse == null) {

        return null;

    }/*from   www.  j  a v  a  2 s  .  c om*/

    String body = userResponse.getBody();
    logger.log(Level.FINE, "User response body: {0}", body);

    final JsonParser parser = new JsonParser();
    final JsonElement result = parser.parse(body);

    if (result instanceof JsonArray) {

        final JsonArray arr = (JsonArray) result;

        if (arr.iterator().hasNext()) {

            final JsonElement el = arr.iterator().next();

            final String address = el.getAsJsonObject().get("email").getAsString();
            logger.log(Level.INFO, "Got 'email' credential from GitHub: {0}", address);
            return address;
        }

    }

    return null;

}

From source file:org.wso2.carbon.databridge.commons.utils.EventConverterUtils.java

License:Open Source License

public static List<Event> convertFromJson(String json, String streamId, StreamDefinition streamDefinition) {
    if ((streamId == null || streamId.equals(""))) {
        String errorMsg = "Stream name cannot be null or empty";
        MalformedEventException malformedEventException = new MalformedEventException();
        if (log.isDebugEnabled()) {
            log.error(errorMsg, malformedEventException);
        } else {//from  w  w  w .  j  a v  a  2  s . c  o m
            log.error(errorMsg);
        }
        throw malformedEventException;
    }
    List<Event> eventList = new ArrayList<Event>();
    try {
        JsonParser jsonParser = new JsonParser();
        JSONArray eventObjects = new JSONArray(json);
        for (int i = 0; i < eventObjects.length(); i++) {
            Event event = new Event();
            JsonElement jsonElement = jsonParser.parse(eventObjects.get(i).toString());

            JsonObject jsonObject = (JsonObject) jsonElement;

            Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet();

            for (Map.Entry<String, JsonElement> entry : entries) {
                String key = entry.getKey();

                if (entry.getValue() instanceof JsonArray) {
                    List<Attribute> attributeList = streamDefinition.getAttributeListForKey(key);
                    if (attributeList == null) {
                        continue;
                    }

                    JsonArray jsonArray = (JsonArray) entry.getValue();
                    Iterator it = jsonArray.iterator();

                    List list = new ArrayList();
                    int pos = 0;
                    while (it.hasNext()) {
                        Object value = getValue(jsonParser.parse(it.next().toString()).getAsString(),
                                attributeList.get(pos).getType());
                        list.add(value);
                        pos++;
                    }
                    event.setData(key, list.toArray());
                }
            }
            event.setStreamId(streamId);
            eventList.add(event);
        }
    } catch (JSONException e) {
        String errorMsg = "Error converting JSON to event, for JSON : " + json;
        MalformedEventException malformedEventException = new MalformedEventException(errorMsg, e);
        if (log.isDebugEnabled()) {
            log.error(errorMsg, malformedEventException);
        } else {
            log.error(errorMsg);
        }
        throw malformedEventException;
    }
    return eventList;
}

From source file:org.xenmaster.web.APICallDecoder.java

License:Open Source License

@Override
public APICall deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (!json.isJsonObject()) {
        throw new IllegalArgumentException("Invalid JSON Apic object");
    }//from w  w  w  .j av  a 2  s.c  o m
    JsonObject obj = (JsonObject) json;
    APICall apic = new APICall();
    for (Entry<String, JsonElement> e : obj.entrySet()) {
        switch (e.getKey()) {
        case "ref":
            if (e.getValue() != null && !(e.getValue() instanceof JsonNull)) {
                apic.ref = e.getValue().getAsString();
            }
            break;
        case "args":
            if (e.getValue().isJsonArray()) {
                JsonArray arr = e.getValue().getAsJsonArray();
                ArrayList<Object> args = new ArrayList<>(arr.size());
                for (Iterator<JsonElement> it = arr.iterator(); it.hasNext();) {
                    args.add(deserialize(it.next()));
                }
                apic.args = args.toArray();
            } else {
                apic.args = null;
            }
            break;
        }
    }
    return apic;
}