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

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

Introduction

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

Prototype

public final void setLenient(boolean lenient) 

Source Link

Document

Configure this parser to be liberal in what it accepts.

Usage

From source file:de.feike.tiingoclient.JSON.java

License:Apache License

/**
 * Deserialize the given JSON string to Java object.
 *
 * @param <T>/* w ww .j a v a 2 s .  co m*/
 *            Type
 * @param body
 *            The JSON string
 * @param returnType
 *            The type to deserialize into
 * @return The deserialized Java object
 */
@SuppressWarnings("unchecked")
public <T> T deserialize(String body, Type returnType) {
    try {
        if (apiClient.isLenientOnJson()) {
            JsonReader jsonReader = new JsonReader(new StringReader(body));
            // see
            // https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
            jsonReader.setLenient(true);
            return gson.fromJson(jsonReader, returnType);
        } else {
            return gson.fromJson(body, returnType);
        }
    } catch (JsonParseException e) {
        // Fallback processing when failed to parse JSON form response body:
        // return the response body string directly for the String return
        // type;
        // parse response body into date or datetime for the Date return
        // type.
        if (returnType.equals(String.class))
            return (T) body;
        else if (returnType.equals(Date.class))
            return (T) apiClient.parseDateOrDatetime(body);
        else
            throw (e);
    }
}

From source file:de.itboehmer.confluence.rest.core.BaseClient.java

License:Apache License

protected JsonReader toJsonReader(InputStream inputStream) throws UnsupportedEncodingException {
    Validate.notNull(inputStream);/*from ww w  . j  a v  a  2  s .c  o m*/
    InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
    JsonReader jsonReader = new JsonReader(reader);
    jsonReader.setLenient(true);
    return jsonReader;
}

From source file:de.micromata.jira.rest.core.util.RestException.java

License:Apache License

public RestException(HttpMethod method) {
    this.statusCode = method.getStatusCode();
    this.reasonPhrase = method.getStatusText();
    try {/*from   ww  w .  j av  a2  s .  co m*/
        InputStream inputStream = method.getResponseBodyAsStream();
        if (inputStream != null) {
            InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
            JsonReader jsonReader = new JsonReader(reader);
            jsonReader.setLenient(true);
            Gson gson = new Gson();
            restErrorMessage = gson.fromJson(jsonReader, ErrorBean.class);
        }
    } catch (IOException e) {
        // nothing to say
    } finally {
        method.releaseConnection();
    }

}

From source file:de.odysseus.staxon.json.stream.gson.GsonStreamFactory.java

License:Apache License

@Override
public JsonStreamSource createJsonStreamSource(Reader reader) {
    JsonReader jsonReader = new JsonReader(new FilterReader(reader) {
        @Override//from www  .j  a  v a2s .c  om
        public void close() throws IOException {
            // avoid closing underlying stream
        }
    });
    jsonReader.setLenient(false);
    return new GsonStreamSource(jsonReader);
}

From source file:defrac.intellij.config.ConfigCache.java

License:Apache License

@NotNull
private static JsonReader lenientReader(@NotNull final Reader reader) {
    final JsonReader jsonReader = new JsonReader(reader);
    jsonReader.setLenient(true);
    return jsonReader;
}

From source file:ed.cracken.code.servlets.PushHandler.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w w.j  a v a2 s  . c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
    String json = "";
    StringBuilder sb = new StringBuilder();
    while ((json = br.readLine()) != null) {
        sb.append(json);
    }
    br.close();

    System.out.println(">> " + sb.toString());
    JsonReader reader = new JsonReader(new StringReader(sb.toString()));
    reader.setLenient(true);
    Persona persona = new Gson().fromJson(reader, Persona.class);
    IDsManager idsManager;
    if ((idsManager = (IDsManager) request.getServletContext().getAttribute("idsmanager")) == null) {
        idsManager = new IDsManager();
        request.getServletContext().setAttribute("idsmanager", idsManager);
    }
    idsManager.getIds().put(persona.getSession(), persona);

    response.setStatus(HttpServletResponse.SC_ACCEPTED);

}

From source file:edu.berkeley.ground.plugins.hive.util.PluginUtil.java

License:Apache License

public static <T> T fromJson(JsonReader reader, Class<T> clazz) {
    reader.setLenient(true);
    Gson gson = new Gson();
    return gson.fromJson(reader, clazz);
}

From source file:email.mandrill.MandrillApiHandler.java

