Example usage for com.google.gson JsonPrimitive getAsString

List of usage examples for com.google.gson JsonPrimitive getAsString

Introduction

In this page you can find the example usage for com.google.gson JsonPrimitive getAsString.

Prototype

@Override
public String getAsString() 

Source Link

Document

convenience method to get this element as a String.

Usage

From source file:com.ibm.common.activitystreams.internal.LinkValueAdapter.java

License:Apache License

/**
 * Method deserialize.//  ww  w  . jav  a 2s.c  o  m
 * @param el JsonElement
 * @param type Type
 * @param context JsonDeserializationContext
        
        
        
 * @return LinkValue * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */
public LinkValue deserialize(JsonElement el, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    checkArgument(el.isJsonArray() || el.isJsonObject() || el.isJsonPrimitive());
    if (el.isJsonArray()) {
        LinkValue.ArrayLinkValue.Builder builder = linkValues();
        for (JsonElement aryel : el.getAsJsonArray())
            builder.add(context.<LinkValue>deserialize(aryel, LinkValue.class));
        return builder.get();
    } else if (el.isJsonObject()) {
        JsonObject obj = el.getAsJsonObject();
        if (obj.has("objectType")) {
            TypeValue tv = context.deserialize(obj.get("objectType"), TypeValue.class);
            Model pMap = schema.forObjectType(tv.id());
            return context.deserialize(el, pMap != null && pMap.type() != null ? pMap.type() : ASObject.class);
        } else {
            return context.deserialize(el, ASObject.class);
        }
    } else {
        JsonPrimitive prim = el.getAsJsonPrimitive();
        checkArgument(prim.isString());
        return linkValue(prim.getAsString());
    }
}

From source file:com.ibm.common.activitystreams.internal.NaturalLanguageValueAdapter.java

License:Apache License

/**
 * Method deserialize.//from   w ww.j  a va 2  s.  co  m
 * @param element JsonElement
 * @param type1 Type
 * @param context JsonDeserializationContext
        
        
        
 * @return NLV * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */
public NLV deserialize(JsonElement element, Type type1, JsonDeserializationContext context)
        throws JsonParseException {
    checkArgument(element.isJsonPrimitive() || element.isJsonObject());
    if (element.isJsonPrimitive()) {
        JsonPrimitive prim = element.getAsJsonPrimitive();
        checkArgument(prim.isString());
        return NLV.SimpleNLV.make(prim.getAsString());
    } else {
        try {
            JsonObject obj = element.getAsJsonObject();
            NLV.MapNLV.Builder builder = NLV.MapNLV.make();
            for (Entry<String, JsonElement> entry : obj.entrySet())
                builder.set(entry.getKey(), entry.getValue().getAsString());
            return builder.get();
        } catch (Throwable t) {
            throw new IllegalArgumentException();
        }
    }
}

From source file:com.ibm.common.activitystreams.internal.TypeValueAdapter.java

License:Apache License

/**
 * Method deserialize./*from   w w w . j ava 2  s  . c om*/
 * @param el JsonElement
 * @param type Type
 * @param context JsonDeserializationContext
        
        
        
 * @return TypeValue * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */
public TypeValue deserialize(JsonElement el, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    checkArgument(el.isJsonPrimitive() || el.isJsonObject());
    if (el.isJsonPrimitive()) {
        JsonPrimitive prim = el.getAsJsonPrimitive();
        checkArgument(prim.isString());
        return type(prim.getAsString());
    } else {
        JsonObject obj = el.getAsJsonObject();
        if (obj.has("objectType")) {
            TypeValue tv = context.deserialize(obj.get("objectType"), TypeValue.class);
            Model pMap = schema.forObjectType(tv.id());
            return context.<ASObject>deserialize(el, pMap.type() != null ? pMap.type() : ASObject.class);
        } else {
            return context.<ASObject>deserialize(el, ASObject.class);
        }
    }
}

