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:de.loercher.geomodule.cloudant.CloudantGeoSearchStream.java

private void extractEntities(BufferedReader bufferedReader) throws JSONParseException {
    JsonReader reader = new JsonReader(bufferedReader);
    try {//from  w w  w. j a  va  2 s  .c o  m
        reader.beginObject();

        String arrayName = null;
        while (reader.hasNext() && !("features".equals(arrayName))) {
            arrayName = reader.nextName();
            if ("bookmark".equals(arrayName)) {
                bookmark = reader.nextString();
            } else if (!("features".equals(arrayName))) {
                reader.skipValue();
            }
        }

        if ("features".equals(arrayName)) {
            reader.beginArray();

            while (reader.hasNext()) {
                Gson gson = new Gson();
                CloudantArticleEntity entity = gson.fromJson(reader, CloudantArticleEntity.class);

                // Duplicates should not be returned
                if (!(alreadyAvailableIds.contains(entity.getId()))) {
                    bufferedEntities.add(entity);
                }

                alreadyAvailableIds.add(entity.getId());
            }

            reader.endArray();
            reader.endObject();
            reader.close();
        } else {
            JSONParseException e = new JSONParseException(
                    "Parsing of cloudant response failed. Tag 'features' not found. ");
            log.error(e.getLoggingString());
            throw e;
        }
    } catch (IOException ex) {
        JSONParseException e = new JSONParseException("Parsing of cloudant response failed.", ex);
        log.error(e.getLoggingString());
        throw e;
    }
}

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 {/*w ww  . j av  a2s.c om*/
        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   w  w w. j a  v  a 2 s.c  o m*/
        public void close() throws IOException {
            // avoid closing underlying stream
        }
    });
    jsonReader.setLenient(false);
    return new GsonStreamSource(jsonReader);
}

From source file:de.pribluda.android.jsonmarshaller.JSONUnmarshaller.java

License:Apache License

/**
 * convenience method parsing JSON on the fly
 *
 * @param json//ww  w.j  a  va2s  . c om
 * @param beanToBeCreatedClass
 * @param <T>
 * @return
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
public static <T> T unmarshall(String json, java.lang.Class<T> beanToBeCreatedClass)
        throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException,
        IOException {
    return unmarshall(new JsonReader(new StringReader(json)), beanToBeCreatedClass);
}

From source file:de.qaware.chronix.converter.serializer.json.JsonMetricTimeSeriesSerializer.java

License:Apache License

/**
 * Deserialize the given json to a collection of metric data points
 *
 * @param json       the json representation of collection holding metric data points
 * @param queryStart the start of the query
 * @param queryEnd   the end of the query
 * @param builder    the builder for the time series
 *//*from w  ww.  ja v a2  s . c  o  m*/
public void fromJson(byte[] json, final long queryStart, final long queryEnd,
        MetricTimeSeries.Builder builder) {
    if (queryStart <= 0 && queryEnd <= 0) {
        return;
    }

    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(json);
        JsonReader reader = new JsonReader(new InputStreamReader(bais, UTF_8));
        List[] timestampsValues = gson.fromJson(reader, List[].class);
        reader.close();

        List<Double> times = (List<Double>) timestampsValues[0];
        List<Double> values = (List<Double>) timestampsValues[1];

        for (int i = 0; i < times.size(); i++) {
            if (times.get(i) > queryEnd) {
                break;
            }

            if (times.get(i) >= queryStart && times.get(i) <= queryEnd) {
                builder.point(times.get(i).longValue(), values.get(i));
            }
        }

    } catch (IOException | JsonSyntaxException | JsonIOException e) {
        LOGGER.error("Could not deserialize json data. Returning empty lists.", e);
    }

}

From source file:de.sabian.objectstore.ObjectStoreRaw.java

License:Apache License

public <T> boolean fillCollection(String identifier, Class<T> clazz, Collection<T> collection)
        throws IOException {
    if (contains(identifier)) {
        JsonReader jReader = new JsonReader(new StringReader(mJsonStorage.getJson(identifier)));
        jReader.beginArray();/*  www  . ja  va2  s.  c  om*/
        while (jReader.hasNext()) {
            T object = mGson.fromJson(jReader, clazz);
            collection.add(object);
        }
        jReader.endArray();
        jReader.close();
        return true;
    } else
        return false;
}

From source file:de.sabian.objectstore.ObjectStoreRaw.java

License:Apache License

public <T, X> boolean fillMap(String identifier, Class<T> classOfKeys, Class<X> classOfValues, Map<T, X> map)
        throws IOException {
    if (contains(identifier)) {
        JsonReader jReader = new JsonReader(new StringReader(mJsonStorage.getJson(identifier)));
        jReader.beginArray();//from ww  w. j a va2s  .com
        while (jReader.hasNext()) {
            jReader.beginObject();
            String name = jReader.nextName();
            if (!name.equals("key"))
                throw new IOException("expected name key but found: " + name);
            T key = mGson.fromJson(jReader, classOfKeys);
            name = jReader.nextName();
            if (!name.equals("value"))
                throw new IOException("expected name value but found: " + name);
            X value = mGson.fromJson(jReader, classOfValues);
            jReader.endObject();
            map.put(key, value);
        }
        jReader.endArray();
        jReader.close();
        return true;
    } else
        return false;
}

