List of usage examples for com.google.gson JsonObject getAsJsonPrimitive
public JsonPrimitive getAsJsonPrimitive(String memberName)
From source file:com.stackmob.sdk.push.StackMobPushTokenDeserializer.java
License:Apache License
public StackMobPushToken deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { JsonObject obj = json.getAsJsonObject(); JsonPrimitive tokenStringPrimitive = obj.getAsJsonPrimitive("token"); String tokenString = tokenStringPrimitive.getAsString(); JsonPrimitive tokenTypePrimitive = obj.getAsJsonPrimitive("type"); StackMobPushToken.TokenType tokenType = StackMobPushToken.TokenType .valueOf(tokenTypePrimitive.getAsString()); JsonPrimitive registeredMSPrimitive = obj.getAsJsonPrimitive("registered_milliseconds"); long registeredMS = registeredMSPrimitive.getAsInt(); return new StackMobPushToken(tokenString, tokenType, registeredMS); }
From source file:com.streamsets.pipeline.stage.destination.elasticsearch.ElasticsearchTarget.java
License:Apache License
private List<ErrorItem> extractErrorItems(JsonObject json) { List<ErrorItem> errorItems = new ArrayList<>(); JsonArray items = json.getAsJsonArray("items"); for (int i = 0; i < items.size(); i++) { JsonObject item = items.get(i).getAsJsonObject().entrySet().iterator().next().getValue() .getAsJsonObject();//w ww .ja v a2 s . c o m int status = item.get("status").getAsInt(); if (status >= 400) { Object error = item.get("error"); // In some old versions, "error" is a simple string not a json object. if (error instanceof JsonObject) { errorItems.add(new ErrorItem(i, item.getAsJsonObject("error").get("reason").getAsString())); } else if (error instanceof JsonPrimitive) { errorItems.add(new ErrorItem(i, item.getAsJsonPrimitive("error").getAsString())); } else { // Error would be null if json has no "error" field. errorItems.add(new ErrorItem(i, "")); } } } return errorItems; }
From source file:com.synflow.cx.internal.instantiation.properties.EntityPropertiesChecker.java
License:Open Source License
/** * Checks the given properties of the <code>instantiable</code>. * /*from w ww . j a v a2 s. c o m*/ * @param instantiable * a Cx instantiable * @param properties * JSON properties */ public void checkProperties(Instantiable instantiable, JsonObject properties) { checkTest(instantiable, properties.get(PROP_TEST)); JsonElement type = properties.get(PROP_TYPE); if (type != null) { if (type.isJsonPrimitive()) { JsonPrimitive entityType = properties.getAsJsonPrimitive(PROP_TYPE); if (TYPE_COMBINATIONAL.equals(entityType)) { // set an empty list of clocks, set no reset properties.add(PROP_CLOCKS, new JsonArray()); properties.add(PROP_RESET, null); return; } else { handler.addError(entityType, "the only valid value of type is 'combinational', ignored."); } } else { handler.addError(type, "type must be a string"); } } checkClocksDeclared(properties); checkResetDeclared(properties); }
From source file:com.synflow.cx.internal.instantiation.properties.EntityPropertiesChecker.java
License:Open Source License
/** * Checks that the 'reset' property is properly declared. * //ww w. ja v a2 s . c om * @param properties * properties */ private void checkResetDeclared(JsonObject properties) { JsonElement reset = properties.get(PROP_RESET); if (reset == null) { reset = new JsonObject(); properties.add(PROP_RESET, reset); } if (reset.isJsonObject()) { JsonObject resetObj = reset.getAsJsonObject(); JsonPrimitive type = resetObj.getAsJsonPrimitive(PROP_TYPE); if (type == null || !RESET_ASYNCHRONOUS.equals(type) && !RESET_SYNCHRONOUS.equals(type)) { // default is asynchronous reset resetObj.add(PROP_TYPE, RESET_ASYNCHRONOUS); } JsonPrimitive active = resetObj.getAsJsonPrimitive(PROP_ACTIVE); if (active == null || !ACTIVE_HIGH.equals(active) && !ACTIVE_LOW.equals(active)) { // default is active low reset resetObj.add(PROP_ACTIVE, ACTIVE_LOW); } if (!resetObj.has(PROP_NAME)) { // compute default name if (ACTIVE_LOW.equals(resetObj.getAsJsonPrimitive(PROP_ACTIVE))) { resetObj.addProperty(PROP_NAME, "reset_n"); } else { resetObj.addProperty(PROP_NAME, "reset"); } } } }
From source file:com.talvish.tales.serialization.json.translators.JsonObjectToPolymorphicObjectTranslator.java
License:Apache License
/** * Translates the received object into the appropriate json representation. * If the object is of the wrong type or the translator used doesn't produce * JsonElements's then a TranslationException will occur. */// ww w . j a va 2s .co m @Override public Object translate(Object anObject) { Object returnValue; if (anObject == null || anObject.equals(JsonNull.INSTANCE)) { returnValue = null; } else { try { // need to extract two things, the "value" and the "value_type" // and if they don't exist then we have a problem JsonObject jsonObject = (JsonObject) anObject; JsonPrimitive valueTypeJson = jsonObject.getAsJsonPrimitive("value_type"); JsonElement valueJson = jsonObject.get("value"); if (valueTypeJson == null || !valueTypeJson.isString()) { throw new TranslationException(String.format("The associate value type is missing.")); } else if (valueJson == null) { throw new TranslationException(String.format("The associate value for type '%s' is missing.", valueTypeJson.getAsString())); } else { String valueTypeString = valueTypeJson.getAsString(); TypeFormatAdapter typeAdapter = typeAdapters.get(valueTypeString); if (typeAdapter == null) { throw new TranslationException(String .format("Json is referring to a type '%s' that isn't supported.", valueTypeString)); } else { returnValue = typeAdapter.getFromFormatTranslator().translate(valueJson); } } // TODO: catch the various gson json exceptions } catch (ClassCastException e) { throw new TranslationException(e); } } return returnValue; }
From source file:com.thoughtworks.go.server.domain.user.Marshaling.java
License:Apache License
private static String defensivelyGetString(JsonObject obj, String key) { return obj.has(key) ? obj.getAsJsonPrimitive(key).getAsString() : ""; }
From source file:com.torben.androidchat.JSONRPC.server.JsonRpcExecutor.java
License:Apache License
public void execute(HttpJsonRpcClientTransport transport) { if (!locked) { synchronized (handlers) { locked = true;//from www . ja v a2 s. c o m } LOG.info("locking executor to avoid modification"); } String methodName = null; JsonArray params = null; JsonObject resp = new JsonObject(); resp.addProperty("jsonrpc", "2.0"); String errorMessage = null; Integer errorCode = null; String errorData = null; JsonObject req = null; try { String requestData = transport.threadedCall(null); if (requestData == null) { Log.v("EXECUTOR", "no Data"); return; } Log.v("EXECUTOR", requestData); JsonParser parser = new JsonParser(); req = (JsonObject) parser.parse(new StringReader(requestData)); } catch (Throwable t) { errorCode = JsonRpcErrorCodes.PARSE_ERROR_CODE; errorMessage = "unable to parse json-rpc request"; errorData = getStackTrace(t); Log.v("EXECUTOR", "Somethign went wrong parsing"); LOG.warn(errorMessage, t); sendError(transport, resp, errorCode, errorMessage, errorData); return; } try { assert req != null; resp.add("id", req.get("id")); methodName = req.getAsJsonPrimitive("method").getAsString(); Log.v("EXECUTOR", "metohdname = " + methodName); params = (JsonArray) req.get("params"); if (params == null) { params = new JsonArray(); } } catch (Throwable t) { errorCode = JsonRpcErrorCodes.INVALID_REQUEST_ERROR_CODE; errorMessage = "unable to read request"; errorData = getStackTrace(t); LOG.warn(errorMessage, t); sendError(transport, resp, errorCode, errorMessage, errorData); return; } try { JsonElement result = executeMethod(methodName, params); resp.add("result", result); } catch (Throwable t) { LOG.warn("exception occured while executing : " + methodName, t); if (t instanceof JsonRpcRemoteException) { sendError(transport, resp, (JsonRpcRemoteException) t); return; } errorCode = JsonRpcErrorCodes.getServerError(1); errorMessage = t.getMessage(); errorData = getStackTrace(t); sendError(transport, resp, errorCode, errorMessage, errorData); return; } try { String responseData = resp.toString(); transport.threadedCall(responseData); } catch (Exception e) { LOG.warn("unable to write response : " + resp, e); } }
From source file:com.twitter.sdk.android.core.AuthTokenAdapter.java
License:Apache License
@Override public AuthToken deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final JsonObject jsonObject = json.getAsJsonObject(); final JsonPrimitive jsonAuthType = jsonObject.getAsJsonPrimitive(AUTH_TYPE); final String authType = jsonAuthType.getAsString(); final JsonElement jsonAuthToken = jsonObject.get(AUTH_TOKEN); return gson.fromJson(jsonAuthToken, authTypeRegistry.get(authType)); }
From source file:com.wso2telco.MePinStatusRequest.java
License:Open Source License
public String call() { String allowStatus = null;/*from w w w. j a va 2 s . co m*/ String clientId = FileUtil.getApplicationProperty("mepin.clientid"); String url = FileUtil.getApplicationProperty("mepin.url"); url = url + "?transaction_id=" + transactionId + "&client_id=" + clientId + ""; log.info("MePIN Status URL: " + url); String authHeader = "Basic " + FileUtil.getApplicationProperty("mepin.accesstoken"); try { HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Authorization", authHeader); String resp = ""; int statusCode = connection.getResponseCode(); InputStream is; if ((statusCode == 200) || (statusCode == 201)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { resp += output; } br.close(); log.info("MePIN Status Response Code: " + statusCode + " " + connection.getResponseMessage()); log.info("MePIN Status Response: " + resp); JsonObject responseJson = new JsonParser().parse(resp).getAsJsonObject(); String respTransactionId = responseJson.getAsJsonPrimitive("transaction_id").getAsString(); JsonPrimitive allowObject = responseJson.getAsJsonPrimitive("allow"); if (allowObject != null) { allowStatus = allowObject.getAsString(); if (Boolean.parseBoolean(allowStatus)) { allowStatus = "APPROVED"; String sessionID = DatabaseUtils.getMePinSessionID(respTransactionId); DatabaseUtils.updateStatus(sessionID, allowStatus); } } } catch (IOException e) { log.error("Error while MePIN Status request" + e); } catch (SQLException e) { log.error("Error in connecting to DB" + e); } return allowStatus; }
From source file:com.yandex.money.api.typeadapters.model.showcase.container.GroupTypeAdapter.java
License:Open Source License
@Override protected void deserialize(JsonObject src, Group.Builder builder, JsonDeserializationContext context) { JsonElement layout = src.getAsJsonPrimitive(MEMBER_LAYOUT); if (layout != null) { builder.setLayout(Group.Layout.parse(layout.getAsString())); }/*w w w . j av a 2s . c om*/ super.deserialize(src, builder, context); }