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

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Flushes and closes this writer and the underlying Writer .

Usage

From source file:logInAuthentication.java

void sendRequestToDataBase(HttpServletRequest request, HttpServletResponse response) throws IOException {
    PrintWriter pw = response.getWriter();
    response.setContentType("text/json;charset=UTF-8");

    try {/*w w  w . ja  va  2  s.c om*/
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/uhms", "root", "");
        java.sql.Statement st = con.createStatement();
        StaticData.phone = request.getParameter("phone");
        StaticData.password = request.getParameter("password");
        ResultSet rs = st
                .executeQuery("SELECT gardian_password from gardian_info where id=" + StaticData.phone);
        if (rs.next()) {
            String pss = rs.getString(1);
            if (!StaticData.password.equals(pss)) {
                throw new Exception("Password did not match");
            }
        } else
            throw new Exception("No User Found by this Phone No");
        rs = st.executeQuery("SELECT *from student_info a,gardian_info b,student_gardian_relation c"
                + " WHERE a.id=c.student_id AND b.id = c.gardian_id" + " AND b.id=" + StaticData.phone);
        StaticData.resultSet = rs;
        if (!rs.next())
            throw new Exception("User Not Found On DATABASE");

        JsonWriter gsonWriter = new JsonWriter(pw);
        ResultSetMetaData metaData = rs.getMetaData();
        gsonWriter.beginObject();
        gsonWriter.name("info");
        gsonWriter.beginArray();
        rs.previous();
        while (rs.next()) {
            gsonWriter.beginObject();
            for (int indx = 1; indx <= metaData.getColumnCount(); indx++) {
                gsonWriter.name(metaData.getColumnLabel(indx));
                gsonWriter.value(rs.getString(indx));
            }
            gsonWriter.endObject();
        }
        gsonWriter.endArray();
        gsonWriter.name("status");
        gsonWriter.value("200");

        gsonWriter.endObject();
        gsonWriter.flush();
        gsonWriter.close();

    } catch (Exception ex) {
        JsonWriter gsonWriter = new JsonWriter(pw);
        gsonWriter.beginObject();
        gsonWriter.name("status");
        gsonWriter.value("400");
        gsonWriter.name("error_desc");
        gsonWriter.value(ex.getMessage());
        gsonWriter.endObject();
        gsonWriter.flush();
        gsonWriter.close();

        //  pw.println(ex);
    }
}

From source file:CheckHallStatus.java