From source file:de.winniehell.battlebeavers.storage.CustomGSON.java

License:Open Source License

public static JsonReader getReader(final Context pContext, final String pFileName)
        throws FileNotFoundException {

    InputStream file = null;//from w w  w  .  j ava 2  s.c o  m

    try {
        file = new FileInputStream(pFileName);
    } catch (final FileNotFoundException e) {
        Log.w(TAG, "Could not open file for input! " + e.getMessage());
        throw e;
    }

    return new JsonReader(new InputStreamReader(file, Charset.defaultCharset()));
}

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);/*w w w.  j ava2  s .  c o  m*/
    return jsonReader;
}

From source file:ec.loxa.sna.gephi.websiteexport.WebSiteExporter.java

private void export() throws Exception {
    Project project = Lookup.getDefault().lookup(ProjectController.class).getCurrentProject();

    ProjectInformation projectInformation = project.getLookup().lookup(ProjectInformation.class);

    setProjectName(projectInformation.getName());
    if (!isAppend()) {

        File root = new File(getPath(), getProjectName());
        //TODO: Debe ejecutarse si y solo si no se agrega un proyecto. Verificar la estructura del index.html
        delete(root);//from w w w  .ja  v a  2s .  com
        root.mkdir();
        projectPath = root;

        //To get de Project Properties
        ProjectMetaData pi = project.getLookup().lookup(ProjectMetaData.class);
        description = pi.getDescription();
        keywords = pi.getKeywords();
        title = pi.getTitle();
    } else {
        projectPath = getPath();
    }

    //To get workspaces in the project
    WorkspaceProvider workspaceProvider = project.getLookup().lookup(WorkspaceProvider.class);

    setAllWorkspaces(workspaceProvider.getWorkspaces());

    //To get workspace information
    WorkspaceInformation workspaceInfortion;
    String workspaceName;

    GraphModel graphModel;
    //AttributeModel attModel;

    ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
    boolean hasPartitionImage;

    if (append) {
        List<GraphStatistic> grph;
        File statisticPath = new File(projectPath.getAbsolutePath() + File.separator + "estadisticas.json");
        JsonReader reder = new JsonReader(new FileReader(statisticPath.getAbsolutePath()));
        Gson gson = new Gson();
        try {
            StatisticsJSON resp = gson.fromJson(reder, StatisticsJSON.class);
            grph = resp.getGraphs();
            setNumAppend(grph.size());
            for (int i = 0; i < grph.size(); i++) {
                statistics.addGraph(grph.get(i));
            }
        } catch (Exception e) {
            System.out.println("Fail: " + e.getMessage());
        }
    }

    for (int i = 0; i < allWorkspaces.length && !cancel; i++) {
        setWorkspace(allWorkspaces[i]);
        workspaceInfortion = getWorkspace().getLookup().lookup(WorkspaceInformation.class);
        workspaceName = workspaceInfortion.getName().replace(" ", "");

        //Verificar si se ha seleccionado
        if (isSelected(workspaceName)) {
            try {
                pc.openWorkspace(getWorkspace());
            } catch (Exception e) {
                System.out.println("MESSAGE: " + e.getMessage());
            }

            Progress.setDisplayName(progress, getMessage("message_Export") + " " + workspaceName);

            if (append) {
                String pathAux = projectPath + File.separator + workspaceName;
                File ws = new File(pathAux);
                while (ws.exists()) {
                    workspaceName = workspaceName + "_1";
                    pathAux = projectPath + File.separator + workspaceName;
                    ws = new File(pathAux);
                }
            }
            createDirectoryToWorkspace(projectPath, workspaceName);
            saveGEXF(workspaceName, getWorkspace());

            //Se verifica si no se cancel el proceso
            if (!cancel) {
                //                    PartitionModel partitionModel
                //                            = getWorkspace().getLookup().lookup(PartitionModel.class);

                graphModel = getWorkspace().getLookup().lookup(GraphModel.class);
                //attModel = getWorkspace().getLookup().lookup(AttributeModel.class);

                try {
                    if (graphModel.isDirected()) {
                        graphType = "Directed";
                    } else {
                        graphType = "Undirected";
                    }
                } catch (Exception e) {
                    System.out.println("ERROR: " + e.getMessage());
                }

                saveGraphCSV(workspaceName, getWorkspace());
                saveGraphPDF(workspaceName, getWorkspace());
                //                    hasPartitionImage = generatePartitionImage(partitionModel, workspaceName);
                //                    getStatistics(workspaceName, graphModel.getGraphVisible(), hasPartitionImage);
                getStatistics(workspaceName, graphModel.getGraphVisible(), false);
            } else {
                Progress.setDisplayName(progress, getMessage("message_Cancel"));
            }
        }
    }
    //Si el proceso no fue cancelado se genera la informacin
    if (!cancel) {
        saveStatistics();
        if (!isAppend()) {
            copyWebSiteFiles();
        }
        builIndexPage();
        if (!append) {
            builInfoPage();
            builAboutPage();
        }
        delete(new File(projectPath.getAbsolutePath() + File.separator + "FilesWebSite.zip"));
        delete(new File(projectPath.getAbsolutePath() + File.separator + "__MACOSX"));
    }
}