Example usage for com.google.gson JsonParser JsonParser

List of usage examples for com.google.gson JsonParser JsonParser

Introduction

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

Prototype

@Deprecated
public JsonParser() 

Source Link

Usage

From source file:ch.cern.db.flume.sink.elasticsearch.serializer.JSONtoElasticSearchEventSerializer.java

License:GNU General Public License

private void appendBody(XContentBuilder builder, Event event) throws IOException {
    JsonParser parser = new JsonParser();

    JsonObject json = parser.parse(new String(event.getBody())).getAsJsonObject();

    for (Entry<String, JsonElement> property : json.entrySet()) {

        if (property.getValue().isJsonNull()) {
            builder.nullField(property.getKey());

            continue;
        }//from  w  w  w.  ja v a  2  s  . c  o m

        if (!property.getValue().isJsonPrimitive()) {
            builder.field(property.getKey(), property.getValue());

            continue;
        }

        JsonPrimitive primitiveValue = (JsonPrimitive) property.getValue();

        if (primitiveValue.isBoolean())
            builder.field(property.getKey(), primitiveValue.getAsBoolean());
        else if (primitiveValue.isNumber())
            if (primitiveValue.getAsString().indexOf('.') != -1)
                builder.field(property.getKey(), primitiveValue.getAsNumber().doubleValue());
            else
                builder.field(property.getKey(), primitiveValue.getAsNumber().longValue());
        else if (primitiveValue.isString())
            builder.field(property.getKey(), primitiveValue.getAsString());
    }
}

From source file:ch.cern.db.flume.sink.kite.parser.JSONtoAvroParser.java

License:GNU General Public License

/**
 * Parse the entity from the body in JSON of the given event.
 * //from w w w.jav  a2 s  .c  o m
 * @param event
 *            The event to parse.
 * @param reuse
 *            If non-null, this may be reused and returned from this method.
 * @return The parsed entity as a GenericRecord.
 * @throws EventDeliveryException
 *             A recoverable error such as an error downloading the schema
 *             from the URL has occurred.
 * @throws NonRecoverableEventException
 *             A non-recoverable error such as an unparsable schema or
 *             entity has occurred.
 */
@Override
public GenericRecord parse(Event event, GenericRecord reuse)
        throws EventDeliveryException, NonRecoverableEventException {

    JsonObject parser = new JsonParser().parse(new String(event.getBody())).getAsJsonObject();

    GenericRecordBuilder recordBuilder = new GenericRecordBuilder(datasetSchema);
    for (Field field : datasetSchema.getFields()) {
        String at_header = field.getProp(FIELD_AT_HEADER_PROPERTY);

        if (at_header != null && at_header.equals(Boolean.TRUE.toString())) {
            recordBuilder.set(field.name(), event.getHeaders().get(field.name()));
        } else {
            JsonElement element = parser.get(field.name());

            recordBuilder.set(field.name(), getElementAsType(field.schema(), element));
        }
    }

    return recordBuilder.build();
}

From source file:ch.cern.db.flume.source.deserializer.RecoveryManagerDeserializer.java

License:GNU General Public License

/**
 * Reads a line from a file and returns an event
 * //w  w  w. j  ava2 s  .  co  m
 * @return Event containing parsed line
 * @throws IOException
 */