void sendRequestToDataBase(HttpServletRequest request, HttpServletResponse response) throws IOException {
    PrintWriter pw = response.getWriter();
    response.setContentType("text/json;charset=UTF-8");

    try {/*from w  ww. j ava2s. co  m*/
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/uhms", "root", "");
        java.sql.Statement st = con.createStatement();
        StaticData.phone = request.getParameter("phone");
        StaticData.password = request.getParameter("password");
        StaticData.id = request.getParameter("id");
        ResultSet rs = st
                .executeQuery("SELECT gardian_password from gardian_info where id=" + StaticData.phone);
        if (rs.next()) {
            String pss = rs.getString(1);
            if (!StaticData.password.equals(pss)) {
                throw new Exception("Password did not match");
            }
        } else {
            throw new Exception("No User Found by this Phone No");
        }
        rs = st.executeQuery(
                "SELECT gardian_id FROM student_gardian_relation where student_id=" + StaticData.id);
        if (rs.next()) {
            String id = rs.getString(1);
            if (!StaticData.phone.contains(id)) {
                throw new Exception("Gardian And Student Info Not related");
            }
        } else {
            throw new Exception("Unauthorized Access");
        }
        rs = st.executeQuery(
                "SELECT * from check_in_out where day_time = (select MAX(day_time) from check_in_out WHERE id ="
                        + StaticData.id + ")");
        JsonWriter gsonWriter = new JsonWriter(pw);
        ResultSetMetaData metaData = rs.getMetaData();
        if (rs.next()) {
            gsonWriter.beginObject();
            for (int i = 0; i < metaData.getColumnCount(); i++) {
                gsonWriter.name(metaData.getColumnLabel(i + 1));
                gsonWriter.value(rs.getString(i + 1));
            }
        } else {
            throw new Exception("Student information Not Found");
        }
        //currret month meal calculation
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar);
        Timestamp current = new Timestamp(calendar.getTimeInMillis());
        //  System.out.println(current);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1, 0, 0, 0);
        Timestamp start = new Timestamp(calendar.getTimeInMillis());
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.getMaximum(Calendar.DAY_OF_MONTH), 23, 59, 59);
        Timestamp end = new Timestamp(calendar.getTimeInMillis());

        rs = st.executeQuery("select sum(quantity) from meal_log  where id=" + StaticData.id
                + " AND day_time>= '" + start + "' AND day_time<='" + end + "' AND type='BREAKFAST'");
        gsonWriter.name("BREAKFAST");
        if (rs.next()) {
            gsonWriter.value(rs.getInt(1) + "");
        } else {
            gsonWriter.value("0");
        }

        rs = st.executeQuery("select sum(quantity) from meal_log  where id=" + StaticData.id
                + " AND day_time>= '" + start + "' AND day_time<='" + end + "' AND type='LUNCH'");
        gsonWriter.name("LUNCH");
        if (rs.next()) {
            gsonWriter.value(rs.getInt(1) + "");
        } else {
            gsonWriter.value("0");
        }
        rs = st.executeQuery("select sum(quantity) from meal_log  where id=" + StaticData.id
                + " AND day_time>= '" + start + "' AND day_time<='" + end + "' AND type='DINNER'");
        gsonWriter.name("DINNER");
        if (rs.next()) {
            gsonWriter.value(rs.getInt(1) + "");
        } else {
            gsonWriter.value("0");
        }
        //calculate meal rate
        rs = st.executeQuery("select sum(quantity) from meal_log  where day_time>= '" + start
                + "' AND day_time<='" + end + "'");
        rs.next();
        int totalMeal = rs.getInt(1);
        rs = st.executeQuery("select sum(amount) from bazar_info  where day_time>= '" + start
                + "' AND day_time<='" + end + "'");
        rs.next();
        int totalBazarAmount = rs.getInt(1);
        gsonWriter.name("meal_rate");
        gsonWriter.value((double) totalBazarAmount / totalMeal + "");

        gsonWriter.name("status");
        gsonWriter.value("200");
        gsonWriter.endObject();
        gsonWriter.flush();
        gsonWriter.close();

    } catch (Exception ex) {
        JsonWriter gsonWriter = new JsonWriter(pw);
        gsonWriter.beginObject();
        gsonWriter.name("status");
        gsonWriter.value("400");
        gsonWriter.name("error_desc");
        gsonWriter.value(ex.getMessage());
        gsonWriter.endObject();
        gsonWriter.flush();
        gsonWriter.close();

        //  pw.println(ex);
    }
}

From source file:ChangePassword.java

void sendRequestToDataBase(HttpServletRequest request, HttpServletResponse response) throws IOException {
    PrintWriter pw = response.getWriter();
    response.setContentType("text/json;charset=UTF-8");

    try {/*from w w w.ja v a2 s.c o  m*/
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/uhms", "root", "");
        java.sql.Statement st = con.createStatement();
        StaticData.phone = request.getParameter("phone");
        StaticData.password = request.getParameter("oldpassword");
        StaticData.newPassword = request.getParameter("newpassword");
        ResultSet rs = st
                .executeQuery("SELECT gardian_password from gardian_info where id=" + StaticData.phone);
        if (rs.next()) {
            String pss = rs.getString(1);
            if (!StaticData.password.equals(pss)) {
                throw new Exception("Enter Current Password Correctly.");
            }
        } else
            throw new Exception("No User Found by this Phone No");
        if (StaticData.newPassword.isEmpty())
            throw new Exception("Password can't be empty.");

        int executeUpdate = st.executeUpdate("UPDATE gardian_info SET gardian_password = '"
                + StaticData.newPassword + "'" + " WHERE id=" + StaticData.phone);
        JsonWriter gsonWriter = new JsonWriter(pw);
        gsonWriter.beginObject();
        if (executeUpdate != 1)
            throw new Exception("Password Change failed.");
        gsonWriter.name("status");
        gsonWriter.value("200");
        gsonWriter.name("message");
        gsonWriter.value("Password Changed Successfully.");
        gsonWriter.endObject();
        gsonWriter.flush();
        gsonWriter.close();

    } catch (Exception ex) {
        JsonWriter gsonWriter = new JsonWriter(pw);
        gsonWriter.beginObject();
        gsonWriter.name("status");
        gsonWriter.value("400");
        gsonWriter.name("error_desc");
        gsonWriter.value(ex.getMessage());
        gsonWriter.endObject();
        gsonWriter.flush();
        gsonWriter.close();

        //  pw.println(ex);
    }
}