public static Map<String, Object> getEmailDetails(String mandrillEmailId)
        throws URISyntaxException, IOException {
    Map<String, Object> emailDetails = new HashMap<>();
    HttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("https://mandrillapp.com/api/1.0/messages/info.json");
    URI uri = new URIBuilder(httpGet.getURI()).addParameter("key", SendEmail.MANDRILL_KEY)
            .addParameter("id", mandrillEmailId).build();
    logger.info("Getting Email details: " + uri.toString());
    Gson gson = new Gson();
    httpGet.setURI(uri);/*from ww w  .  j ava 2 s  . co m*/

    //Execute and get the response.
    HttpResponse response = httpclient.execute(httpGet);
    HttpEntity responseEntity = response.getEntity();
    if (responseEntity != null) {
        String jsonContent = EntityUtils.toString(responseEntity);
        logger.info(jsonContent);
        // Create a Reader from String
        Reader stringReader = new StringReader(jsonContent);

        // Pass the string reader to JsonReader constructor
        JsonReader reader = new JsonReader(stringReader);
        reader.setLenient(true);
        Map<String, Object> mandrillEmailDetails = gson.fromJson(reader, Map.class);
        emailDetails.put("sent_on", mandrillEmailDetails.get("ts"));
        emailDetails.put("mandrill_id", mandrillEmailDetails.get("_id"));
        emailDetails.put("email_state", mandrillEmailDetails.get("state"));
        emailDetails.put("subject", mandrillEmailDetails.get("subject"));
        emailDetails.put("email", mandrillEmailDetails.get("email"));
        emailDetails.put("tags", mandrillEmailDetails.get("tags"));
        emailDetails.put("opens", mandrillEmailDetails.get("opens"));
        emailDetails.put("clicks", mandrillEmailDetails.get("clicks"));
        emailDetails.put("sender", mandrillEmailDetails.get("sender"));

    }

    return emailDetails;
}

From source file:email.mandrill.MandrillApiHandler.java

public static List<Map<String, Object>> getTags() {
    List<Map<String, Object>> mandrillTagList = new ArrayList<>();

    try {//from  ww  w  . j  a  v a  2 s.c  om

        HttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("https://mandrillapp.com/api/1.0/tags/list.json");
        URI uri = new URIBuilder(httpGet.getURI()).addParameter("key", SendEmail.MANDRILL_KEY).build();
        logger.info("Getting mandrill tags: " + uri.toString());
        Gson gson = new Gson();
        httpGet.setURI(uri);

        //Execute and get the response.
        HttpResponse response = httpclient.execute(httpGet);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            String jsonContent = EntityUtils.toString(responseEntity);
            logger.info(jsonContent);
            // Create a Reader from String
            Reader stringReader = new StringReader(jsonContent);

            // Pass the string reader to JsonReader constructor
            JsonReader reader = new JsonReader(stringReader);
            reader.setLenient(true);
            mandrillTagList = gson.fromJson(reader, List.class);

        }

    } catch (URISyntaxException ex) {
        Logger.getLogger(MandrillApiHandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MandrillApiHandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(MandrillApiHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return mandrillTagList;
}

From source file:geomesa.example.twitter.ingest.TwitterParser.java

License:Apache License

/**
 * Parse an input stream using GSON//from w  ww  .  j  a va 2  s .c  o  m
 */
public List<SimpleFeatureCollection> parse(final InputStream is, final String sourceName) throws IOException {
    log.info(sourceName + " - starting parsing");

    final long startTime = System.currentTimeMillis();

    final List<SimpleFeatureCollection> results = new ArrayList<>();
    final Reader bufReader = new BufferedReader(new InputStreamReader(is));
    final JsonReader jr = new JsonReader(bufReader);
    jr.setLenient(true);

    DefaultFeatureCollection batch = new DefaultFeatureCollection(featureName, twitterType);

    long numGoodTweets = 0;
    long numBadTweets = 0;
    JsonObject obj;
    while ((obj = next(jsonParser, jr, sourceName)) != null) {
        SimpleFeature sf = null;
        try {
            sf = convertToFeature(obj, builder, geoFac, df);
        } catch (Exception e) {
            // parsing error
        }
        if (sf != null && sf.getDefaultGeometry() != null) {
            batch.add(sf);
            numGoodTweets++;
            if (numGoodTweets % BATCH_SIZE == 0) {
                results.add(batch);
                batch = new DefaultFeatureCollection(featureName, twitterType);
            }
            if (numGoodTweets % 100_000 == 0) {
                log.debug(Long.toString(numGoodTweets) + " records parsed");
            }
        } else {
            numBadTweets++;
        }
    }
    // add remaining results
    if (!batch.isEmpty()) {
        results.add(batch);
    }
    final long parseTime = System.currentTimeMillis() - startTime;
    log.info(sourceName + " - parsed " + numGoodTweets + " skipping " + numBadTweets + " invalid tweets in "
            + parseTime + "ms");
    return results;
}