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:edu.rpi.shuttles.data.RPIShuttleDataProvider.java

License:Apache License

public SparseArray<Stop> fetchStops() throws IOException {
    // Download stop data.
    URL stopsURL = new URL(mStopsUrl);
    URLConnection stopsConnection = stopsURL.openConnection();
    stopsConnection.setRequestProperty("User-Agent", mUserAgent);
    InputStream in = new BufferedInputStream(stopsConnection.getInputStream());
    JsonReader reader = new JsonReader(new InputStreamReader(in));
    mStops.clear();//from  w w  w .j a v  a 2  s .c  o  m
    mRouteStopsMap.clear();

    reader.beginArray();
    while (reader.hasNext()) {
        Stop stop = readStop(reader);
        mStops.put(stop.id, stop);
    }
    reader.endArray();

    reader.close();
    return mStops;
}

From source file:edu.rpi.shuttles.data.RPIShuttleDataProvider.java

License:Apache License

public SparseArray<Route> fetchRoutes() throws IOException {
    URL routesURL = new URL(mRoutesUrl);
    URLConnection routesConnection = routesURL.openConnection();
    routesConnection.setRequestProperty("User-Agent", mUserAgent);
    InputStream in = new BufferedInputStream(routesConnection.getInputStream());

    URL routePathsURL = new URL(mRoutePathsUrl);
    URLConnection routePathsConnection = routePathsURL.openConnection();
    routePathsConnection.setRequestProperty("User-Agent", mUserAgent);
    InputStream pathInputStream = new BufferedInputStream(routePathsConnection.getInputStream());

    mRoutes.clear();/*from www  .j a v a2  s .  com*/
    JsonReader routesReader = new JsonReader(new InputStreamReader(in));
    routesReader.beginArray();
    while (routesReader.hasNext()) {
        Route route = readRoute(routesReader);
        mRoutes.put(route.id, route);
    }
    routesReader.endArray();

    JsonReader routePathReader = new JsonReader(new InputStreamReader(pathInputStream));
    routePathReader.beginObject();
    while (routePathReader.hasNext()) {
        Log.d("RouteDataProvider", "Entering L1.");
        String key = routePathReader.nextName();
        Log.d("RouteDataProvider", String.format("L1: %s", key));
        if (key.equals("routes")) {
            Log.d("RouteDataProvider", "Found 'routes' tag.");
            routePathReader.beginArray();
            while (routePathReader.hasNext()) {
                populateRoutePath(routePathReader);
            }
            routePathReader.endArray();
        } else {
            Log.d("RouteDataProvider", "Found other tag.");
            routePathReader.skipValue();
        }
    }
    routePathReader.endObject();

    return mRoutes;
}

From source file:edu.rpi.shuttles.data.RPIShuttleDataProvider.java

License:Apache License

public SparseArray<Vehicle> updateVehicleLocations() throws IOException {
    // Download vehicle location data.
    URL vehicleLocationURL = new URL(mVehicleLocationsUrl);
    URLConnection vehicleLocationConnection = vehicleLocationURL.openConnection();
    vehicleLocationConnection.setRequestProperty("User-Agent", mUserAgent);
    InputStream in = new BufferedInputStream(vehicleLocationConnection.getInputStream());
    JsonReader reader = new JsonReader(new InputStreamReader(in));
    SparseArray<Vehicle> updated_vehicles = new SparseArray<Vehicle>();

    reader.beginArray();/*from w ww  . j  av  a  2s  . co m*/
    while (reader.hasNext()) {
        Vehicle shuttle = readVehicleLocation(reader);
        updated_vehicles.put(shuttle.id, shuttle);
        mVehicles.put(shuttle.id, shuttle);
    }
    reader.endArray();

    reader.close();
    return updated_vehicles;
}

From source file:edu.washington.cs.cupid.usage.CupidDataCollector.java

License:Open Source License

public synchronized String getAllJson(String indent, boolean includeNow) throws IOException {
    List<SessionLog> logs = Lists.newArrayList();

    for (File file : logDirectory.listFiles()) {
        if (file.getName().endsWith(".json")) {
            JsonReader reader = new JsonReader(new FileReader(file));
            logs.add((SessionLog) gson.fromJson(reader, SessionLog.class));
            reader.close();//from   w w  w. j a va2 s .  c o  m
        }
    }

    if (init) {
        logs.add(new SessionLog(uuid(), system, sessionLog));
    }

    StringWriter result = new StringWriter();
    JsonWriter writer = new JsonWriter(result);
    if (indent != null) {
        writer.setIndent(indent);
    }
    gson.toJson(logs, new TypeToken<List<SessionLog>>() {
    }.getType(), writer);
    writer.close();
    return result.toString();
}

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);// w  w  w .  j  av  a 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 w ww. j a va2s.com*/

        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:eu.atos.sla.service.rest.ModacloudsTranslator.java

