Example usage for com.google.gson JsonElement getAsJsonArray

List of usage examples for com.google.gson JsonElement getAsJsonArray

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsJsonArray.

Prototype

public JsonArray getAsJsonArray() 

Source Link

Document

convenience method to get this element as a JsonArray .

Usage

From source file:com.ibm.watson.apis.conversation_enhanced.retrieve_and_rank.Client.java

License:Open Source License

/**
 * Helper Method to include highlighting information along with the retrieve and rank response so
 * the final payload includes id,title,highlight,body,sourceUrl as json key value pairs.
 * /*from  ww w . j ava 2 s .c  o m*/
 * @param input The user's query sent to the retrieve and rank service
 * @param results The results obtained from a call to the retrieve and rank service with
 *        <code>input</code> as the query
 * @param highlights SOLR highlighting information obtained from a call to the retrieve and rank
 *        service
 * @return A list of DocumentPayload objects, each representing a single document the retrieve and
 *         rank service believes is a possible answer to the user's query
 */
private List<DocumentPayload> createPayload(String input, String results, String highlights) {
    logger.info(Messages.getString("Service.CREATING_RNR_PAYLOAD")); //$NON-NLS-1$
    List<DocumentPayload> payload = new ArrayList<DocumentPayload>();
    HashMap<String, Integer> hm = new HashMap<String, Integer>();
    JsonElement jelement = new JsonParser().parse(results);
    JsonArray jarray = jelement.getAsJsonArray();
    for (int i = 0; i < jarray.size(); i++) {
        DocumentPayload documentPayload = new DocumentPayload();
        String id = jarray.get(i).getAsJsonObject().get(Constants.SCHEMA_FIELD_ID).toString().replaceAll("\"", //$NON-NLS-1$
                ""); //$NON-NLS-1$
        documentPayload.setId(id);
        documentPayload.setTitle(jarray.get(i).getAsJsonObject().get(Constants.SCHEMA_FIELD_TITLE).toString()
                .replaceAll("\"", "")); //$NON-NLS-1$ //$NON-NLS-2$
        if (jarray.get(i).getAsJsonObject().get(Constants.SCHEMA_FIELD_BODY) != null) {
            documentPayload.setBody(
                    // This method limits the response text in this sample app to two paragraphs.
                    limitParagraph(jarray.get(i).getAsJsonObject().get(Constants.SCHEMA_FIELD_BODY).toString()
                            .replaceAll("\"", ""))); //$NON-NLS-1$ //$NON-NLS-2$
        } else {
            documentPayload.setBody("empty"); //$NON-NLS-1$
        }
        if (jarray.get(i).getAsJsonObject().get(Constants.SCHEMA_FIELD_SOURCE_URL) == null) {
            documentPayload.setSourceUrl("empty"); //$NON-NLS-1$
        } else {
            documentPayload.setSourceUrl(jarray.get(i).getAsJsonObject().get(Constants.SCHEMA_FIELD_SOURCE_URL)
                    .toString().replaceAll("\"", "")); //$NON-NLS-1$ //$NON-NLS-2$
        }
        if (jarray.get(i).getAsJsonObject().get(Constants.SCHEMA_FIELD_CONFIDENCE) != null) {
            documentPayload.setConfidence(jarray.get(i).getAsJsonObject().get(Constants.SCHEMA_FIELD_CONFIDENCE)
                    .toString().replaceAll("\"", "")); //$NON-NLS-1$ //$NON-NLS-2$
        } else {
            documentPayload.setConfidence("0.0"); //$NON-NLS-1$
        }
        payload.add(i, documentPayload);
        hm.put(id, i);
    }
    jelement = new JsonParser().parse(highlights);
    JsonObject highlight = jelement.getAsJsonObject();
    // Add highlighting information
    Set<Map.Entry<String, JsonElement>> entrySet = highlight.entrySet();
    for (Map.Entry<String, JsonElement> entry : entrySet) {
        String docid = entry.getKey();
        String highlighted = ""; //$NON-NLS-1$
        if (entry.getValue().getAsJsonObject().get(Constants.SCHEMA_FIELD_BODY) != null) {
            highlighted = entry.getValue().getAsJsonObject().get(Constants.SCHEMA_FIELD_BODY).getAsJsonArray()
                    .get(0).toString();
        }
        if (hm.get(docid) != null)
            payload.get(hm.get(docid)).setHighlight(highlighted);
    }
    return payload;
}

