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: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);
        }//ww  w  .  j  a  v  a 2  s.com
        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: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  .j a va2  s  .co  m*/
            }
        }
    }
    return res;

}

From source file:com.addthis.hydra.task.source.bundleizer.GsonBundleizer.java

License:Apache License

public ValueObject fromGson(JsonElement gson) {
    if (gson.isJsonNull()) {
        return null;
    } else if (gson.isJsonObject()) {
        JsonObject object = gson.getAsJsonObject();
        ValueMap map = ValueFactory.createMap();
        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            map.put(entry.getKey(), fromGson(entry.getValue()));
        }//from ww  w  .j  a va  2 s  .  co  m
        return map;
    } else if (gson.isJsonArray()) {
        JsonArray gsonArray = gson.getAsJsonArray();
        ValueArray valueArray = ValueFactory.createArray(gsonArray.size());
        for (JsonElement arrayElement : gsonArray) {
            valueArray.add(fromGson(arrayElement));
        }
        return valueArray;
    } else {
        JsonPrimitive primitive = gson.getAsJsonPrimitive();
        if (primitive.isNumber()) {
            return ValueFactory.create(primitive.getAsDouble());
        } else {
            return ValueFactory.create(primitive.getAsString());
        }
    }
}

From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java

License:Apache License

/**
 * Set generic array property for a resource, based on an array found in the retrieved JSON.
 *
 * @param jsonArray JsonArray/*from www .ja  v  a 2  s.  com*/
 * @param key String
 * @param resource Resource
 * @throws RepositoryException exception
 */
private void setNodeSimpleArrayProperty(final JsonArray jsonArray, final String key, final Resource resource)
        throws RepositoryException {
    JsonPrimitive firstVal = jsonArray.get(0).getAsJsonPrimitive();

    try {
        Object[] values;
        if (firstVal.isBoolean()) {
            values = new Boolean[jsonArray.size()];
            for (int i = 0; i < jsonArray.size(); i++) {
                values[i] = jsonArray.get(i).getAsBoolean();
            }
        } else if (DECIMAL_REGEX.matcher(firstVal.getAsString()).matches()) {
            values = new BigDecimal[jsonArray.size()];
            for (int i = 0; i < jsonArray.size(); i++) {
                values[i] = jsonArray.get(i).getAsBigDecimal();
            }
        } else if (firstVal.isNumber()) {
            values = new Long[jsonArray.size()];
            for (int i = 0; i < jsonArray.size(); i++) {
                values[i] = jsonArray.get(i).getAsLong();
            }
        } else {
            values = new String[jsonArray.size()];
            for (int i = 0; i < jsonArray.size(); i++) {
                values[i] = jsonArray.get(i).getAsString();
            }
        }

        ValueMap resourceProperties = resource.adaptTo(ModifiableValueMap.class);
        resourceProperties.put(key, values);
        LOG.trace("Array property '{}' added for resource '{}'", key, resource.getPath());
    } catch (Exception e) {
        LOG.error("Unable to assign property '{}' to resource '{}'", key, resource.getPath(), e);
    }
}

From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java

License:Apache License

/**
 * Set a simple resource property from the fetched JSON.
 *
 * @param value Object/*from   w  w  w  .  j a v a 2s  .co m*/
 * @param key String
 * @param resource Resource
 * @throws RepositoryException exception
 */
