List of usage examples for com.google.gson.stream JsonWriter JsonWriter
public JsonWriter(Writer out)
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 a2 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:ContattiSQL.java
protected void doGetSingle(String contattoId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection con = getConnection(); Statement stmt = null;// w w w .j a va 2s . c om ResultSet rs = null; try { stmt = con.createStatement(); } catch (SQLException ex) { Logger.getLogger(ContattiSQL.class.getName()).log(Level.SEVERE, null, ex); } try { rs = stmt.executeQuery("SELECT ContattoId, Cognome, Nome, EMail FROM dbo.Contatti" + " Where ContattoId = " + contattoId); rs.next(); ContattoViewModel viewModel = new ContattoViewModel(); viewModel.cognome = rs.getString(2); viewModel.nome = rs.getString(3); viewModel.email = rs.getString(4); JsonWriter writer = new JsonWriter(response.getWriter()); Gson gson = new Gson(); gson.toJson(viewModel, ContattoViewModel.class, writer); } catch (SQLException ex) { Logger.getLogger(ContattiSQL.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:ContattiSQL.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*w ww . j av a 2 s . c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedReader reader = request.getReader(); Gson gson = new Gson(); ContattoViewModel contatto = (ContattoViewModel) gson.fromJson(reader, ContattoViewModel.class); try { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); } catch (ClassNotFoundException ex) { Logger.getLogger(ContattiSQL.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(ContattiSQL.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(ContattiSQL.class.getName()).log(Level.SEVERE, null, ex); } Connection con = DriverManager.getConnection( "jdbc:sqlserver://127.0.0.1;instanceName=SQLSERVER2012;databaseName=ITS2014;user=its2014;password=its2014;"); Statement stmt = con.createStatement(); String sql = "insert into dbo.Contatti (Cognome, Nome, EMail) " + "VALUES(" + "'" + contatto.cognome + "'" + ", '" + contatto.nome + "'" + ", '" + contatto.email + "'" + ")"; stmt.execute(sql); JsonWriter writer = new JsonWriter(response.getWriter()); gson.toJson(Risposta.OK, Risposta.class, writer); con.close(); } catch (SQLException ex) { Logger.getLogger(ContattiSQL.class.getName()).log(Level.SEVERE, null, 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 {/*w w w. j a va 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"); 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 {//w w w .j a va2 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:ScoresServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* ww w . j a v a 2s . c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //processRequest(request, response); BufferedReader reader = request.getReader(); Gson gson = new Gson(); ScoreViewModel contatto = (ScoreViewModel) gson.fromJson(reader, ScoreViewModel.class); try { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); } catch (ClassNotFoundException ex) { Logger.getLogger(ScoresServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(ScoresServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(ScoresServlet.class.getName()).log(Level.SEVERE, null, ex); } Connection con = DriverManager.getConnection( "jdbc:sqlserver://127.0.0.1;instanceName=SQLSERVER2012;databaseName=FlappyBird;user=flappybird;password=flappybird;"); Statement stmt = con.createStatement(); String sql = "insert into dbo.Scores (Username, Score) " + "VALUES(" + "'" + contatto.username + "'" + ", '" + contatto.score + "'" + ")"; stmt.execute(sql); JsonWriter writer = new JsonWriter(response.getWriter()); gson.toJson(Risposta.OK, Risposta.class, writer); con.close(); } catch (SQLException ex) { Logger.getLogger(ScoresServlet.class.getName()).log(Level.SEVERE, null, 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();//ww w. ja v a 2s . com }
From source file:aaa.AdminMgmt.java
@GET @Path("login") @Produces(MediaType.APPLICATION_JSON)/* w w w. ja v a 2s. c om*/ public Response login(@QueryParam("user") String uid, @QueryParam("psswd") String psswd) throws NamingException, SQLException { dao.open(); pst = dao.cn.prepareStatement("select *from admin where email=? AND password=?"); String res = null; pst.setString(1, uid); pst.setString(2, psswd); ResultSet rs = pst.executeQuery(); if (rs != null) { rs.next(); //if(rs.getString(4).equals(uid) && rs.getString(5).equals(psswd)){ rs.previous(); Gson gson = new Gson(); try (StringWriter stringWriter = new StringWriter()) { JsonWriter writer = new JsonWriter(stringWriter); tools.ResultSetAdapter ra = new tools.ResultSetAdapter(); ra.write(writer, rs); res = "{ \"data\" :" + stringWriter.getBuffer().toString() + "}"; } catch (Exception e) { res = e.getMessage() + ""; } finally { if (pst != null && dao.cn != null) { rs.close(); pst.close(); dao.cn.close(); } //} } } return modRes.cbrs(res); }
From source file:aaa.GenericResource.java
@GET @Path("login") @Produces(MediaType.APPLICATION_JSON)//from w ww . jav a 2s . c o m public Response loginsa(@QueryParam("user") String user, @QueryParam("psswd") String psswd) throws NamingException, SQLException { dao.open(); pst = dao.cn.prepareStatement("select *from superadmin where email=? AND password=?"); String res = null; pst.setString(1, user); pst.setString(2, psswd); ResultSet rs = pst.executeQuery(); if (rs != null) { rs.next(); if (rs.getString(4).equals(user) && rs.getString(5).equals(psswd)) { rs.previous(); Gson gson = new Gson(); try (StringWriter stringWriter = new StringWriter()) { JsonWriter writer = new JsonWriter(stringWriter); tools.ResultSetAdapter ra = new tools.ResultSetAdapter(); ra.write(writer, rs); res = "{ \"data\" :" + stringWriter.getBuffer().toString() + "}"; } catch (Exception e) { res = e.getMessage() + ""; } finally { if (pst != null && dao.cn != null) { rs.close(); pst.close(); dao.cn.close(); } } } } return modRes.cbrs(res); }
From source file:at.univie.sensorium.logging.JSONLogger.java
License:Open Source License
private JsonWriter getWriterForName(String sensorname) { JsonWriter writer = jsonMap.get(sensorname); if (writer == null) { try {// w w w. ja v a2 s .c om String filename = sensorname.substring(sensorname.lastIndexOf('.') + 1) + ".json"; File extFile = new File(extDir, filename); if (extFile.exists()) { // get the first free filename.number int i = 0; boolean done = false; while (!done) { File f = new File(extDir, filename + "." + String.valueOf(i++)); if (f.exists()) continue; extFile.renameTo(f); extFile = new File(extDir, filename); // reset extFile // to original // pointer done = true; } } FileWriter fw = new FileWriter(extFile); writer = new JsonWriter(fw); writer.beginArray(); jsonMap.put(sensorname, writer); writerMap.put(sensorname, fw); files.add(extFile); } catch (FileNotFoundException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.d(SensorRegistry.TAG, sw.toString()); jsonMap.remove(sensorname); writerMap.remove(sensorname); } catch (IOException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.d(SensorRegistry.TAG, sw.toString()); } } return writer; }