From source file:com.ibm.watson.apis.conversation_with_discovery.discovery.DiscoveryClient.java

License:Open Source License

/**
 * Helper Method to include highlighting information along with the Discovery response so the final payload
 * includes id,title,body,sourceUrl as json key value pairs.
 *
 * @param resultsElement the results element
 * @return A list of DocumentPayload objects, each representing a single document the discovery service believes is a
 *         possible answer to the user's query
 *//*from   w ww. j  a va2  s.co  m*/
private List<DocumentPayload> createPayload(JsonElement resultsElement) {
    logger.info(Messages.getString("Service.CREATING_DISCOVERY_PAYLOAD"));
    List<DocumentPayload> payload = new ArrayList<DocumentPayload>();
    JsonArray jarray = resultsElement.getAsJsonArray();

    for (int i = 0; (i < jarray.size()) && (i < Constants.DISCOVERY_MAX_SEARCH_RESULTS_TO_SHOW); i++) {
        DocumentPayload documentPayload = new DocumentPayload();
        String id = jarray.get(i).getAsJsonObject().get(Constants.DISCOVERY_FIELD_ID).toString()
                .replaceAll("\"", "");
        documentPayload.setId(id);
        documentPayload.setTitle(jarray.get(i).getAsJsonObject().get(Constants.DISCOVERY_FIELD_TITLE).toString()
                .replaceAll("\"", ""));
        if (jarray.get(i).getAsJsonObject().get(Constants.DISCOVERY_FIELD_BODY) != null) {
            String body = jarray.get(i).getAsJsonObject().get(Constants.DISCOVERY_FIELD_BODY).toString()
                    .replaceAll("\"", "");

            // This method limits the response text in this sample
            // app to two paragraphs.
            String bodyTwoPara = limitParagraph(body);
            documentPayload.setBody(bodyTwoPara);
            documentPayload.setBodySnippet(getSniplet(body));

        } else {
            documentPayload.setBody("empty");
        }
        if (jarray.get(i).getAsJsonObject().get(Constants.DISCOVERY_FIELD_SOURCE_URL) == null) {
            documentPayload.setSourceUrl("empty");
        } else {
            documentPayload.setSourceUrl(jarray.get(i).getAsJsonObject()
                    .get(Constants.DISCOVERY_FIELD_SOURCE_URL).toString().replaceAll("\"", ""));
        }
        if (jarray.get(i).getAsJsonObject().get(Constants.DISCOVERY_FIELD_CONFIDENCE) != null) {
            documentPayload.setConfidence(jarray.get(i).getAsJsonObject()
                    .get(Constants.DISCOVERY_FIELD_CONFIDENCE).toString().replaceAll("\"", ""));
        } else {
            documentPayload.setConfidence("0.0");
        }
        payload.add(i, documentPayload);
    }

    return payload;
}

From source file:com.ibm.watson.app.common.services.general.impl.DefaultConfigurationServiceImpl.java

License:Open Source License