From source file:com.ibm.g11n.pipeline.client.ServiceAccount.java

License:Open Source License

/**
 * Returns an instance of ServiceAccount for a JsonArray in the VCAP_SERVICES environment.
 * <p>//from  w  ww.ja v  a 2 s  . c  o m
 * This method is called from {@link #getInstanceByVcapServices(String, String)}.
 * 
 * @param jsonArray
 *          The candidate JSON array which may include valid credentials.
 * @param serviceInstanceName
 *          The name of IBM Globalization Pipeline service instance, or null
 *          designating the first available service instance.
 * @return  An instance of ServiceAccount. This method returns null if no matching service
 *          instance name was found (when serviceInstanceName is null), or no valid
 *          credential data was found. 
 */
private static ServiceAccount parseToServiceAccount(JsonArray jsonArray, String serviceInstanceName) {
    ServiceAccount account = null;
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonObject gpObj = jsonArray.get(i).getAsJsonObject();
        if (serviceInstanceName != null) {
            // When service instance name is specified,
            // this method returns only a matching entry
            JsonPrimitive name = gpObj.getAsJsonPrimitive("name");
            if (name == null || !serviceInstanceName.equals(name.getAsString())) {
                continue;
            }
        }
        JsonObject credentials = gpObj.getAsJsonObject("credentials");
        if (credentials == null) {
            continue;
        }
        JsonPrimitive jsonUrl = credentials.getAsJsonPrimitive("url");
        JsonPrimitive jsonInstanceId = credentials.getAsJsonPrimitive("instanceId");
        JsonPrimitive jsonUserId = credentials.getAsJsonPrimitive("userId");
        JsonPrimitive jsonPassword = credentials.getAsJsonPrimitive("password");

        if (jsonUrl != null && jsonInstanceId != null && jsonUserId != null & jsonPassword != null) {
            account = getInstance(jsonUrl.getAsString(), jsonInstanceId.getAsString(), jsonUserId.getAsString(),
                    jsonPassword.getAsString());
            logger.config("A ServiceAccount is created from VCAP_SERVICES: url=" + jsonUrl + ", instanceId="
                    + jsonInstanceId + ", userId=" + jsonUserId + ", password=***");
            break;
        }
    }

    return account;
}

From source file:com.ibm.gaas.ServiceAccount.java

License:Open Source License

/**
 * Returns an instance of ServiceAccount from the VCAP_SERVICES environment
 * variable. When <code>serviceInstanceName</code> is null, this method returns
 * a ServiceAccount for the first valid IBM Globlization service instance.
 * If <code>serviceInstanceName</code> is not null, this method look up a
 * matching service entry, and returns a ServiceAccount for the matching entry.
 * If <code>serviceInstanceName</code> is not null and there is no match,
 * this method returns null./*from   w  ww .ja  v  a  2  s.  c o  m*/
 * 
 * @param serviceInstanceName
 *          The name of the IBM Globalization service instance, or null
 *          designating the first available service instance.
 * @return  An instance of ServiceAccount for the specified service instance
 *          name, or null.
 */
