Example usage for com.google.gson JsonObject getAsJsonPrimitive

List of usage examples for com.google.gson JsonObject getAsJsonPrimitive

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsJsonPrimitive.

Prototype

public JsonPrimitive getAsJsonPrimitive(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonPrimitive element.

Usage

From source file:ca.ualberta.cs.scandaloutraveltracker.mappers.UserMapper.java

License:Apache License

@Override
public Location deserialize(JsonElement element, Type arg1, JsonDeserializationContext jdc)
        throws JsonParseException {

    JsonObject jo = element.getAsJsonObject();
    Location location = new Location(jo.getAsJsonPrimitive("provider").getAsString());
    location.setAccuracy(jo.getAsJsonPrimitive("accuracy").getAsFloat());
    location.setLatitude(jo.getAsJsonPrimitive("latitude").getAsDouble());
    location.setLongitude(jo.getAsJsonPrimitive("longitude").getAsDouble());

    return location;
}

From source file:ch.cyberduck.core.dropbox.DropboxExceptionMappingService.java

License:Open Source License

private void parse(final StringBuilder buffer, final String message) {
    final JsonParser parser = new JsonParser();
    try {/*from  w ww  . ja  v a 2  s . com*/
        final JsonElement element = parser.parse(new StringReader(message));
        if (element.isJsonObject()) {
            final JsonObject json = element.getAsJsonObject();
            final JsonObject error = json.getAsJsonObject("error");
            if (null == error) {
                this.append(buffer, message);
            } else {
                final JsonPrimitive tag = error.getAsJsonPrimitive(".tag");
                if (null == tag) {
                    this.append(buffer, message);
                } else {
                    this.append(buffer, StringUtils.replace(tag.getAsString(), "_", " "));
                }
            }
        }
        if (element.isJsonPrimitive()) {
            this.append(buffer, element.getAsString());
        }
    } catch (JsonParseException e) {
        // Ignore
    }
}

From source file:ch.cyberduck.core.hubic.HubicAuthenticationResponseHandler.java

License:Open Source License

@Override
public AuthenticationResponse handleResponse(final HttpResponse response) throws IOException {
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        Charset charset = HTTP.DEF_CONTENT_CHARSET;
        ContentType contentType = ContentType.get(response.getEntity());
        if (contentType != null) {
            if (contentType.getCharset() != null) {
                charset = contentType.getCharset();
            }/*  w  ww .  j  a  v a  2 s.  c o m*/
        }
        try {
            final JsonParser parser = new JsonParser();
            final JsonObject json = parser
                    .parse(new InputStreamReader(response.getEntity().getContent(), charset)).getAsJsonObject();
            final String token = json.getAsJsonPrimitive("token").getAsString();
            final String endpoint = json.getAsJsonPrimitive("endpoint").getAsString();
            return new AuthenticationResponse(response, token,
                    Collections.singleton(new Region(null, URI.create(endpoint), null, true)));
        } catch (JsonParseException e) {
            throw new IOException(e.getMessage(), e);
        }
    } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED
            || response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
        throw new AuthorizationException(new Response(response));
    }
    throw new GenericException(new Response(response));
}

From source file:ch.cyberduck.core.sds.SDSExceptionMappingService.java

License:Open Source License