private void setNodeSimpleProperty(final JsonPrimitive value, final String key, final Resource resource)
        throws RepositoryException {
    ValueMap resourceProperties = resource.adaptTo(ModifiableValueMap.class);
    if (value.isString() && DATE_REGEX.matcher(value.getAsString()).matches()) {
        try {
            resourceProperties.put(key,
                    GregorianCalendar.from(ZonedDateTime.parse(value.getAsString(), DATE_TIME_FORMATTER)));
        } catch (DateTimeParseException e) {
            LOG.warn("Unable to parse date '{}' for property:resource '{}'.", value,
                    key + ":" + resource.getPath());
        }
    } else if (value.isString() && DECIMAL_REGEX.matcher(value.getAsString()).matches()) {
        resourceProperties.put(key, value.getAsBigDecimal());
    } else if (value.isBoolean()) {
        resourceProperties.put(key, value.getAsBoolean());
    } else if (value.isNumber()) {
        if (DECIMAL_REGEX.matcher(value.getAsString()).matches()) {
            resourceProperties.put(key, value.getAsBigDecimal());
        } else {
            resourceProperties.put(key, value.getAsLong());
        }
    } else if (value.isJsonNull()) {
        resourceProperties.remove(key);
    } else {
        resourceProperties.put(key, value.getAsString());
    }

    LOG.trace("Property '{}' added for resource '{}'.", key, resource.getPath());
}

From source file:com.arcbees.vcs.util.PolymorphicTypeAdapter.java

License:Apache License

@Override
public T deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObject = json.getAsJsonObject();
    JsonPrimitive jsonPrimitive = (JsonPrimitive) jsonObject.get(CLASSNAME);
    String className = jsonPrimitive.getAsString();

    Class<?> clazz;/*from   ww w .  j a v  a 2s.  c  o  m*/
    try {
        clazz = Class.forName(className);
    } catch (ClassNotFoundException e) {
        throw new JsonParseException(e.getMessage());
    }

    return context.deserialize(jsonObject.get(VALUE), clazz);
}

From source file:com.balajeetm.mystique.core.module.GsonSerialiser.java

License:Open Source License

@Override
public void serialize(JsonElement value, JsonGenerator gen, SerializerProvider provider) throws IOException {
    if (jsonLever.isNull(value)) {
        gen.writeNull();//from  ww  w .  j  a  va 2  s. c o m
    } else if (jsonLever.isObject(value)) {
        gen.writeStartObject();
        JsonObject jsonObject = value.getAsJsonObject();
        for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            gen.writeFieldName(entry.getKey());
            serialize(entry.getValue(), gen, provider);
        }
        gen.writeEndObject();
    } else if (jsonLever.isArray(value)) {
        gen.writeStartArray();
        JsonArray jsonArray = value.getAsJsonArray();
        for (JsonElement jsonElement : jsonArray) {
            serialize(jsonElement, gen, provider);
        }
        gen.writeEndArray();
    } else if (jsonLever.isPrimitive(value)) {
        JsonPrimitive jsonPrimitive = value.getAsJsonPrimitive();
        if (jsonPrimitive.isBoolean()) {
            gen.writeBoolean(jsonPrimitive.getAsBoolean());
        }
        if (jsonPrimitive.isNumber()) {
            Number nnode = jsonPrimitive.getAsNumber();
            if (nnode instanceof LazilyParsedNumber) {
                gen.writeNumber(nnode.toString());
            } else if (nnode instanceof Integer) {
                gen.writeNumber(nnode.intValue());
            } else if (nnode instanceof Short) {
                gen.writeNumber(nnode.shortValue());
            } else if (nnode instanceof BigInteger || nnode instanceof Long) {
                gen.writeNumber(nnode.longValue());
            } else if (nnode instanceof Float) {
                gen.writeNumber(nnode.floatValue());
            } else if (nnode instanceof Double || nnode instanceof BigDecimal) {
                gen.writeNumber(nnode.doubleValue());
            }
        }
        if (jsonPrimitive.isString()) {
            gen.writeString(jsonPrimitive.getAsString());
        }
    }
}

From source file:com.blackducksoftware.integration.hub.detect.detector.npm.NpmCliParser.java

License:Apache License