License:Apache License

@Override
/**//from  ww  w .j  a  va  2s .com
 * Performs the translation from the data coming from the Monitor and SLA's MonitoringMetric.
 * 
 * The key of each monitor data is the name of the violation (contained in the slo), so each
 * slo containing the key must enforce that metric.
 */
public Map<IGuaranteeTerm, List<IMonitoringMetric>> translate(IAgreement agreement, String data) {
    MultivaluedMapWrapper<IGuaranteeTerm, IMonitoringMetric> resultWrapper = new MultivaluedMapWrapper<IGuaranteeTerm, IMonitoringMetric>();

    Gson gson = new Gson();
    JsonReader reader = null;
    Type type = new TypeToken<Map<String, Map<String, List<Map<String, String>>>>>() {
    }.getType();
    reader = new JsonReader(new StringReader(data));
    final Map<String, Map<String, List<Map<String, String>>>> json = gson.fromJson(reader, type);

    /*
     * key: name of violation
     */
    final MultivaluedMapWrapper<String, IGuaranteeTerm> metric2terms = initTermsMap(agreement);

    for (Map<String, List<Map<String, String>>> item : json.values()) {
        BindingHelper var = new BindingHelper(item);
        /*
         * get guarantee terms that evaluate that violation
         */
        List<IGuaranteeTerm> terms = metric2terms.get(var.key);

        if (terms == null) {
            logger.warn("List of terms handling " + var.key + " is empty");
            continue;
        }

        resultWrapper.addToKeys(terms, new MonitoringMetric(var));
    }
    logger.debug("Output metricsmap = " + resultWrapper.getMap());
    return resultWrapper.getMap();
}

From source file:eu.eexcess.federatedrecommender.evaluation.csv.CSVResultCreation.java

License:Open Source License

private EvaluationQueryList getEvaluationQueriesFromJson() {
    JsonReader reader = null;/*  ww  w  . j  a v  a 2  s .  co m*/
    try {

        reader = new JsonReader(new FileReader(directoryPath + "queriesEn-selected.json"));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    EvaluationQueryList queries = null;
    Gson gson = new GsonBuilder().create();

    queries = gson.fromJson(reader, EvaluationQueryList.class);
    return queries;
}

From source file:eu.fayder.restcountries.rest.CountryServiceBase.java

License:Mozilla Public License

protected List<? extends BaseCountry> loadJson(String filename, Class<? extends BaseCountry> clazz) {
    LOG.debug("Loading JSON " + filename);
    List<BaseCountry> countries = new ArrayList<>();
    InputStream is = CountryServiceBase.class.getClassLoader().getResourceAsStream(filename);
    Gson gson = new Gson();
    JsonReader reader;//  w ww.  ja v a2 s .  co m
    try {
        reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
        reader.beginArray();
        while (reader.hasNext()) {
            BaseCountry country = gson.fromJson(reader, clazz);
            countries.add(country);
        }
    } catch (Exception e) {
        LOG.error("Could not load JSON " + filename);
    }
    return countries;
}

From source file:eu.liveGov.libraries.livegovtoolkit.helper.LogFileHelper.java

License:Open Source License

@Override
public void webcallReady(HttpResponse response) {
    if (response != null && response.getStatusLine().getStatusCode() != 200) {
        try {/*  w ww.j a  va 2 s.c  o  m*/
            Gson gson = new Gson();
            JsonReader jr = new JsonReader(new InputStreamReader(response.getEntity().getContent()));
            ServiceApiErrorObject result = gson.fromJson(jr, ServiceApiErrorObject.class);
            logger.error("webcallReady;statuscode: {}, mesaage:{}", response.getStatusLine().getStatusCode(),
                    result.getMessage());
        } catch (Exception e) {
            logger.error("webcallReady;statuscode: {}", response.getStatusLine().getStatusCode());
        }
    }
    File tmpFile = new File(logFileLocation + ".tmp");
    if (tmpFile.exists())
        tmpFile.delete();
}