private static ServiceAccount getInstanceByVcapServices(String serviceInstanceName) {
    Map<String, String> env = System.getenv();
    String vcapServices = env.get("VCAP_SERVICES");
    if (vcapServices == null) {
        return null;
    }

    ServiceAccount account = null;
    try {
        JsonObject obj = new JsonParser().parse(vcapServices).getAsJsonObject();
        JsonArray gaasArray = obj.getAsJsonArray(GAAS_SERVICE_NAME);
        if (gaasArray != null) {
            for (int i = 0; i < gaasArray.size(); i++) {
                JsonObject gaasEntry = gaasArray.get(i).getAsJsonObject();
                if (serviceInstanceName != null) {
                    // When service instance name is specified,
                    // this method returns only a matching entry
                    JsonPrimitive name = gaasEntry.getAsJsonPrimitive("name");
                    if (name == null || !serviceInstanceName.equals(name.getAsString())) {
                        continue;
                    }
                }
                JsonObject credentials = gaasEntry.getAsJsonObject("credentials");
                if (credentials == null) {
                    continue;
                }
                JsonPrimitive jsonUri = credentials.getAsJsonPrimitive("uri");
                JsonPrimitive jsonApiKey = credentials.getAsJsonPrimitive("api_key");
                if (jsonUri != null && jsonApiKey != null) {
                    logger.info(
                            "A ServiceAccount is created from VCAP_SERVICES: uri=" + jsonUri + ", api_key=***");
                    account = getInstance(jsonUri.getAsString(), jsonApiKey.getAsString());
                    break;
                }
            }
        }
    } catch (JsonParseException e) {
        // Fall through - will return null
    }

    return account;
}

From source file:com.ibm.mil.readyapps.summit.utilities.Utils.java

License:Open Source License

private static JsonElement getJsonPrimitive(String json) {
    JsonParser parser = new JsonParser();
    JsonObject jsonObject = parser.parse(json).getAsJsonObject();
    JsonPrimitive jsonPrimitive = jsonObject.getAsJsonPrimitive("result");
    return parser.parse(jsonPrimitive.getAsString());
}

From source file:com.ibm.streamsx.topology.generator.spl.SubmissionTimeValue.java

License:Open Source License

/**
 * Create a main composite to represent a submission parameter.
 * /*from   w w  w .  j  a  va  2 s .com*/
 * A parameter with name width,  type int32 default 3 is mapped to in the main composite:
 * 
 * expression<int32> $__spl_stv_width : (int32) getSubmissionTimeValue("width", "3");
 * 
 */
private void addMainCompositeParam(JsonObject params, JsonObject param) {

    JsonObject spv = jobject(param, "value");
    String spname = jstring(spv, "name");
    String metaType = jstring(spv, "metaType");
    String cpname = mkCompositeParamName(spname);

    JsonObject cp = new JsonObject();
    cp.addProperty("type", TYPE_COMPOSITE_PARAMETER);

    JsonObject cpv = new JsonObject();
    cpv.addProperty("name", cpname);
    cpv.addProperty("metaType", metaType);

    String splspname = SPLGenerator.stringLiteral(spname);
    String splType = Types.metaTypeToSPL(metaType);

    String cpdv;
    if (!spv.has("defaultValue")) {
        cpdv = String.format("(%s) getSubmissionTimeValue(%s)", splType, splspname);
    } else {
        JsonPrimitive defaultValueJson = spv.get("defaultValue").getAsJsonPrimitive();
        String defaultValue;

        if (metaType.startsWith("UINT")) {
            StringBuilder sbunsigned = new StringBuilder();
            sbunsigned.append("(rstring) ");
            SPLGenerator.numberLiteral(sbunsigned, defaultValueJson, metaType);
            defaultValue = sbunsigned.toString();
        } else {
            defaultValue = SPLGenerator.stringLiteral(defaultValueJson.getAsString());
        }

        cpdv = String.format("(%s) getSubmissionTimeValue(%s, %s)", splType, splspname, defaultValue);
    }
    cpv.addProperty("defaultValue", cpdv);

    cp.add("value", cpv);

    params.add(cpname, cp);
    submissionMainCompositeParams.put(spname, cp);
}

From source file:com.ibm.streamsx.topology.generator.spl.SubmissionTimeValue.java

License:Open Source License

/**
 * Generate a submission time value SPL param value definition
 * in a main composite.// w w  w .j  av a 2s .  co  m
 * <p>
 * e.g.,
 * <pre>{@code
 *  param
 *      expression<uint32> $__jaa_stv_foo : (uint32) getSubmissionTimeValue("foo", 3)
 * }</pre>
 * @param spval JSONObject for the submission parameter's value
 * @param sb
 */
