List of usage examples for com.google.gson.stream JsonWriter flush
public void flush() throws IOException
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 ww. ja v a 2 s . com*/ 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 {/*www .ja v a 2 s .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 ww w . j av a 2s .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:Trainer.java
License:Apache License
private static void writeJsonArray(List list) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, IOException { JsonWriter writer = new JsonWriter(new OutputStreamWriter(System.out)); writer.setIndent(" "); JSONMarshaller.marshallArray(writer, list.toArray()); writer.flush(); }
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 ww . jav a2 s .c o 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:be.iminds.iot.dianne.jsonrpc.DianneRequestHandler.java
License:Open Source License
private void writeError(JsonWriter writer, String id, int code, String message) throws IOException { writer.beginObject();// ww w .j a va 2s.c o m writer.name("jsonrpc"); writer.value("2.0"); writer.name("id"); writer.value(id); writer.name("error"); writer.beginObject(); // error object writer.name("code"); writer.value(code); writer.name("message"); writer.value(message); writer.endObject(); // end error object writer.endObject(); writer.flush(); }
From source file:be.iminds.iot.dianne.jsonrpc.DianneRequestHandler.java
License:Open Source License
private void writeResult(JsonWriter writer, String id, Object result) throws IOException { writer.beginObject();/*from ww w.ja v a2 s.co m*/ writer.name("jsonrpc"); writer.value("2.0"); writer.name("id"); writer.value(id); writer.name("result"); // write result object try { if (result instanceof LearnResult) { DianneCoordinatorWriter.writeLearnResult(writer, (LearnResult) result, 10000); } else if (result instanceof AgentResult) { DianneCoordinatorWriter.writeAgentResult(writer, (AgentResult) result, 10000); } else { DianneCoordinatorWriter.writeObject(writer, result); } } catch (Throwable t) { t.printStackTrace(); } // end result object writer.endObject(); writer.flush(); }
From source file:ch.there.gson.GsonInvokerServiceExporter.java
License:Apache License
protected void writeRemoteInvocationResult(HttpExchange exchange, RemoteInvocationResult result, OutputStream os) throws IOException { Gson gson = GsonFactory.getGson();//from ww w . j av a2 s . co m JsonWriter writer = new JsonWriter(new OutputStreamWriter(os)); gson.toJson(result, RemoteInvocationResult.class, writer); writer.flush(); }
From source file:co.cask.cdap.common.conf.Configuration.java
License:Apache License
/** * Writes out all the parameters and their properties (final and resource) to * the given {@link Writer}/*from w ww. j av a2 s. co m*/ * The format of the output would be * { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2, * key2.isFinal,key2.resource}... ] } * It does not output the parameters of the configuration object which is * loaded from an input stream. * @param out the Writer to write to * @throws IOException */ public static void dumpConfiguration(Configuration config, Writer out) throws IOException { JsonWriter dumpGenerator = new JsonWriter(out); dumpGenerator.beginObject(); dumpGenerator.name("properties"); dumpGenerator.beginArray(); dumpGenerator.flush(); synchronized (config) { for (Map.Entry<Object, Object> item : config.getProps().entrySet()) { dumpGenerator.beginObject(); dumpGenerator.name("key").value((String) item.getKey()); dumpGenerator.name("value").value(config.get((String) item.getKey())); dumpGenerator.name("isFinal").value(config.finalParameters.contains(item.getKey())); dumpGenerator.name("resource").value(config.updatingResource.get(item.getKey())); dumpGenerator.endObject(); } } dumpGenerator.endArray(); dumpGenerator.endObject(); dumpGenerator.flush(); }
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>//w w w. java 2 s . c o m * 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); } }