Example usage for com.google.gson.stream JsonReader JsonReader

List of usage examples for com.google.gson.stream JsonReader JsonReader

Introduction

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

Prototype

public JsonReader(Reader in) 

Source Link

Document

Creates a new instance that reads a JSON-encoded stream from in .

Usage

From source file:org.apache.accumulo.core.clientImpl.bulk.LoadMappingIterator.java

License:Apache License

LoadMappingIterator(TableId tableId, InputStream loadMapFile) throws IOException {
    this.tableId = tableId;
    this.reader = new JsonReader(new BufferedReader(new InputStreamReader(loadMapFile, UTF_8)));
    this.reader.beginArray();
}

From source file:org.apache.airavata.workflow.core.parser.JsonWorkflowParser.java

License:Apache License

public JsonWorkflowParser(InputStreamReader inputStreamReader) {
    this(new JsonReader(inputStreamReader));
}

From source file:org.apache.ambari.funtest.server.AmbariHttpWebRequest.java

License:Apache License

@SuppressWarnings("deprecation")
private RuntimeException createRuntimeException(HttpException httpException) {
    String message = httpException.getMessage();
    try {/*from ww w . ja  va 2 s . co  m*/
        JsonElement jsonElement = new JsonParser()
                .parse(new JsonReader(new StringReader(httpException.getMessage())));
        if (jsonElement != null && jsonElement.getAsJsonObject().has("message")) {
            message = jsonElement.getAsJsonObject().get("message").getAsString();
        }
    } catch (Throwable t) {
    }
    if (httpException.getReasonCode() != HttpStatus.SC_OK) {
        message = httpException.getReasonCode() + " " + httpException.getReason() + ": " + message;
    }
    return new RuntimeException(message, httpException);
}

From source file:org.apache.ambari.funtest.server.utils.RestApiUtils.java

License:Apache License

/**
 * Executes a web request and throws an exception if the status code is incorrect.
 *
 * @param request/*w  w  w  . j a  v a 2  s . c o m*/
 * @return
 * @throws Exception
 */
public static JsonElement executeRequest(WebRequest request) throws Exception {
    WebResponse response = request.getResponse();
    int responseCode = response.getStatusCode();
    String responseBody = response.getContent();

    if (responseCode != HttpStatus.SC_OK && responseCode != HttpStatus.SC_CREATED
            && responseCode != HttpStatus.SC_ACCEPTED) {
        throw new RuntimeException(String.format("%d:%s", responseCode, responseBody));
    }

    return new JsonParser().parse(new JsonReader(new StringReader(responseBody)));
}

From source file:org.apache.ambari.server.controller.metrics.RestMetricsPropertyProvider.java

License:Apache License

/**
 * Extracts requested properties from a given JSON input stream into
 * resource.//from   w w w.j a  va  2  s.c  o  m
 *
 * @param jsonStream           input stream that contains JSON
 * @param requestedPropertyIds a set of property IDs
 *                             that should be fetched for this URL
 * @param resource             all extracted values are placed into resource
 */
private void extractValuesFromJSON(InputStream jsonStream, Set<String> requestedPropertyIds, Resource resource,
        Map<String, PropertyInfo> propertyInfos) throws IOException {
    Gson gson = new Gson();
    Type type = new TypeToken<Map<Object, Object>>() {
    }.getType();
    JsonReader jsonReader = new JsonReader(new BufferedReader(new InputStreamReader(jsonStream)));
    Map<String, String> jsonMap = gson.fromJson(jsonReader, type);
    for (String requestedPropertyId : requestedPropertyIds) {
        PropertyInfo propertyInfo = propertyInfos.get(requestedPropertyId);
        String metricsPath = propertyInfo.getPropertyId();
        String documentPath = extractDocumentPath(metricsPath);
        String[] docPath = documentPath.split(DOCUMENT_PATH_SEPARATOR);
        Map<String, String> subMap = jsonMap;
        for (int i = 0; i < docPath.length; i++) {
            String pathElement = docPath[i];
            if (!subMap.containsKey(pathElement)) {
                String message = String.format("Can not fetch %dth element of document path (%s) "
                        + "from json. Wrong metrics path: %s", i, pathElement, metricsPath);
                throw new IOException(message);
            }
            Object jsonSubElement = jsonMap.get(pathElement);
            if (i == docPath.length - 1) { // Reached target document section
                // Extract property value
                resource.setProperty(requestedPropertyId, jsonSubElement);
            } else { // Navigate to relevant document section
                subMap = gson.fromJson((JsonElement) jsonSubElement, type);
            }
        }
    }
}

From source file:org.apache.ambari.view.hive.resources.uploads.parsers.json.JSONParser.java

License:Apache License

public JSONParser(Reader reader, ParseOptions parseOptions) throws IOException {
    super(reader, parseOptions);
    this.jsonReader = new JsonReader(this.reader);
    JSONIterator = new JSONIterator(this.jsonReader);
    iterator = new RowIterator(JSONIterator);
}

From source file:org.apache.ambari.view.slider.rest.client.BaseHttpClient.java

License:Apache License