void generateMainDef(JsonObject spval, StringBuilder sb) {
    String paramName = generateCompositeParamReference(spval);
    String spName = SPLGenerator.stringLiteral(jstring(spval, "name"));
    String metaType = jstring(spval, "metaType");
    String splType = Types.metaTypeToSPL(metaType);

    sb.append(String.format("expression<%s> %s : ", splType, paramName));
    if (!spval.has("defaultValue")) {
        sb.append(String.format("(%s) getSubmissionTimeValue(%s)", splType, spName));
    } else {
        JsonPrimitive defaultValueJson = spval.get("defaultValue").getAsJsonPrimitive();
        String defaultValue;

        if (metaType.startsWith("UINT")) {
            StringBuilder sbunsigned = new StringBuilder();
            sbunsigned.append("(rstring) ");
            SPLGenerator.numberLiteral(sbunsigned, defaultValueJson, metaType);
            defaultValue = sbunsigned.toString();
        } else {
            defaultValue = SPLGenerator.stringLiteral(defaultValueJson.getAsString());
        }

        sb.append(String.format("(%s) getSubmissionTimeValue(%s, %s)", splType, spName, defaultValue));
    }
}

From source file:com.iheart.quickio.client.QuickIo.java

License:Open Source License

private void move(final JsonElement json) {
    if (!json.isJsonPrimitive()) {
        return;//from   w w w .j ava 2  s  . c o  m
    }

    JsonPrimitive pr = json.getAsJsonPrimitive();
    if (!pr.isString()) {
        return;
    }

    this.reconnect(pr.getAsString());
}

From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java

License:Apache License

private ObjectId createCustomPluginTask(CustomMapReduceJobPojo taskConfig, Collection<String> dependencies,
        Collection<ObjectId> communities, ResponseObject response, boolean bUpdate) {
    ObjectId retVal = null;//from   www.  j a  v a  2s  .co  m
    try {
        StringBuffer url = new StringBuffer(apiRoot).append("custom/mapreduce/");
        if (bUpdate) {
            if (taskConfig._id != null) {
                url.append("updatejob/").append(taskConfig._id.toString()).append("/");
            } else {
                url.append("updatejob/").append(taskConfig.jobtitle).append("/");
                taskConfig.jobtitle = null;
            } //TESTED
        } else {
            url.append("schedulejob/");
        }
        if (null != communities) {
            for (ObjectId communityId : communities) {
                url.append(communityId.toString()).append(',');
            }
            url.setLength(url.length() - 1);
        } else {
            url.append("null");
        }
        url.append('/');

        if ((null != taskConfig.jobDependencies) && !taskConfig.jobDependencies.isEmpty()) {
            for (ObjectId jobId : taskConfig.jobDependencies) {
                url.append(jobId.toString()).append(',');
            }
            url.setLength(url.length() - 1);
        } else if ((null != dependencies) && !dependencies.isEmpty()) {
            for (String jobTitle : dependencies) {
                url.append(jobTitle).append(',');
            }
            url.setLength(url.length() - 1);
        } else {
            url.append("null");
        }
        url.append("/");

        // "nextRunTime"==first Schedule (date)
        if (null != taskConfig.firstSchedule) {
            taskConfig.nextRunTime = taskConfig.firstSchedule.getTime();
        }

        String json = sendRequest(url.toString(), ApiManager.mapToApi(taskConfig, null));
        ResponsePojo internal_responsePojo = ResponsePojo.fromApi(json, ResponsePojo.class);
        ResponseObject internal_ro = internal_responsePojo.getResponse();
        response = shallowCopy(response, internal_ro);

        if (response.isSuccess()) {
            JsonPrimitive retValObj = (JsonPrimitive) internal_responsePojo.getData();
            retVal = new ObjectId(retValObj.getAsString());
        }
    } catch (Exception e) {
        response.setSuccess(false);
        response.setMessage(e.getMessage());
    }
    return retVal;
}