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

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this JSON reader and the underlying java.io.Reader .

Usage

From source file:org.homedns.mkh.databuffer.DataBuffer.java

License:Apache License

/**
 * Puts data as json string to the data buffer.
 * /*from  www.  jav  a 2  s  .  c o  m*/
 * @param sJsonData
 *            the data as json string to put
 * 
 * @throws SQLException
 * @throws ParseException 
 * @throws InvalidDatabufferDesc 
 * @throws IOException 
 */
public void putJson(String sJsonData) throws SQLException, ParseException, InvalidDatabufferDesc, IOException {
    LOG.debug(sJsonData);
    String[][] data;
    JsonReader reader = null;
    try {
        reader = new JsonReader(new StringReader(sJsonData));
        reader.setLenient(true);
        Gson gson = new Gson();
        data = gson.fromJson(reader, String[][].class);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
    for (String[] row : data) {
        moveToInsertRow();
        for (Column col : _metaData.getColList()) {
            Object value = null;
            String sValue = row[col.getColNum()];
            int iType = _metaData.getColumnType(col.getColNum() + 1);
            try {
                if (iType == Types.TIMESTAMP) {
                    value = new Timestamp((getEnvironment().getServerDateFormat().parse((sValue)).getTime()));
                } else if (iType == Types.TINYINT || iType == Types.SMALLINT || iType == Types.INTEGER) {
                    value = new Integer(sValue);
                } else if (iType == Types.BIGINT) {
                    value = new Long(sValue);
                } else if (iType == Types.DOUBLE) {
                    value = new Double(sValue);
                } else if (iType == Types.FLOAT) {
                    value = new Float(sValue);
                } else if (iType == Types.BOOLEAN) {
                    value = new Boolean(sValue);
                } else if (iType == Types.VARCHAR) {
                    value = sValue;
                }
            } catch (ParseException e) {
                ParseException ex = new ParseException(col.getName() + ": " + sValue, 0);
                ex.initCause(e);
                throw ex;
            }
            updateObject(col.getColNum() + 1, value);
        }
        insertRow();
        moveToCurrentRow();
        last();
    }
    LOG.debug("putJson: success");
}

From source file:org.homedns.mkh.databuffer.DataBufferMetaData.java

License:Apache License

/**
 * @param sDataBufferName/* w  ww  .  j a  v  a 2 s  .co  m*/
 *            the data buffer name
 * @param env
 *            the data buffer environment
 * 
 * @throws IOException
 * @throws InvalidDatabufferDesc
 */
public DataBufferMetaData(String sDataBufferName, Environment env) throws InvalidDatabufferDesc, IOException {
    _env = env;
    _sDataBufferName = sDataBufferName;
    JsonReader in = null;
    try {
        in = new JsonReader(new FileReader(env.getDataBufferFilename(sDataBufferName)));
        _desc = new Gson().fromJson(in, DataBufferDesc.class);
        _desc.check();
        setMetaData();
    } catch (Exception e) {
        InvalidDatabufferDesc ex = new InvalidDatabufferDesc(sDataBufferName);
        ex.initCause(e);
        throw ex;
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:org.imperiumstudios.Imperium1871Bungee.BukkitWarpHelper.files.JsonFile.java

License:Open Source License

/**
 * Read the config File into RAM./*  w w  w .  ja  v a 2s  .c o  m*/
 */
public void readFile() {
    try {
        JsonReader reader = new JsonReader(new FileReader(jsonFile));

        reader.beginObject();

        while (reader.hasNext())
            jsonFileContent.put(reader.nextName(), reader.nextString());

        reader.endObject();
        reader.close();
    } catch (IOException ex) {
        IMP.log.error("JsonFile.java > readFile() > Unable to read " + jsonFile + ". Disabling this plugin ..");
        IMP.log.error("JsonFile.java > readFile() > Error: " + ex.getMessage());
        IMP.disable();
    }
}

From source file:org.jenkinsci.plugins.jiraissue.JobConfigMapping.java

License:Apache License

/**
 * Loads the JobConfigEntry from the file associated with the project
 * @param project//from  w  w  w . j a v  a 2 s .  c o  m
 * @return the loaded JobConfigEntry, or null if there was no file, or it could not be loaded
 */
private JobConfigEntry load(AbstractProject project) {
    JobConfigEntry entry = null;
    try {
        Gson gson = new GsonBuilder().registerTypeAdapter(AbstractFields.class, new FieldConfigsJsonAdapter())
                .create();
        FileInputStream fileIn = new FileInputStream(getPathToJsonFile(project));
        JsonReader reader = new JsonReader(new InputStreamReader(fileIn, "UTF-8"));

        entry = gson.fromJson(reader, JobConfigEntry.class);
        reader.close();
        fileIn.close();

        return (JobConfigEntry) entry.readResolve();
    } catch (FileNotFoundException e) {
        entry = loadBackwardsCompatible(project);
        if (entry == null) {
            JiraUtils.log("No configs found for project " + project.getFullName());
        }
    } catch (Exception e) {
        JiraUtils.logError("ERROR: Could not load configs for project " + project.getFullName(), e);
    }
    return entry;
}

From source file:org.kairosdb.client.AbstractClient.java

License:Apache License

private List<String> readNameQueryResponse(InputStream stream) throws IOException {
    List<String> list = new ArrayList<String>();
    JsonReader reader = new JsonReader(new InputStreamReader(stream, "UTF-8"));

    try {/*from   ww  w . j  av a 2  s .  c om*/
        reader.beginObject();
        String container = reader.nextName();
        if (container.equals("results")) {
            reader.beginArray();
            while (reader.hasNext()) {
                list.add(reader.nextString());
            }
            reader.endArray();
            reader.endObject();
        }
    } finally {
        reader.close();
    }

    return list;
}

From source file:org.kairosdb.core.http.rest.json.DataPointsParser.java

License:Apache License

public ValidationErrors parse() throws IOException, DatastoreException {
    long start = System.currentTimeMillis();
    ValidationErrors validationErrors = new ValidationErrors();

    JsonReader reader = new JsonReader(inputStream);

    try {/*from  ww  w . java 2s . co m*/
        int metricCount = 0;

        if (reader.peek().equals(JsonToken.BEGIN_ARRAY)) {
            try {
                reader.beginArray();

                while (reader.hasNext()) {
                    NewMetric metric = parseMetric(reader);
                    validateAndAddDataPoints(metric, validationErrors, metricCount);
                    metricCount++;
                }
            } catch (EOFException e) {
                validationErrors.addErrorMessage("Invalid json. No content due to end of input.");
            }

            reader.endArray();
        } else if (reader.peek().equals(JsonToken.BEGIN_OBJECT)) {
            NewMetric metric = parseMetric(reader);
            validateAndAddDataPoints(metric, validationErrors, 0);
        } else
            validationErrors.addErrorMessage("Invalid start of json.");

    } catch (EOFException e) {
        validationErrors.addErrorMessage("Invalid json. No content due to end of input.");
    } finally {
        reader.close();
    }

    ingestTime = (int) (System.currentTimeMillis() - start);

    return validationErrors;
}

From source file:org.kairosdb.util.ResponseToMetricConverter.java

License:Apache License

public void convert(InputStream inputStream, OutputStream outStream) throws IOException {

    JsonReader reader = new JsonReader(new InputStreamReader(inputStream));
    JsonWriter writer = new JsonWriter(new OutputStreamWriter(outStream));

    try {//from   www. j  av a 2 s  .co m
        writer.beginArray();

        // Queries array
        reader.beginObject();
        while (reader.hasNext()) {
            String token = reader.nextName();
            if (token.equals("queries")) {
                reader.beginArray();

                while (reader.hasNext()) {
                    reader.beginObject();
                    token = reader.nextName();
                    if (token.equals("results")) {
                        parseResults(reader, writer);
                    }
                    reader.endObject();
                }

                reader.endArray();
            }
        }
        reader.endObject();

        writer.endArray();
    } catch (RuntimeException e) {
        e.printStackTrace();
    } finally {
        reader.close();
        writer.close();
    }
}

From source file:org.mule.modules.servicesource.ServiceSourceConnector.java

License:Open Source License

private <T> List<T> readStream(InputStream stream, Class<T> type) {
    JsonReader reader = null;
    try {/*from  ww  w  . j  a  v a2 s.c o  m*/
        reader = new JsonReader(new InputStreamReader(stream));
        List<T> result = new ArrayList<T>();

        try {
            reader.beginArray();
        } catch (MalformedJsonException e) {
            // this means that the input came empty
            return result;
        }
        while (reader.hasNext()) {
            result.add(GsonFactory.getGson().<T>fromJson(reader, type));
        }
        reader.endArray();

        return result;

    } catch (IOException e) {
        throw new ServiceSourceException("Error consuming stream", e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                logger.error("Error closing stream reader", e);
            }
        }

        IOUtils.closeQuietly(stream);
    }
}

From source file:org.mythdroid.services.GuideService.java

License:Open Source License

/**
 * Get ProgramGuide data//from  w  w  w  .  j av a2  s .c o m
 * @param start Date for start of data
 * @param end Date for end of data
 * @return ArrayList of Channels
 */
public ArrayList<Channel> GetProgramGuide(Date start, Date end) throws IOException {

    final Params params = new Params();
    params.put("StartTime", Globals.utcFormat(start)); //$NON-NLS-1$
    params.put("EndTime", Globals.utcFormat(end)); //$NON-NLS-1$
    params.put("StartChanId", 0); //$NON-NLS-1$
    params.put("NumChannels", -1); //$NON-NLS-1$
    params.put("Details", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    InputStream is = jc.GetStream("GetProgramGuide", params); //$NON-NLS-1$
    JsonReader jreader = new JsonReader(new BufferedReader(new InputStreamReader(is, "UTF-8")) //$NON-NLS-1$
    );

    ArrayList<Channel> channels = new ArrayList<Channel>();

    jreader.beginObject();
    skipTo(jreader, JsonToken.BEGIN_OBJECT);
    jreader.beginObject();
    skipTo(jreader, JsonToken.NAME);
    while (jreader.hasNext()) {
        String name = jreader.nextName();
        if (name.equals("NumOfChannels")) { //$NON-NLS-1$
            channels.ensureCapacity(jreader.nextInt());
            break;
        }
        jreader.skipValue();
    }
    skipTo(jreader, JsonToken.BEGIN_ARRAY);
    jreader.beginArray();
    while (jreader.hasNext()) {
        jreader.beginObject();
        channels.add((Channel) gson.fromJson(jreader, Channel.class));
        jreader.endObject();
    }
    jreader.endArray();
    jreader.endObject();
    jreader.endObject();
    jreader.close();
    jc.endStream();

    return channels;

}

From source file:org.mythdroid.services.VideoService.java

License:Open Source License

/**
 * Get a list of videos / directories in a given subdirectory
 * @param subdir the desired subdirectory or "ROOT" for the top-level
 * @return an ArrayList of Videos//  ww  w  . j a  va 2 s  .  com
 */
public ArrayList<Video> getVideos(String subdir) throws IOException {

    ArrayList<Video> videos = new ArrayList<Video>(128);

    InputStream is = jc.GetStream("GetVideoList", null); //$NON-NLS-1$

    if (is == null)
        return null;

    JsonReader jreader = new JsonReader(new BufferedReader(new InputStreamReader(is, "UTF-8")) //$NON-NLS-1$
    );

    Video vid;
    final ArrayList<String> subdirs = new ArrayList<String>(16);

    jreader.beginObject();
    skipTo(jreader, JsonToken.BEGIN_OBJECT);
    jreader.beginObject();
    skipTo(jreader, JsonToken.BEGIN_ARRAY);
    jreader.beginArray();
    while (jreader.hasNext()) {
        jreader.beginObject();
        vid = gson.fromJson(jreader, Video.class);
        jreader.endObject();

        if (!subdir.equals("ROOT") && !vid.filename.startsWith(subdir)) //$NON-NLS-1$
            continue;

        String name = vid.filename;

        if (!subdir.equals("ROOT")) //$NON-NLS-1$
            name = vid.filename.substring(subdir.length() + 1);

        int slash;
        if ((slash = name.indexOf('/')) > 0) {
            String dir = name.substring(0, slash);
            if (!subdirs.contains(dir))
                subdirs.add(dir);
        } else
            videos.add(vid);
    }
    jreader.endArray();
    jreader.endObject();
    jreader.endObject();
    jreader.close();
    jc.endStream();

    for (String name : subdirs) {
        try {
            videos.add(new Video("-1 DIRECTORY " + name)); //$NON-NLS-1$
        } catch (IllegalArgumentException e) {
            ErrUtil.logWarn(e);
        }
    }

    videos.trimToSize();

    return videos;

}