private void populateChildren(final MutableDependencyGraph graph, final Dependency parentDependency,
        final JsonObject parentNodeChildren, final Boolean root) {
    if (parentNodeChildren == null) {
        return;//from   w ww .j  a va  2  s.co m
    }
    final Set<Entry<String, JsonElement>> elements = parentNodeChildren.entrySet();
    elements.forEach(it -> {
        if (it.getValue() != null && it.getValue().isJsonObject()) {

        }
        final JsonObject element = it.getValue().getAsJsonObject();
        final String name = it.getKey();
        String version = null;
        final JsonPrimitive versionPrimitive = element.getAsJsonPrimitive(JSON_VERSION);
        if (versionPrimitive != null && versionPrimitive.isString()) {
            version = versionPrimitive.getAsString();
        }
        final JsonObject children = element.getAsJsonObject(JSON_DEPENDENCIES);

        if (name != null && version != null) {
            final ExternalId externalId = externalIdFactory.createNameVersionExternalId(Forge.NPM, name,
                    version);
            final Dependency child = new Dependency(name, version, externalId);

            populateChildren(graph, child, children, false);
            if (root) {
                graph.addChildToRoot(child);
            } else {
                graph.addParentWithChild(parentDependency, child);
            }
        }
    });
}

From source file:com.blackypaw.mc.i18n.chat.ChatComponentDeserializer.java

License:Open Source License

/**
 * Creates a text component given its JSON representation. Both the shorthand notation as
 * a raw string as well as the notation as a full-blown JSON object are supported.
 *
 * @param json The JSON element to be deserialized into a text component
 *
 * @return The deserialized TextComponent
 *///from   w ww.j a va  2 s.  com
private TextComponent deserializeTextComponent(JsonElement json) {
    final TextComponent component = new TextComponent("");

    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            component.setText(primitive.getAsString());
        }
    } else if (json.isJsonObject()) {
        JsonObject object = json.getAsJsonObject();

        if (object.has("text")) {
            JsonElement textElement = object.get("text");
            if (textElement.isJsonPrimitive()) {
                JsonPrimitive textPrimitive = textElement.getAsJsonPrimitive();
                if (textPrimitive.isString()) {
                    component.setText(textPrimitive.getAsString());
                }
            }
        }

        if (object.has("extra")) {
            JsonElement extraElement = object.get("extra");
            if (extraElement.isJsonArray()) {
                JsonArray extraArray = extraElement.getAsJsonArray();
                for (int i = 0; i < extraArray.size(); ++i) {
                    JsonElement fieldElement = extraArray.get(i);
                    component.addChild(this.deserializeComponent(fieldElement));
                }
            }
        }
    }

    return component;
}

From source file:com.builtbroken.builder.html.parts.HTMLPartHeader.java

@Override
public String process(JsonElement value) {
    try {// w w  w.  j  a  va2 s  .co m
        if (value.isJsonObject() && !value.isJsonPrimitive()) {
            JsonObject h = value.getAsJsonObject();
            String text = h.getAsJsonPrimitive("text").getAsString();
            int size = 2;
            if (h.has("size")) {
                JsonPrimitive p = h.getAsJsonPrimitive("size");
                if (p.isString()) {
                    String s = p.getAsString().toLowerCase();
                    if (s.equals("small")) {
                        size = 3;
                    } else if (s.equals("medium")) {
                        size = 2;
                    } else if (s.equals("large")) {
                        size = 1;
                    }
                } else {
                    size = p.getAsInt();
                }
            }
            if (h.has("link")) {
                String link = h.getAsJsonPrimitive("link").getAsString();
                if (link.startsWith("url")) {
                    return "<h" + size + "><a href=\"" + link + "\">" + text + "</a></h" + size + ">";
                } else if (link.endsWith(".json")) {
                    return "<h" + size + "><a href=\"#PageRef:" + link + "#\">" + text + "</a></h" + size + ">";
                } else {
                    return "<h" + size + "><a href=\"#" + link + "#\">" + text + "</a></h" + size + ">";
                }
            }
            return "<h" + size + ">" + text + "</h" + size + ">";
        }
        return "<h2>" + value.getAsString() + "</h2>";
    } catch (Exception e) {
        throw new RuntimeException("Unexpected error while parsing header tag " + value, e);
    }
}