From source file:at.univie.sensorium.logging.JSONLogger.java

License:Open Source License

public void finalizeLog() {
    //      String id = UUID.randomUUID().toString();
    for (AbstractSensor s : SensorRegistry.getInstance().getSensors()) {
        s.removeListener(this);
    }/*from   w w w .  ja v  a 2s.co m*/
    for (JsonWriter js : jsonMap.values()) {
        try {
            //            js.beginObject();
            //            js.name("id").value(id);
            //            js.endObject();
            js.endArray();
            js.flush(); // added on 2013-04-09; does this help in fixing the missing ]?
            js.close(); // added on 2013-04-09; does this help in fixing the missing ]?
        } catch (IOException e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            Log.d(SensorRegistry.TAG, sw.toString());
        }
    }
    // JSONWriter.close() already flushes/closes underlying writer,
    // so explicity closing the FileWriter would always throw an exception
}

From source file:bammerbom.ultimatecore.bukkit.resources.utils.JsonRepresentedObject.java

License:MIT License

/**
 * Serialize this fancy message, converting it into syntactically-valid JSON
 * using a {@link JsonWriter}. This JSON should be compatible with vanilla
 * formatter commands such as {@code /tellraw}.
 *
 * @return The JSON string representing this object.
 */// w  w w  . j  a v  a2  s .c  om
public String toJSONString() {
    if (!dirty && jsonString != null) {
        return jsonString;
    }
    StringWriter string = new StringWriter();
    JsonWriter json = new JsonWriter(string);
    try {
        writeJson(json);
        json.close();
    } catch (IOException e) {
        throw new RuntimeException("invalid message");
    }
    jsonString = string.toString();
    dirty = false;
    return jsonString;
}

From source file:bytehala.flowmortarexample.GsonParceler.java

License:Apache License

private String encode(Path instance) throws IOException {
    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter);

    try {/*from   w  w w.j av  a 2s.  c  o m*/
        Class<?> type = instance.getClass();

        writer.beginObject();
        writer.name(type.getName());
        gson.toJson(instance, type, writer);
        writer.endObject();

        return stringWriter.toString();
    } finally {
        writer.close();
    }
}

From source file:classifiers.DummyClassifier.java

License:Apache License

public void parseStreamAndClassify(String jsonFile, String resultsFile) throws IOException {

    String journalName;/*from   w ww  .  j  av  a 2s  .c om*/
    int count = 0;
    int abstract_count = 0;

    try {
        JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(jsonFile)));
        JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(resultsFile), "UTF-8"));
        writer.setIndent("    ");

        //reader.setLenient(true);
        reader.beginArray();
        writer.beginArray();
        while (reader.hasNext()) {

            reader.beginObject();
            writer.beginObject();
            while (reader.hasNext()) {
                String name = reader.nextName();

                if (name.equals("abstract")) {
                    abstract_count++;
                    reader.skipValue();

                } else if (name.equals("pmid")) {
                    String pmid = reader.nextString();
                    writer.name("labels");
                    writeLabels(writer);
                    writer.name("pmid").value(pmid);
                } else if (name.equals("title")) {
                    reader.skipValue();
                } else {
                    System.out.println(name);
                    reader.skipValue();
                }
            }
            reader.endObject();
            writer.endObject();
        }
        reader.endArray();
        writer.endArray();

        System.out.println("Abstracts: " + abstract_count);

        writer.close();
    } catch (FileNotFoundException ex) {

    }
}

From source file:cn.bingoogolapple.scaffolding.net.NetRequestBodyConverter.java

License:Apache License

@Override
public RequestBody convert(T value) throws IOException {
    Buffer buffer = new Buffer();
    Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
    JsonWriter jsonWriter = gson.newJsonWriter(writer);
    adapter.write(jsonWriter, value);/*from   w ww  .j a v a2  s  . com*/
    jsonWriter.close();
    return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}

From source file:co.cask.cdap.data.stream.service.StreamFetchHandler.java

License:Apache License

/**
 * Handler for the HTTP API {@code /streams/[stream_name]/events?start=[start_ts]&end=[end_ts]&limit=[event_limit]}
 * <p>//  www  .  j a  v a  2s.com
 * Responds with:
 * <ul>
 * <li>404 if stream does not exist</li>
 * <li>204 if no event in the given start/end time range exists</li>
 * <li>200 if there is are one or more events</li>
 * </ul>
 * </p>
 * <p>
 * Response body is a JSON array of the StreamEvent object.
 * </p>
 *
 * @see StreamEventTypeAdapter StreamEventTypeAdapter for the format of the StreamEvent object
 */