@Override
public Event readEvent() throws IOException {
    ensureOpen();

    in.mark();
    if (in.read() == -1)
        return null;
    in.reset();

    RecoveryManagerLogFile rman_log = new RecoveryManagerLogFile(in, maxLineLength);

    JSONEvent event = new JSONEvent();

    event.addProperty("startTimestamp", rman_log.getStartTimestamp());
    event.addProperty("backupType", rman_log.getBackupType());
    event.addProperty("destination", rman_log.getBackupDestination());
    event.addProperty("entityName", rman_log.getEntityName());

    //Process properties like (name = value)
    for (Pair<String, String> property : rman_log.getProperties())
        event.addProperty(property.getFirst(), property.getSecond());

    String v_params = rman_log.getVParams();
    event.addProperty("v_params", v_params != null ? new JsonParser().parse(v_params).getAsJsonObject() : null);

    JsonArray mountPointNASRegexResult = rman_log.getMountPointNASRegexResult();
    event.addProperty("mountPointNASRegexResult", mountPointNASRegexResult);

    JsonArray volInfoBackuptoDiskFinalResult = rman_log.getVolInfoBackuptoDiskFinalResult();
    event.addProperty("volInfoBackuptoDiskFinalResult", volInfoBackuptoDiskFinalResult);

    JsonArray valuesOfFilesystems = rman_log.getValuesOfFilesystems();
    event.addProperty("valuesOfFilesystems", valuesOfFilesystems);

    List<RecoveryManagerReport> recoveryManagerReports = rman_log.getRecoveryManagerReports();
    JsonArray recoveryManagerReportsJson = recoveryManagerReportsToJSON(recoveryManagerReports);
    event.addProperty("recoveryManagerReports", recoveryManagerReportsJson);

    int recoveryManagerReportsSize = recoveryManagerReportsJson.size();
    if (recoveryManagerReportsSize > 0) {
        JsonObject lastReport = (JsonObject) recoveryManagerReportsJson.get(recoveryManagerReportsSize - 1);

        event.addProperty("finishTime", lastReport.get("finishTime"));
        event.addProperty("finalStatus", lastReport.get("status"));
    } else {
        event.addProperty("finishTime", null);
        event.addProperty("finalStatus", null);
    }

    return event;
}

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 w w .  j  a v a 2s .  co  m
        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();
            }/*from   ww w.ja va  2s . c om*/
        }
        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);
        }/*w  w w. j  av  a2  s .c  o  m*/
        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:ch.iterate.openstack.swift.Client.java

License:Open Source License

/**
 * Lists the segments associated with an existing object.
 *
 * @param region    The name of the storage region
 * @param container The name of the container
 * @param name      The name of the object
 * @return a Map from container to lists of storage objects if a large object is present, otherwise null
 *///from ww  w .  ja v a  2 s . com
public Map<String, List<StorageObject>> listObjectSegments(Region region, String container, String name)
        throws IOException {

    Map<String, List<StorageObject>> existingSegments = new HashMap<String, List<StorageObject>>();

    try {
        ObjectMetadata existingMetadata = getObjectMetaData(region, container, name);

        if (existingMetadata.getMetaData().containsKey(Constants.MANIFEST_HEADER)) {
            /*
             * We have found an existing dynamic large object, so use the prefix to get a list of
             * existing objects. If we're putting up a new dlo, make sure the segment prefixes are
             * different, then we can delete anything that's not in the new list if necessary.
             */
            String manifestDLO = existingMetadata.getMetaData().get(Constants.MANIFEST_HEADER);
            String segmentContainer = manifestDLO.substring(1, manifestDLO.indexOf('/', 1));
            String segmentPath = manifestDLO.substring(manifestDLO.indexOf('/', 1), manifestDLO.length());
            existingSegments.put(segmentContainer, this.listObjects(region, segmentContainer, segmentPath));
        } else if (existingMetadata.getMetaData().containsKey(Constants.X_STATIC_LARGE_OBJECT)) {
            /*
             * We have found an existing static large object, so grab the manifest data that
             * details the existing segments - delete any later that we don't need any more
             */
            boolean isSLO = "true".equals(existingMetadata.getMetaData().get(Constants.X_STATIC_LARGE_OBJECT)
                    .toLowerCase(Locale.ENGLISH));
            if (isSLO) {
                final JsonParser parser = new JsonParser();
                URIBuilder urlBuild = new URIBuilder(region.getStorageUrl(container, name));
                urlBuild.setParameter("multipart-manifest", "get");
                URI url = urlBuild.build();
                HttpGet method = new HttpGet(url);
                Response response = this.execute(method);
                if (response.getStatusCode() == HttpStatus.SC_OK) {
                    String manifest = response.getResponseBodyAsString();
                    JsonArray segments = parser.parse(manifest).getAsJsonArray();
                    for (JsonElement o : segments) {
                        /*
                         * Parse each JSON object in the list and create a list of Storage Objects
                         */
                        JsonObject segment = o.getAsJsonObject();
                        String objectPath = segment.get("name").getAsString();
                        String segmentContainer = objectPath.substring(1, objectPath.indexOf('/', 1));
                        String segmentPath = objectPath.substring(objectPath.indexOf('/', 1) + 1,
                                objectPath.length());
                        List<StorageObject> containerSegments = existingSegments.get(segmentContainer);
                        if (containerSegments == null) {
                            containerSegments = new ArrayList<StorageObject>();
                            existingSegments.put(segmentContainer, containerSegments);
                        }
                        final StorageObject object = new StorageObject(segmentPath);
                        object.setSize(Long.valueOf(segment.get("bytes").getAsString()));
                        object.setMd5sum(segment.get("hash").getAsString());
                        object.setLastModified(segment.get("last_modified").getAsString());
                        object.setMimeType(segment.get("content_type").getAsString());
                        containerSegments.add(object);
                    }
                } else {
                    method.abort();
                    throw new GenericException(response);
                }
            }
        } else {
            /*
             * Not a large object, so return null
             */
            return null;
        }
    } catch (NotFoundException e) {
        /*
         * Just means no object exists with the specified region, container and name
         */
        return null;
    } catch (JsonParseException e) {
        throw new GenericException("JSON parsing failed reading static large object manifest", e);
    } catch (URISyntaxException e) {
        throw new GenericException("URI Building failed reading static large object manifest", e);
    }

    return existingSegments;
}