public DefaultConfigurationServiceImpl() {
    // First read properties to get all defaults
    String props = System.getProperty("wim.config.service.properties");
    InputStream is = null;/*from w  w w  . j a v a 2 s.com*/
    if (props != null) {
        try {
            is = new FileInputStream(props);
        } catch (IOException e) {
        }
    } else {
        is = getClass().getResourceAsStream("/properties/config_service.properties");
    }

    if (is != null) {
        Properties p = new Properties();
        try {
            p.load(is);
            for (Object k : p.keySet()) {
                properties.put((String) k, p.getProperty((String) k));
            }
        } catch (IOException e) {

        } finally {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
    // Read VCAP_SERVICES and override properties
    final String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
    if (VCAP_SERVICES != null) {
        if (logger.isDebugEnabled())
            logger.debug("VCAP_SERVICES is : " + VCAP_SERVICES);
        JsonParser parser = new JsonParser();
        JsonElement e = parser.parse(VCAP_SERVICES);
        JsonElement sqle = e.getAsJsonObject().get("sqldb");
        if (sqle != null) {
            sqle = sqle.getAsJsonArray().get(0);
            properties.put("db.name", sqle.getAsJsonObject().get("name").getAsString());
            properties.put("db.type", "sqldb");
        }
        JsonElement nlce = e.getAsJsonObject().get("natural_language_classifier.dev");
        if (nlce != null) {
            nlce = nlce.getAsJsonArray().get(0);
            nlce = nlce.getAsJsonObject().get("credentials");
            properties.put("nlclassifier.url", nlce.getAsJsonObject().get("url").getAsString());
            properties.put("nlclassifier.username", nlce.getAsJsonObject().get("username").getAsString());
            properties.put("nlclassifier.password", nlce.getAsJsonObject().get("password").getAsString());
        }
    }

    if (logger.isDebugEnabled())
        logger.debug("Resolved the following Properites " + properties);
}

From source file:com.ibm.watson.app.common.services.impl.BluemixServicesConfigurationParser.java

License:Open Source License

public void parseAndRegisterServices(JsonElement json) {
    Objects.requireNonNull(json, MessageKey.AQWEGA14019E_json_element_null.getMessage().getFormattedMessage());
    if (!json.isJsonObject()) {
        throw new JsonParseException(MessageKey.AQWEGA14001E_expected_json_object_parse_bluemix_service_conf
                .getMessage().getFormattedMessage());
    }//from ww  w  .  j a  v a 2  s . c  o m

    final boolean isTrace = logger.isTraceEnabled();

    for (Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
        final String serviceKey = entry.getKey();
        final JsonElement serviceConfigArray = entry.getValue();
        if (!serviceConfigArray.isJsonArray()) {
            throw new JsonParseException(MessageKey.AQWEGA14002E_expected_json_array_while_parsing_config_1
                    .getMessage(serviceKey).getFormattedMessage());
        }

        BluemixServiceInfo<? extends BluemixConfiguredService> service = BluemixServicesBinder
                .getBluemixServiceByName(serviceKey);
        if (service == null) {
            logger.warn(MessageKey.AQWEGA12001W_unexpected_conf_supplied_for_service_ignore_1
                    .getMessage(serviceKey));
            continue;
        }

        if (isTrace) {
            logger.trace("Loading configuration for service '" + serviceKey + "'");
        }

        for (JsonElement serviceInstanceConfig : serviceConfigArray.getAsJsonArray()) {
            try {
                BluemixConfiguredService serviceImpl = service.serviceImpl.getConstructor().newInstance();
                serviceImpl
                        .setConfig(gson.fromJson(serviceInstanceConfig, serviceImpl.getConfigurationClass()));
                serviceImpl.initialize();
                register(service, serviceImpl);
            } catch (IllegalAccessException | InstantiationException | IllegalArgumentException
                    | InvocationTargetException | NoSuchMethodException | SecurityException e) {
                logger.warn(MessageKey.AQWEGA12002W_unable_register_service_error_2.getMessage(serviceKey,
                        e.getMessage()));
                logger.catching(Level.DEBUG, e);
            }
        }
    }
}

From source file:com.ibm.watson.developer_cloud.speech_to_text.v1.deserializer.SpeechTimestampDeserializer.java

License:Open Source License

@Override
public ArrayList<SpeechTimestamp> deserialize(JsonElement json, Type typeOfT,
        JsonDeserializationContext context) throws JsonParseException {
    ArrayList<SpeechTimestamp> list = new ArrayList<SpeechTimestamp>() {
    };//from   w  w w .  ja  v  a 2s  .  c  o m

    for (JsonElement element : json.getAsJsonArray()) {
        String word = element.getAsJsonArray().get(0).getAsString();
        float start = element.getAsJsonArray().get(1).getAsFloat();
        float end = element.getAsJsonArray().get(2).getAsFloat();

        SpeechTimestamp timestamp = new SpeechTimestamp();
        timestamp.setWord(word);
        timestamp.setStart(start);
        timestamp.setEnd(end);

        list.add(timestamp);
    }

    return list;
}

From source file:com.ibm.watson.developer_cloud.speech_to_text.v1.deserializer.SpeechWordConfidenceDeserializer.java

License:Open Source License

@Override
public ArrayList<SpeechWordConfidence> deserialize(JsonElement json, Type typeOfT,
        JsonDeserializationContext context) throws JsonParseException {
    ArrayList<SpeechWordConfidence> list = new ArrayList<SpeechWordConfidence>() {
    };//w w  w.  j a v  a 2s.  c  o m

    for (JsonElement element : json.getAsJsonArray()) {
        String word = element.getAsJsonArray().get(0).getAsString();
        float confidence = element.getAsJsonArray().get(1).getAsFloat();

        SpeechWordConfidence wordConfidence = new SpeechWordConfidence();
        wordConfidence.setWord(word);
        wordConfidence.setConfidence(confidence);

        list.add(wordConfidence);
    }

    return list;
}

From source file:com.ikanow.infinit.e.data_model.custom.InfiniteFileInputJsonParser.java

License:Apache License

private BasicDBObject getDocumentFromJson(boolean bRecursing) throws IOException {
    if (!_inSecondaryObject) {
        reader.beginObject();//from   www . j av a 2s.c om
        _inSecondaryObject = true;
    }

    while (reader.hasNext()) {
        String name = reader.nextName();

        boolean bMatch = false;
        if (bRecursing) {
            bMatch = recursiveObjectIdentifiers.contains(name.toLowerCase());
        } else {
            bMatch = objectIdentifiers.contains(name.toLowerCase());
        } //TESTED

        if (bMatch) {
            JsonElement meta = parser.parse(reader);

            if (meta.isJsonObject()) {

                BasicDBObject currObj = convertJsonToDocument(meta);
                if (null != currObj) {
                    return currObj;
                }
            } //TESTED
            else if (meta.isJsonArray()) {
                _secondaryArray = meta.getAsJsonArray();
                _posInSecondaryArray = 0;
                for (JsonElement meta2 : _secondaryArray) {
                    _posInSecondaryArray++;
                    BasicDBObject currObj = convertJsonToDocument(meta2);
                    if (null != currObj) {
                        return currObj;
                    }
                }
                _secondaryArray = null;
            } //TESTED

        } //TESTED
        else {
            if (bRecurse) { //TODO (INF-2469): Not currently supported, it gets a bit tricky? (need to convert to a stack)

                JsonToken tok = reader.peek();
                if (JsonToken.BEGIN_OBJECT == tok) {
                    BasicDBObject currObj = getDocumentFromJson(true);
                    if (null != currObj) {
                        return currObj;
                    }
                } //TESTED
                else if (JsonToken.BEGIN_ARRAY == tok) {
                    reader.beginArray();
                    while (reader.hasNext()) {
                        JsonToken tok2 = reader.peek();

                        if (JsonToken.BEGIN_OBJECT == tok2) {
                            BasicDBObject currObj = getDocumentFromJson(true);
                            if (null != currObj) {
                                return currObj;
                            }
                        } else {
                            reader.skipValue();
                        } //TESTED

                    } //TESTED      
                    reader.endArray();
                } else {
                    reader.skipValue();
                } //TESTED
            } else {
                reader.skipValue();
            } //TESTED
        }

    } //(end loop over reader)

    reader.endObject();
    _inSecondaryObject = false;

    return null;

}

From source file:com.ikanow.infinit.e.data_model.custom.InfiniteFileInputJsonParser.java

License:Apache License

private String getKey(JsonElement meta, String key, boolean bPrimitiveOnly) {
    try {/*  w w  w  .  j av  a 2s. c o m*/
        String[] components = key.split("\\.");
        JsonObject metaObj = meta.getAsJsonObject();
        for (String comp : components) {
            meta = metaObj.get(comp);

            if (null == meta) {
                return null;
            } //TESTED
            else if (meta.isJsonObject()) {
                metaObj = meta.getAsJsonObject();
            } //TESTED
            else if (meta.isJsonPrimitive()) {
                return meta.getAsString();
            } //TESTED
            else if (bPrimitiveOnly) { // (meta isn't allowed to be an array, then you'd have too many primary keys!)
                return null;
            } //TOTEST (? - see JsonToMetadataParser)
            else { // Check with first instance
                JsonArray array = meta.getAsJsonArray();
                meta = array.get(0);
                if (meta.isJsonObject()) {
                    metaObj = meta.getAsJsonObject();
                }
            } //TESTED            
        }
        if (!bPrimitiveOnly) { // allow objects, we just care if the field exists...
            if (null != metaObj) {
                return "[Object]";
            }
        } //TESTED
    } catch (Exception e) {
    } // no primary key

    return null;
}

From source file:com.ikanow.infinit.e.data_model.custom.InfiniteFileInputJsonParser.java

License:Apache License

static public BasicDBObject convertJsonObjectToBson(JsonObject json, boolean bHtmlUnescape) {
    int length = json.entrySet().size();
    BasicDBObject list = new BasicDBObject(capacity(length));
    for (Map.Entry<String, JsonElement> jsonKeyEl : json.entrySet()) {
        JsonElement jsonEl = jsonKeyEl.getValue();
        if (jsonEl.isJsonArray()) {
            list.put(jsonKeyEl.getKey(), handleJsonArray(jsonEl.getAsJsonArray(), bHtmlUnescape));
        } else if (jsonEl.isJsonObject()) {
            list.put(jsonKeyEl.getKey(), convertJsonObjectToBson(jsonEl.getAsJsonObject(), bHtmlUnescape));
        } else if (jsonEl.isJsonPrimitive()) {
            if (bHtmlUnescape) {
                list.put(jsonKeyEl.getKey(), StringEscapeUtils.unescapeHtml(jsonEl.getAsString()));
            } else {
                list.put(jsonKeyEl.getKey(), jsonEl.getAsString());
            }//from  www  .  j a v  a 2  s  . c o m
        }
    }
    if (list.size() > 0) {
        return list;
    }
    return null;
}

From source file:com.ikanow.infinit.e.data_model.custom.InfiniteFileInputJsonParser.java

License:Apache License

static private Object[] handleJsonArray(JsonArray jarray, boolean bHtmlUnescape) {
    Object o[] = new Object[jarray.size()];
    for (int i = 0; i < jarray.size(); i++) {
        JsonElement jsonEl = jarray.get(i);
        if (jsonEl.isJsonObject()) {
            o[i] = convertJsonObjectToBson(jsonEl.getAsJsonObject(), bHtmlUnescape);
        }//from w  ww  .  java  2  s  .c  o m
        if (jsonEl.isJsonArray()) {
            o[i] = handleJsonArray(jsonEl.getAsJsonArray(), bHtmlUnescape);
        } else if (jsonEl.isJsonPrimitive()) {
            if (bHtmlUnescape) {
                o[i] = StringEscapeUtils.unescapeHtml(jsonEl.getAsString());
            } else {
                o[i] = jsonEl.getAsString();
            }
        }
    }
    return o;
}