@GET
@Path("/{stream}/events")
public void fetch(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId,
        @PathParam("stream") String stream, @QueryParam("start") @DefaultValue("0") String start,
        @QueryParam("end") @DefaultValue("9223372036854775807") String end,
        @QueryParam("limit") @DefaultValue("2147483647") int limit) throws Exception {
    long startTime = TimeMathParser.parseTime(start, TimeUnit.MILLISECONDS);
    long endTime = TimeMathParser.parseTime(end, TimeUnit.MILLISECONDS);

    Id.Stream streamId = Id.Stream.from(namespaceId, stream);
    if (!verifyGetEventsRequest(streamId, startTime, endTime, limit, responder)) {
        return;
    }

    StreamConfig streamConfig = streamAdmin.getConfig(streamId);
    long now = System.currentTimeMillis();
    startTime = Math.max(startTime, now - streamConfig.getTTL());
    endTime = Math.min(endTime, now);

    // Create the stream event reader
    try (FileReader<StreamEventOffset, Iterable<StreamFileOffset>> reader = createReader(streamConfig,
            startTime)) {
        TimeRangeReadFilter readFilter = new TimeRangeReadFilter(startTime, endTime);
        List<StreamEvent> events = Lists.newArrayListWithCapacity(100);

        // Reads the first batch of events from the stream.
        int eventsRead = readEvents(reader, events, limit, readFilter);

        // If empty already, return 204 no content
        if (eventsRead <= 0) {
            responder.sendStatus(HttpResponseStatus.NO_CONTENT);
            return;
        }

        // Send with chunk response, as we don't want to buffer all events in memory to determine the content-length.
        ChunkResponder chunkResponder = responder.sendChunkStart(HttpResponseStatus.OK,
                ImmutableMultimap.of(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=utf-8"));
        ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
        JsonWriter jsonWriter = new JsonWriter(
                new OutputStreamWriter(new ChannelBufferOutputStream(buffer), Charsets.UTF_8));
        // Response is an array of stream event
        jsonWriter.beginArray();
        while (limit > 0 && eventsRead > 0) {
            limit -= eventsRead;

            for (StreamEvent event : events) {
                GSON.toJson(event, StreamEvent.class, jsonWriter);
                jsonWriter.flush();

                // If exceeded chunk size limit, send a new chunk.
                if (buffer.readableBytes() >= CHUNK_SIZE) {
                    // If the connect is closed, sendChunk will throw IOException.
                    // No need to handle the exception as it will just propagated back to the netty-http library
                    // and it will handle it.
                    // Need to copy the buffer because the buffer will get reused and send chunk is an async operation
                    chunkResponder.sendChunk(buffer.copy());
                    buffer.clear();
                }
            }
            events.clear();

            if (limit > 0) {
                eventsRead = readEvents(reader, events, limit, readFilter);
            }
        }
        jsonWriter.endArray();
        jsonWriter.close();

        // Send the last chunk that still has data
        if (buffer.readable()) {
            // No need to copy the last chunk, since the buffer will not be reused
            chunkResponder.sendChunk(buffer);
        }
        Closeables.closeQuietly(chunkResponder);
    }
}

From source file:co.cask.cdap.filetailer.state.FileTailerStateProcessorImpl.java

License:Apache License

@Override
public void saveState(FileTailerState state) throws FileTailerStateProcessorException {
    try {//from   ww  w.j a  v a 2  s  .co m
        Preconditions.checkNotNull(state);
    } catch (NullPointerException e) {
        LOG.info("Cannot save null state");
        return;
    }
    createDirs(stateDir);
    LOG.debug("Start saving File Tailer state ..");
    try {
        JsonWriter jsonWriter = new JsonWriter(Files.newWriter(stateFile, UTF_8));
        try {
            GSON.toJson(state, FileTailerState.class, jsonWriter);
            LOG.debug("File Tailer state saved successfully");
        } finally {
            try {
                jsonWriter.close();
            } catch (IOException e) {
                LOG.error("Cannot close JSON Writer for file {}: {}", stateFile.getAbsolutePath(),
                        e.getMessage(), e);
            }
        }
    } catch (IOException e) {
        LOG.error("Cannot close JSON Writer for file {}: {}", stateFile.getAbsolutePath(), e.getMessage(), e);
    }
}