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:org.thingsboard.server.common.transport.adaptor.JsonConverter.java

License:Apache License

private static KeyValueProto buildNumericKeyValueProto(JsonPrimitive value, String key) {
    if (value.getAsString().contains(".")) {
        return KeyValueProto.newBuilder().setKey(key).setType(KeyValueType.DOUBLE_V)
                .setDoubleV(value.getAsDouble()).build();
    } else {//from  www . ja  v a2 s  .  com
        try {
            long longValue = Long.parseLong(value.getAsString());
            return KeyValueProto.newBuilder().setKey(key).setType(KeyValueType.LONG_V).setLongV(longValue)
                    .build();
        } catch (NumberFormatException e) {
            throw new JsonSyntaxException("Big integer values are not supported!");
        }
    }
}

From source file:org.thingsboard.server.common.transport.adaptor.JsonConverter.java

License:Apache License

private static void parseNumericValue(List<KvEntry> result, Entry<String, JsonElement> valueEntry,
        JsonPrimitive value) {
    if (value.getAsString().contains(".")) {
        result.add(new DoubleDataEntry(valueEntry.getKey(), value.getAsDouble()));
    } else {//w ww  . j a v a  2s .c om
        try {
            long longValue = Long.parseLong(value.getAsString());
            result.add(new LongDataEntry(valueEntry.getKey(), longValue));
        } catch (NumberFormatException e) {
            throw new JsonSyntaxException("Big integer values are not supported!");
        }
    }
}

From source file:org.thingsboard.server.common.transport.adaptor.JsonConverter.java

License:Apache License

private static List<KvEntry> parseValues(JsonObject valuesObject) {
    List<KvEntry> result = new ArrayList<>();
    for (Entry<String, JsonElement> valueEntry : valuesObject.entrySet()) {
        JsonElement element = valueEntry.getValue();
        if (element.isJsonPrimitive()) {
            JsonPrimitive value = element.getAsJsonPrimitive();
            if (value.isString()) {
                if (maxStringValueLength > 0 && value.getAsString().length() > maxStringValueLength) {
                    String message = String.format(
                            "String value length [%d] for key [%s] is greater than maximum allowed [%d]",
                            value.getAsString().length(), valueEntry.getKey(), maxStringValueLength);
                    throw new JsonSyntaxException(message);
                }/*from ww w.  j  ava 2 s .com*/
                if (isTypeCastEnabled && NumberUtils.isParsable(value.getAsString())) {
                    try {
                        parseNumericValue(result, valueEntry, value);
                    } catch (RuntimeException th) {
                        result.add(new StringDataEntry(valueEntry.getKey(), value.getAsString()));
                    }
                } else {
                    result.add(new StringDataEntry(valueEntry.getKey(), value.getAsString()));
                }
            } else if (value.isBoolean()) {
                result.add(new BooleanDataEntry(valueEntry.getKey(), value.getAsBoolean()));
            } else if (value.isNumber()) {
                parseNumericValue(result, valueEntry, value);
            } else {
                throw new JsonSyntaxException(CAN_T_PARSE_VALUE + value);
            }
        } else {
            throw new JsonSyntaxException(CAN_T_PARSE_VALUE + element);
        }
    }
    return result;
}

From source file:org.trimou.gson.resolver.JsonElementResolver.java

License:Apache License

private Object unwrapJsonPrimitive(JsonPrimitive jsonPrimitive) {
    if (jsonPrimitive.isBoolean()) {
        return jsonPrimitive.getAsBoolean();
    } else if (jsonPrimitive.isString()) {
        return jsonPrimitive.getAsString();
    } else if (jsonPrimitive.isNumber()) {
        return jsonPrimitive.getAsNumber();
    }//from  ww w  .  j  a va  2 s .  com
    return jsonPrimitive;
}

From source file:org.tsukuba_bunko.lilac.web.controller.JsonRequestParser.java

License:Open Source License

/**
 * JavaScript?(?,,)Java?????/*from  w w  w . j a v a 2 s .co m*/
 * @param jsonPrimitiveJavaScript?
 * @returnJava
 */
public Object getJavaObject(JsonPrimitive jsonPrimitive) {
    if (jsonPrimitive.isBoolean()) {
        return jsonPrimitive.getAsBoolean();
    } else if (jsonPrimitive.isNumber()) {
        return jsonPrimitive.getAsNumber();
    } else {
        return jsonPrimitive.getAsString();
    }
}