@SuppressWarnings("deprecation")
public JsonElement doGetJson(String url, String path) throws HttpException, IOException {
    GetMethod get = new GetMethod(url + path);
    if (isNeedsAuthentication()) {
        get.setDoAuthentication(true);/*w  ww .java  2s .  com*/
    }
    int executeMethod = getHttpClient().executeMethod(get);
    switch (executeMethod) {
    case HttpStatus.SC_OK:
        JsonElement jsonElement = new JsonParser()
                .parse(new JsonReader(new InputStreamReader(get.getResponseBodyAsStream())));
        return jsonElement;
    case HttpStatus.SC_NOT_FOUND:
        return null;
    default:
        HttpException httpException = new HttpException(get.getResponseBodyAsString());
        httpException.setReason(HttpStatus.getStatusText(executeMethod));
        httpException.setReasonCode(executeMethod);
        throw httpException;
    }
}

From source file:org.apache.axis2.json.gson.JsonBuilder.java

License:Apache License

public OMElement processDocument(InputStream inputStream, String s, MessageContext messageContext)
        throws AxisFault {
    messageContext.setProperty(JsonConstant.IS_JSON_STREAM, true);
    JsonReader jsonReader;//from   w  w  w .  j  a  va2s .c om
    String charSetEncoding = null;
    if (inputStream != null) {
        try {
            charSetEncoding = (String) messageContext
                    .getProperty(Constants.Configuration.CHARACTER_SET_ENCODING);
            jsonReader = new JsonReader(new InputStreamReader(inputStream, charSetEncoding));
            GsonXMLStreamReader gsonXMLStreamReader = new GsonXMLStreamReader(jsonReader);
            messageContext.setProperty(JsonConstant.GSON_XML_STREAM_READER, gsonXMLStreamReader);
        } catch (UnsupportedEncodingException e) {
            throw new AxisFault(charSetEncoding + " encoding is may not supported by json inputStream ", e);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Inputstream is null, This is possible with GET request");
        }
    }
    // dummy envelop
    SOAPFactory soapFactory = OMAbstractFactory.getSOAP11Factory();
    return soapFactory.getDefaultEnvelope();
}

From source file:org.apache.camel.component.salesforce.internal.processor.JsonRestProcessor.java

License:Apache License

@Override
protected void processResponse(Exchange exchange, InputStream responseEntity, SalesforceException ex,
        AsyncCallback callback) {/* www  . j  a v a 2s  . com*/
    // process JSON response for TypeReference
    try {
        // do we need to un-marshal a response

        if (responseEntity != null) {
            JsonReader reader = new JsonReader(new InputStreamReader(responseEntity, "UTF-8"));
            Gson gson = new GsonBuilder().create();

            Object response = null;

            Class<?> responseClass = exchange.getProperty(RESPONSE_CLASS, Class.class);
            if (responseClass != null) {

                response = gson.fromJson(reader, responseClass);

                //   System.out.println("response " + response);*/
                //      response = objectMapper.readValue(responseEntity, responseClass);
            } else {
                TypeReference<?> responseType = exchange.getProperty(RESPONSE_TYPE, TypeReference.class);
                if (responseType != null) {
                    //   System.out.println("responseType != null");
                    response = gson.fromJson(reader, responseClass);
                    //response = objectMapper.readValue(responseEntity, responseType);
                } else {
                    //   System.out.println("responseType == null");
                    // return the response as a stream, for getBlobField
                    response = responseEntity;
                }
            }
            exchange.getOut().setBody(response);
        } else {
            exchange.setException(ex);
        }
        // copy headers and attachments
        exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders());
        exchange.getOut().getAttachments().putAll(exchange.getIn().getAttachments());
    } catch (IOException e) {
        String msg = "Error parsing JSON response: " + e.getMessage();
        exchange.setException(new SalesforceException(msg, e));
    } catch (Exception e) {

        e.printStackTrace();
    }

    finally {
        // cleanup temporary exchange headers
        exchange.removeProperty(RESPONSE_CLASS);
        exchange.removeProperty(RESPONSE_TYPE);

        // consume response entity
        try {
            if (responseEntity != null) {
                responseEntity.close();
            }
        } catch (IOException ignored) {
        }

        // notify callback that exchange is done
        callback.done(false);
    }

}

From source file:org.apache.hadoop.dynamodb.importformat.ImportInputFormat.java

License:Open Source License

/**
 * An example manifest file looks like/*from   ww w .  j  a v a  2s  . c  o  m*/
 *
 * {"name":"DynamoDB-export","version":3, "entries":[
 * {"url":"s3://path/to/object/92dd1414-a049-4c68-88fb-a23acd44907e","mandatory":true},
 * {"url":"s3://path/to/object/ba3f3535-7aa1-4f97-a530-e72938bf4b76","mandatory":true} ]}
 */
// @formatter:on
private List<InputSplit> parseManifest(FileSystem fs, Path manifestPath, JobConf job) throws IOException {
    List<InputSplit> splits = null;

    FSDataInputStream fp = fs.open(manifestPath);
    JsonReader reader = new JsonReader(new InputStreamReader(fp, Charsets.UTF_8));

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        switch (name) {
        case VERSION_JSON_KEY:
            job.set(DynamoDBConstants.EXPORT_FORMAT_VERSION, String.valueOf(reader.nextInt()));
            break;
        case ENTRIES_JSON_KEY:
            splits = readEntries(reader, job);
            break;
        default:
            log.info("Skipping a JSON key in the manifest file: " + name);
            reader.skipValue();
            break;
        }
    }
    reader.endObject();

    if (splits == null) {
        return Collections.emptyList();
    }
    return splits;
}