@Override
public BackgroundException map(final ApiException failure) {
    for (Throwable cause : ExceptionUtils.getThrowableList(failure)) {
        if (cause instanceof SocketException) {
            // Map Connection has been shutdown: javax.net.ssl.SSLException: java.net.SocketException: Broken pipe
            return new DefaultSocketExceptionMappingService().map((SocketException) cause);
        }//from  ww w. j a va2s.  c om
        if (cause instanceof HttpResponseException) {
            return new HttpResponseExceptionMappingService().map((HttpResponseException) cause);
        }
        if (cause instanceof IOException) {
            return new DefaultIOExceptionMappingService().map((IOException) cause);
        }
    }
    final StringBuilder buffer = new StringBuilder();
    if (null != failure.getResponseBody()) {
        final JsonParser parser = new JsonParser();
        try {
            final JsonObject json = parser.parse(new StringReader(failure.getResponseBody())).getAsJsonObject();
            if (json.has("errorCode")) {
                if (json.get("errorCode").isJsonPrimitive()) {
                    final int errorCode = json.getAsJsonPrimitive("errorCode").getAsInt();
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Failure with errorCode %s", errorCode));
                    }
                    final String key = String.format("Error %d", errorCode);
                    final String localized = LocaleFactory.get().localize(key, "SDS");
                    this.append(buffer, localized);
                    if (StringUtils.equals(localized, key)) {
                        log.warn(String.format("Missing user message for error code %d", errorCode));
                        if (json.has("debugInfo")) {
                            if (json.get("debugInfo").isJsonPrimitive()) {
                                this.append(buffer, json.getAsJsonPrimitive("debugInfo").getAsString());
                            }
                        }
                    }
                    switch (failure.getCode()) {
                    case HttpStatus.SC_NOT_FOUND:
                        switch (errorCode) {
                        case -70501:
                            // [-70501] User not found
                            return new AccessDeniedException(buffer.toString(), failure);
                        case -40761:
                            // [-40761] Filekey not found for encrypted file
                            return new AccessDeniedException(buffer.toString(), failure);
                        }
                        break;
                    case HttpStatus.SC_PRECONDITION_FAILED:
                        switch (errorCode) {
                        case -10108:
                            // [-10108] Radius Access-Challenge required.
                            if (json.has("replyMessage")) {
                                if (json.get("replyMessage").isJsonPrimitive()) {
                                    final JsonPrimitive replyMessage = json.getAsJsonPrimitive("replyMessage");
                                    if (log.isDebugEnabled()) {
                                        log.debug(String.format("Failure with replyMessage %s", replyMessage));
                                    }
                                    buffer.append(replyMessage.getAsString());
                                }
                            }
                            return new PartialLoginFailureException(buffer.toString(), failure);
                        }
                        break;
                    case HttpStatus.SC_UNAUTHORIZED:
                        switch (errorCode) {
                        case -10012:
                            // [-10012] Wrong token.
                            return new ExpiredTokenException(buffer.toString(), failure);
                        }
                        break;
                    }
                }
            } else {
                switch (failure.getCode()) {
                case HttpStatus.SC_INTERNAL_SERVER_ERROR:
                    break;
                default:
                    if (json.has("debugInfo")) {
                        log.warn(String.format("Missing error code for failure %s", json));
                        if (json.get("debugInfo").isJsonPrimitive()) {
                            this.append(buffer, json.getAsJsonPrimitive("debugInfo").getAsString());
                        }
                    }
                }
            }
        } catch (JsonParseException e) {
            // Ignore
            this.append(buffer, failure.getMessage());
        }
    }
    switch (failure.getCode()) {
    case HttpStatus.SC_PRECONDITION_FAILED:
        // [-10103] EULA must be accepted
        // [-10104] Password must be changed
        // [-10106] Username must be changed
        return new LoginFailureException(buffer.toString(), failure);
    }
    return new HttpResponseExceptionMappingService().map(failure, buffer, failure.getCode());
}

From source file:client.getforgeid.java

License:Creative Commons License

/**
 * reads json data to get forge profile and forge id
 * @return the last used version id of forge
 * @throws IOException//from ww  w .j a v  a2s.com
 */
public static String findForgeProfile() throws IOException {
    File configFile = getConfigFile();

    Gson gson = GsonUtil.make();
    JsonObject jobj;
    try (InputStream is = new FileInputStream(configFile); InputStreamReader isr = new InputStreamReader(is)) {
        jobj = gson.fromJson(isr, JsonElement.class).getAsJsonObject();
    }

    JsonObject profiles = jobj.getAsJsonObject("profiles");
    JsonObject forge = profiles.getAsJsonObject("Forge");
    if (forge == null)
        return null;

    return forge.getAsJsonPrimitive("lastVersionId").getAsString();
}

From source file:client.getforgeid.java

License:Creative Commons License

/**
 * gets last run minecraft version// w w w.jav  a 2 s.c  o  m
 * @return returns the last run version id 
 * @throws IOException
 */
public static String findLastUsedMcVersion() throws IOException {
    File configFile = getConfigFile();

    Gson gson = GsonUtil.make();
    JsonObject jobj;
    try (InputStream is = new FileInputStream(configFile); InputStreamReader isr = new InputStreamReader(is)) {
        jobj = gson.fromJson(isr, JsonElement.class).getAsJsonObject();
    }

    String selectedprofile = jobj.getAsJsonPrimitive("selectedProfile").getAsString();

    JsonObject profiles = jobj.getAsJsonObject("profiles");
    JsonObject mc = profiles.getAsJsonObject(selectedprofile);
    if (mc == null)
        return null;

    String lastVersionID = mc.getAsJsonPrimitive("lastVersionId").getAsString();
    if (lastVersionID.length() > 6) {
        lastVersionID = lastVersionID.substring(0, 5); // TODO: work out
        // better way to get
        // mc version.
    }
    return lastVersionID;
}

From source file:cloudlens.cli.Whisk.java

License:Apache License

public static JsonObject main(JsonObject args) {
    final JsonObject res = new JsonObject();

    try {//from  ww w. jav a 2s  .  c om
        final CL cl = new CL(System.out, System.err, false, true);

        String script = "";
        String logURI = "";

        if (args.has("script")) {
            script = args.getAsJsonPrimitive("script").getAsString();
        }
        if (args.has("log")) {
            logURI = args.getAsJsonPrimitive("log").getAsString();
        }

        try {
            final InputStream inputStream = FileReader.fetchFile(logURI);
            cl.source(inputStream);
            final List<ASTElement> top = ASTBuilder.parse(script);
            cl.launch(top);

            final JsonElement jelement = new JsonParser().parse(cl.cl.get("result").asString());
            return jelement.getAsJsonObject();

        } catch (final CLException e) {
            res.addProperty("error", e.getMessage());
            System.err.println(e.getMessage());
        } finally {
            cl.outWriter.flush();
            cl.errWriter.flush();
        }

    } catch (final Exception e) {
        res.addProperty("error", e.getMessage());
        System.err.println(e.getMessage());
    }

    return res;
}