From source file:org.tuleap.mylyn.task.core.internal.parser.AbstractTuleapDeserializer.java

License:Open Source License

/**
 * {@inheritDoc}//from   w  w  w.  j  a v a  2  s.co  m
 *
 * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type,
 *      com.google.gson.JsonDeserializationContext)
 */
@Override
public T deserialize(JsonElement rootJsonElement, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObject = rootJsonElement.getAsJsonObject();
    T pojo = super.deserialize(rootJsonElement, type, context);
    JsonElement jsonTrackerRef = jsonObject.get(ITuleapConstants.JSON_TRACKER);
    TuleapReference trackerRef = context.deserialize(jsonTrackerRef, TuleapReference.class);
    pojo.setTracker(trackerRef);

    JsonArray fields = jsonObject.get(ITuleapConstants.VALUES).getAsJsonArray();
    for (JsonElement field : fields) {
        JsonObject jsonField = field.getAsJsonObject();
        int fieldId = jsonField.get(ITuleapConstants.FIELD_ID).getAsInt();
        if (jsonField.has(ITuleapConstants.FIELD_VALUE)) {
            JsonElement jsonValue = jsonField.get(ITuleapConstants.FIELD_VALUE);
            if (jsonValue.isJsonPrimitive()) {
                JsonPrimitive primitive = jsonValue.getAsJsonPrimitive();
                if (primitive.isString()) {
                    pojo.addFieldValue(new LiteralFieldValue(fieldId, primitive.getAsString()));
                } else if (primitive.isNumber()) {
                    pojo.addFieldValue(new LiteralFieldValue(fieldId, String.valueOf(primitive.getAsNumber())));
                } else if (primitive.isBoolean()) {
                    pojo.addFieldValue(
                            new LiteralFieldValue(fieldId, String.valueOf(primitive.getAsBoolean())));
                }
            }
        } else if (jsonField.has(ITuleapConstants.FIELD_BIND_VALUE_ID)
                && !jsonField.get(ITuleapConstants.FIELD_BIND_VALUE_ID).isJsonNull()) {
            // sb?
            JsonElement jsonBindValueId = jsonField.get(ITuleapConstants.FIELD_BIND_VALUE_ID);
            int bindValueId = jsonBindValueId.getAsInt();
            pojo.addFieldValue(new BoundFieldValue(fieldId, Lists.newArrayList(Integer.valueOf(bindValueId))));
        } else if (jsonField.has(ITuleapConstants.FIELD_BIND_VALUE_IDS)
                && !jsonField.get(ITuleapConstants.FIELD_BIND_VALUE_IDS).isJsonNull()) {
            // sb?, msb, cb, or tbl (open list)
            JsonElement jsonBindValueIds = jsonField.get(ITuleapConstants.FIELD_BIND_VALUE_IDS);
            JsonArray jsonIds = jsonBindValueIds.getAsJsonArray();
            if (jsonIds.size() > 0) {
                JsonPrimitive firstElement = jsonIds.get(0).getAsJsonPrimitive();
                if (firstElement.isString()) {
                    // Open list (tbl)
                    List<String> bindValueIds = new ArrayList<String>();
                    for (JsonElement idElement : jsonIds) {
                        bindValueIds.add(idElement.getAsString());
                    }
                    pojo.addFieldValue(new OpenListFieldValue(fieldId, bindValueIds));
                } else {
                    List<Integer> bindValueIds = new ArrayList<Integer>();
                    for (JsonElement idElement : jsonIds) {
                        bindValueIds.add(Integer.valueOf(idElement.getAsInt()));
                    }
                    pojo.addFieldValue(new BoundFieldValue(fieldId, bindValueIds));
                }
            } else {
                pojo.addFieldValue(new BoundFieldValue(fieldId, Collections.<Integer>emptyList()));
            }
        } else if (jsonField.has(ITuleapConstants.FIELD_LINKS)
                && !jsonField.get(ITuleapConstants.FIELD_LINKS).isJsonNull()) {
            // Artifact links
            pojo.addFieldValue(
                    context.<ArtifactLinkFieldValue>deserialize(jsonField, ArtifactLinkFieldValue.class));
        } else if (jsonField.has(ITuleapConstants.FILE_DESCRIPTIONS)
                && jsonField.get(ITuleapConstants.FILE_DESCRIPTIONS).isJsonArray()) {
            AttachmentFieldValue value = context.deserialize(jsonField, AttachmentFieldValue.class);
            pojo.addFieldValue(value);
        }

    }

    return pojo;
}