From source file:ch.jamiete.hilda.configuration.Configuration.java

License:Apache License

public void load() {
    if (!this.file.exists()) {
        this.json = new JsonObject();
        return;// w ww .  j a v  a 2s. c  o  m
    }

    Charset charset = null;

    try {
        charset = Charset.forName("UTF-8");
    } catch (final Exception e) {
        charset = Charset.defaultCharset();
    }

    try {
        this.json = new JsonParser().parse(FileUtils.readFileToString(this.file, charset)).getAsJsonObject();
    } catch (final IOException e) {
        Hilda.getLogger().log(Level.WARNING,
                "Encountered an exception while loading configuration " + this.file.getName(), e);
        this.json = new JsonObject();
    }

    if (new Gson().toJson(this.json).equals("{}")) {
        try {
            this.file.delete();
        } catch (final Exception e) {
            // Ignore
        }
    }
}

From source file:ch.there.gson.GsonInvokerServiceExporter.java

License:Apache License

@Override
public void handle(HttpExchange exchange) throws IOException {
    Gson gson = GsonFactory.getGson();/*from  w w  w . j a  v  a  2 s  .c o  m*/

    try {
        Integer rpcVersion = Integer.valueOf(exchange.getRequestHeaders().getFirst("rpc-version"));
        CallerRemoteApiVersion.setVersion(rpcVersion);
        InputStreamReader reader = new InputStreamReader(exchange.getRequestBody());
        JsonParser parser = new JsonParser();
        JsonObject remote = parser.parse(reader).getAsJsonObject();
        String methodName = remote.get("methodName").getAsString();

        Type collectionType = new TypeToken<Collection<Class<?>>>() {
        }.getType();
        Collection<Class<?>> parameterTypes = gson.fromJson(remote.get("parameterTypes"), collectionType);

        JsonArray args = remote.get("arguments").getAsJsonArray();
        Class<?>[] params = parameterTypes.toArray(new Class[parameterTypes.size()]);

        Object[] arguments = new Object[params.length];

        for (int i = 0; i < params.length; i++) {
            Class<?> clazz = params[i];
            Object argument = gson.fromJson(args.get(i), clazz);
            arguments[i] = argument;
        }

        RemoteInvocation remoteInvocation = new RemoteInvocation(methodName, params, arguments);
        RemoteInvocationResult result = invokeAndCreateResult(remoteInvocation, getProxy());
        writeRemoteInvocationResult(exchange, result);
        exchange.close();
    } catch (Throwable e) {
        e.printStackTrace();
    }

}

From source file:cheerPackage.JSONUtils.java

public static String getJsonAttributeValue(String rawJson, String attribute)
        throws MalformedJsonException, JsonSyntaxException {
    //just a single Json Object
    JsonParser parser = new JsonParser();
    JsonElement json = parser.parse(rawJson);
    if (json.isJsonObject()) {
        return json.getAsJsonObject().get(attribute).getAsString();
    } else if (json.isJsonPrimitive()) {
        return json.getAsString();
    } else {/*from w w w .  ja  v  a  2s  .c  o m*/
        System.out.println(
                "This function only works on Json objects and primitives, use getValieFromArrayElement for arrays");
        return null;
    }
}