From source file:cloudlens.parser.ASTBuilder.java

License:Apache License

public static List<ASTParagraph> parseZeppelinExport(String file) throws FileNotFoundException, IOException {
    final List<ASTParagraph> res = new ArrayList<>();
    try (final FileReader rd = new FileReader(file);) {
        final JsonObject notebook = new JsonParser().parse(rd).getAsJsonObject();
        final JsonArray paragraphs = notebook.getAsJsonArray("paragraphs");

        final Iterator<JsonElement> it = paragraphs.iterator();
        while (it.hasNext()) {
            final JsonObject p = it.next().getAsJsonObject();
            final JsonPrimitive textOpt = p.getAsJsonPrimitive("text");
            if (textOpt != null) {
                final String text = textOpt.getAsString();
                if (text.startsWith("%cl")) {
                    final String content = text.substring(3);
                    final List<ASTElement> elements = parse(content);
                    res.add(new ASTParagraph(elements));
                } else {
                    res.add(new ASTParagraph(text));
                }/*from   w  w w . ja v  a2s  .  c  o m*/
            }
        }
    }
    return res;

}

From source file:club.jmint.crossing.client.CrossingClient.java

License:Apache License

public CallResult serviceCall(String inf, JsonObject params, boolean isEncrypt) {
    String result = null;//from   www  . j  a  v a 2 s . c o m
    CallResult cr = new CallResult();
    try {
        if (isEncrypt) {
            result = call(inf, params.toString(), true);
        } else {
            result = call(inf, params.toString());
        }
    } catch (CrossException e) {
        CrossLog.printStackTrace(e);
        CrossLog.logger.error("service call failed.");
        return null;
    }

    JsonParser jp = new JsonParser();
    JsonObject jo;
    try {
        jo = (JsonObject) jp.parse(result);
    } catch (JsonSyntaxException e) {
        CrossLog.printStackTrace(e);
        CrossLog.logger.error("service call failed.");
        return null;
    }

    cr.errorCode = jo.getAsJsonPrimitive("errorCode").getAsInt();
    if (cr.errorCode == ErrorCode.SUCCESS.getCode()) {
        cr.isSuccess = true;
    } else {
        cr.isSuccess = false;
    }
    cr.errorInfo = jo.getAsJsonPrimitive("errorInfo").getAsString();
    if (jo.has("params")) {
        cr.data = jo.getAsJsonObject("params");
    }

    return cr;
}

From source file:club.jmint.crossing.specs.CrossingService.java

License:Apache License

protected JsonObject parseInputParams(String params, boolean encrypt) throws CrossException {
    //parsing//from  w w w .j a v  a2s .  c o  m
    JsonParser jp = new JsonParser();
    JsonObject jo, jode, joparams;
    try {
        jo = (JsonObject) jp.parse(params);
    } catch (JsonSyntaxException e) {
        throw new CrossException(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(),
                ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo());
    }

    String encrypted, jsonParams;
    if (encrypt) {
        if (!jo.has("encrypted")) {
            throw new CrossException(ErrorCode.COMMON_ERR_PARAM_MISSING.getCode(),
                    ErrorCode.COMMON_ERR_PARAM_MISSING.getInfo());
        }
        encrypted = jo.getAsJsonPrimitive("encrypted").getAsString();
        jsonParams = buildDecrypt(encrypted);
        if (jsonParams == null) {
            throw new CrossException(ErrorCode.COMMON_ERR_DECRYPTION.getCode(),
                    ErrorCode.COMMON_ERR_DECRYPTION.getInfo());
        }
        try {
            jode = (JsonObject) jp.parse(jsonParams);
        } catch (JsonSyntaxException e) {
            throw new CrossException(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(),
                    ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo());
        }
        jo = jode;
    }

    //Check signature
    if (!jo.has("sign")) {
        throw new CrossException(ErrorCode.COMMON_ERR_SIGN_MISSING.getCode(),
                ErrorCode.COMMON_ERR_SIGN_MISSING.getInfo());
    }
    String signValue = jo.getAsJsonPrimitive("sign").getAsString();
    if (!jo.has("params")) {
        throw new CrossException(ErrorCode.COMMON_ERR_PARAM_MISSING.getCode(),
                ErrorCode.COMMON_ERR_PARAM_MISSING.getInfo());
    }
    String inputparams = jo.getAsJsonObject("params").toString();

    String signCheck = buildSign(inputparams, signKey);
    if (!signCheck.equals(signValue)) {
        throw new CrossException(ErrorCode.COMMON_ERR_SIGN_BAD.getCode(),
                ErrorCode.COMMON_ERR_SIGN_BAD.getInfo());
    }

    try {
        joparams = (JsonObject) jp.parse(inputparams);
    } catch (JsonSyntaxException e) {
        throw new CrossException(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(),
                ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo());
    }

    return joparams;
}