From source file:org.wso2.ballerina.nativeimpl.lang.json.GetString.java

License:Open Source License

@Override
public BValue[] execute(Context ctx) {
    String jsonPath = null;/*from  ww  w.  jav  a 2  s  .c o m*/
    BValue result = null;
    try {
        // Accessing Parameters.
        BJSON json = (BJSON) getArgument(ctx, 0);
        jsonPath = getArgument(ctx, 1).stringValue();

        // Getting the value from JSON
        ReadContext jsonCtx = JsonPath.parse(json.value());
        JsonElement element = jsonCtx.read(jsonPath);
        if (element == null) {
            throw new BallerinaException("No matching element found for jsonpath: " + jsonPath);
        } else if (element.isJsonPrimitive()) {
            // if the resulting value is a primitive, return the respective primitive value object
            JsonPrimitive value = element.getAsJsonPrimitive();
            if (value.isString()) {
                result = new BString(value.getAsString());
            } else {
                throw new BallerinaException("The element matching path: " + jsonPath + " is not a String.");
            }
        } else {
            throw new BallerinaException("The element matching path: " + jsonPath + " is not a String.");
        }
    } catch (PathNotFoundException e) {
        ErrorHandler.handleNonExistingJsonpPath(OPERATION, jsonPath, e);
    } catch (InvalidPathException e) {
        ErrorHandler.handleInvalidJsonPath(OPERATION, e);
    } catch (JsonPathException e) {
        ErrorHandler.handleJsonPathException(OPERATION, e);
    } catch (Throwable e) {
        ErrorHandler.handleJsonPathException(OPERATION, e);
    }

    // Setting output value.
    return getBValues(result);
}

From source file:org.wso2.carbon.appmgt.sample.jwt.JWTProcessor.java

License:Open Source License

public Map process(String jwtToken) {
    jwtDetails = new HashMap<String, String>();
    JsonToken token = deserialize(jwtToken);
    //        JsonObject header = token.getHeader();
    JsonObject claims = token.getPayloadAsJsonObject();
    Set<Map.Entry<String, JsonElement>> claimSet = claims.entrySet();

    for (Map.Entry e : claimSet) {
        JsonPrimitive primitive = (JsonPrimitive) e.getValue();
        jwtDetails.put(e.getKey().toString(), primitive.getAsString());
    }//w  ww .ja  v a  2  s.  com
    System.out.println("Claims : " + jwtDetails);
    return jwtDetails;
}

From source file:org.wso2.carbon.identity.authenticator.MePIN.MePINAuthenticator.java

License:Open Source License

/**
 * Process the response of the MePIN end-point
 *//*w w w  .  j a v a 2s. c om*/
@Override
protected void processAuthenticationResponse(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {

    if ((!StringUtils.isEmpty(request.getParameter(MePINConstants.MEPIN_ACCESSTOKEN)))) {

        try {
            String authenticatedLocalUsername = getLocalAuthenticatedUser(context).getUserName();
            String accessToken = request.getParameter(MePINConstants.MEPIN_ACCESSTOKEN);

            String responseString = new MePINTransactions().getUserInformation(
                    authenticatorProperties.get(MePINConstants.MEPIN_USERNAME),
                    authenticatorProperties.get(MePINConstants.MEPIN_PASSWORD), accessToken);
            if (!responseString.equals(MePINConstants.FAILED)) {
                JsonObject responseJson = new JsonParser().parse(responseString).getAsJsonObject();
                String mepinId = responseJson.getAsJsonPrimitive(MePINConstants.MEPIN_ID).getAsString();
                associateFederatedIdToLocalUsername(authenticatedLocalUsername, context,
                        getFederateAuthenticatedUser(context, mepinId));
                context.setSubject(AuthenticatedUser
                        .createLocalAuthenticatedUserFromSubjectIdentifier(authenticatedLocalUsername));
            } else {
                throw new AuthenticationFailedException("Unable to get the MePIN ID.");
            }
        } catch (ApplicationAuthenticatorException e) {
            log.error("Unable to set the subject: " + e.getMessage(), e);
            throw new AuthenticationFailedException("Unable to set the subject: " + e.getMessage(), e);
        } catch (UserProfileException e) {
            log.error("Unable to associate the user: " + e.getMessage(), e);
            throw new AuthenticationFailedException("Unable to associate the user: " + e.getMessage(), e);
        }

    } else {
        String allowStatus = "";
        try {
            String authenticatedLocalUsername = getLocalAuthenticatedUser(context).getUserName();
            String idpName = context.getExternalIdP().getIdPName();
            String mePinId = null;
            mePinId = getMepinIdAssociatedWithUsername(idpName, authenticatedLocalUsername);
            boolean isAuthenticated = false;
            JsonObject transactionResponse = null;
            transactionResponse = new MePINTransactions().createTransaction(mePinId,
                    context.getContextIdentifier(), MePINConstants.MEPIN_CREATE_TRANSACTION_URL,
                    authenticatorProperties.get(MePINConstants.MEPIN_USERNAME),
                    authenticatorProperties.get(MePINConstants.MEPIN_PASSWORD),
                    authenticatorProperties.get(MePINConstants.MEPIN_CLIENT_ID),
                    authenticatorProperties.get(MePINConstants.MEPIN_HEADER),
                    authenticatorProperties.get(MePINConstants.MEPIN_MESSAGE),
                    authenticatorProperties.get(MePINConstants.MEPIN_SHORT_MESSAGE),
                    authenticatorProperties.get(MePINConstants.MEPIN_CONFIRMATION_POLICY),
                    authenticatorProperties.get(MePINConstants.MEPIN_CALLBACK_URL),
                    authenticatorProperties.get(MePINConstants.MEPIN_EXPIRY_TIME));
            String transactionId = transactionResponse.getAsJsonPrimitive(MePINConstants.MEPIN_TRANSACTION_ID)
                    .getAsString();
            String status = transactionResponse.getAsJsonPrimitive(MePINConstants.MEPIN_STATUS).getAsString();
            if (status.equalsIgnoreCase(MePINConstants.MEPIN_OK)) {
                if (log.isDebugEnabled()) {
                    log.debug("Successfully created the MePIN transaction");
                }
                int retry = 0;
                int retryInterval = 1;
                int retryCount = Integer.parseInt(authenticatorProperties.get(MePINConstants.MEPIN_EXPIRY_TIME))
                        / retryInterval;
                while (retry < retryCount) {
                    JsonObject transactionStatusResponse = null;

                    transactionStatusResponse = new MePINTransactions().getTransaction(
                            MePINConstants.MEPIN_GET_TRANSACTION_URL, transactionId,
                            authenticatorProperties.get(MePINConstants.MEPIN_CLIENT_ID),
                            authenticatorProperties.get(MePINConstants.MEPIN_USERNAME),
                            authenticatorProperties.get(MePINConstants.MEPIN_PASSWORD));

                    String transactionStatus = transactionStatusResponse
                            .getAsJsonPrimitive(MePINConstants.MEPIN_TRANSACTION_STATUS).getAsString();
                    JsonPrimitive allowObject = transactionStatusResponse
                            .getAsJsonPrimitive(MePINConstants.MEPIN_ALLOW);
                    if (log.isDebugEnabled()) {
                        log.debug("Transaction status :" + transactionStatus);
                    }
                    if (transactionStatus.equals(MePINConstants.MEPIN_COMPLETED)) {
                        allowStatus = allowObject.getAsString();
                        if (Boolean.parseBoolean(allowStatus)) {
                            isAuthenticated = true;
                            break;
                        }
                    }
                    Thread.sleep(1000);
                    retry++;
                }
                if (isAuthenticated) {
                    context.setSubject(AuthenticatedUser
                            .createLocalAuthenticatedUserFromSubjectIdentifier(authenticatedLocalUsername));
                } else {
                    throw new AuthenticationFailedException("Unable to confirm the MePIN transaction");
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Error while creating the MePIN transaction");
                }
                throw new AuthenticationFailedException("Error while creating the MePIN transaction");
            }
        } catch (UserProfileException e) {
            log.error("Unable to get the associated user: " + e.getMessage(), e);
            throw new AuthenticationFailedException("Unable to get the associated user: " + e.getMessage(), e);
        } catch (IOException e) {
            log.error("Unable to create the MePIN transaction: " + e.getMessage(), e);
            throw new AuthenticationFailedException("Unable to create the MePIN transaction: " + e.getMessage(),
                    e);
        } catch (InterruptedException e) {
            log.error("Interruption occurred while getting the MePIN transaction status" + e.getMessage(), e);
            throw new AuthenticationFailedException(
                    "Interruption occurred while getting the MePIN transaction status" + e.getMessage(), e);
        }
    }
}

From source file:org.wso2.carbon.identity.authenticator.MePINAuthenticator.java

License:Open Source License

/**
 * initiate the authentication request//w w w.j  a  v  a2  s .  c  om
 */
@Override
public AuthenticatorFlowStatus process(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException, LogoutFailedException {
    if (context.isLogoutRequest()) {
        return AuthenticatorFlowStatus.SUCCESS_COMPLETED;
    } else {
        context.setRetrying(false);
        String allowStatus = "";
        boolean isAuthenticated = false;
        Map<String, String> authenticatorProperties = context.getAuthenticatorProperties();
        try {

            String authenticatedLocalUsername = getLocalAuthenticatedUser(context).getUserName();

            //String mePinId = "41b21e2af200fcf75a8442bc93a0d27b";
            String mePinId = "fcf3c2b42ee0ca79015e92d76eb432f6";
            JsonObject transactionResponse = new MePINTransaction().createTransaction(mePinId,
                    context.getContextIdentifier(), MePINConstants.MEPIN_CREATE_TRANSACTION_URL,
                    authenticatorProperties.get(MePINConstants.MEPIN_USERNAME),
                    authenticatorProperties.get(MePINConstants.MEPIN_PASSWORD),
                    authenticatorProperties.get(MePINConstants.MEPIN_CLIENT_ID),
                    authenticatorProperties.get(MePINConstants.MEPIN_HEADER),
                    authenticatorProperties.get(MePINConstants.MEPIN_MESSAGE),
                    authenticatorProperties.get(MePINConstants.MEPIN_SHORT_MESSAGE),
                    authenticatorProperties.get(MePINConstants.MEPIN_CONFIRMATION_POLICY),
                    authenticatorProperties.get(MePINConstants.MEPIN_CALLBACK_URL),
                    authenticatorProperties.get(MePINConstants.MEPIN_EXPIRY_TIME));
            String transactionId = transactionResponse.getAsJsonPrimitive("transaction_id").getAsString();
            String status = transactionResponse.getAsJsonPrimitive("status").getAsString();//TODO constants

            if (status.equalsIgnoreCase("ok")) {
                if (log.isDebugEnabled()) {
                    log.debug("Successfully created the MePIN transaction");
                }
                int retry = 0;
                int retryInterval = 1;
                int retryCount = Integer.parseInt(authenticatorProperties.get(MePINConstants.MEPIN_EXPIRY_TIME))
                        / retryInterval;
                while (retry < retryCount) {
                    JsonObject transactionStatusResponse = new MePINTransaction().getTransaction(
                            MePINConstants.MEPIN_GET_TRANSACTION_URL, transactionId,
                            authenticatorProperties.get(MePINConstants.MEPIN_CLIENT_ID),
                            authenticatorProperties.get(MePINConstants.MEPIN_USERNAME),
                            authenticatorProperties.get(MePINConstants.MEPIN_PASSWORD));

                    String transactionStatus = transactionStatusResponse
                            .getAsJsonPrimitive("transaction_status").getAsString();
                    JsonPrimitive allowObject = transactionStatusResponse.getAsJsonPrimitive("allow");
                    if (log.isDebugEnabled()) {
                        log.debug("Transaction status :" + transactionStatus);
                    }
                    if (transactionStatus.equals("completed")) {
                        allowStatus = allowObject.getAsString();
                        if (Boolean.parseBoolean(allowStatus)) {
                            isAuthenticated = true;
                            break;
                        }
                    }
                    Thread.sleep(1000);
                    retry++;
                }
                if (isAuthenticated) {
                    //context.setSubject("User is logged in");
                    String username = "admin";
                    context.setSubject(
                            AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(username));
                } else
                    throw new AuthenticationFailedException("Error while creating the MePIN transaction");
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Error while creating the MePIN transaction");
                }
                throw new AuthenticationFailedException("Error while creating the MePIN transaction");//TODO remove same msg
            }
        } catch (IOException e) {
            throw new AuthenticationFailedException(e.getMessage(), e);//TODO remove and add constant msg
        } catch (InterruptedException e) {
            e.printStackTrace();//TODO handle

        }
        return AuthenticatorFlowStatus.SUCCESS_COMPLETED;
    }
}