List of usage examples for com.google.gson.stream JsonWriter name
public JsonWriter name(String name) 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 w w .java 2 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("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 {/* w w w.ja v a 2 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("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 a 2s. 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("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:BundleTypeAdapterFactory.java
License:Apache License
@SuppressWarnings("unchecked") @Override/*from www .ja va2 s . com*/ public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) { if (!Bundle.class.isAssignableFrom(type.getRawType())) { return null; } return (TypeAdapter<T>) new TypeAdapter<Bundle>() { @Override public void write(JsonWriter out, Bundle bundle) throws IOException { if (bundle == null) { out.nullValue(); return; } out.beginObject(); for (String key : bundle.keySet()) { out.name(key); Object value = bundle.get(key); if (value == null) { out.nullValue(); } else { gson.toJson(value, value.getClass(), out); } } out.endObject(); } @Override public Bundle read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; case BEGIN_OBJECT: return toBundle(readObject(in)); default: throw new IOException("expecting object: " + in.getPath()); } } private Bundle toBundle(List<Pair<String, Object>> values) throws IOException { Bundle bundle = new Bundle(); for (Pair<String, Object> entry : values) { String key = entry.first; Object value = entry.second; if (value instanceof String) { bundle.putString(key, (String) value); } else if (value instanceof Integer) { bundle.putInt(key, ((Integer) value).intValue()); } else if (value instanceof Long) { bundle.putLong(key, ((Long) value).longValue()); } else if (value instanceof Double) { bundle.putDouble(key, ((Double) value).doubleValue()); } else if (value instanceof Parcelable) { bundle.putParcelable(key, (Parcelable) value); } else if (value instanceof List) { List<Pair<String, Object>> objectValues = (List<Pair<String, Object>>) value; Bundle subBundle = toBundle(objectValues); bundle.putParcelable(key, subBundle); } else { throw new IOException("Unparcelable key, value: " + key + ", " + value); } } return bundle; } private List<Pair<String, Object>> readObject(JsonReader in) throws IOException { List<Pair<String, Object>> object = new ArrayList<Pair<String, Object>>(); in.beginObject(); while (in.peek() != JsonToken.END_OBJECT) { switch (in.peek()) { case NAME: String name = in.nextName(); Object value = readValue(in); object.add(new Pair<String, Object>(name, value)); break; case END_OBJECT: break; default: throw new IOException("expecting object: " + in.getPath()); } } in.endObject(); return object; } private Object readValue(JsonReader in) throws IOException { switch (in.peek()) { case BEGIN_ARRAY: return readArray(in); case BEGIN_OBJECT: return readObject(in); case BOOLEAN: return in.nextBoolean(); case NULL: in.nextNull(); return null; case NUMBER: return readNumber(in); case STRING: return in.nextString(); default: throw new IOException("expecting value: " + in.getPath()); } } private Object readNumber(JsonReader in) throws IOException { double doubleValue = in.nextDouble(); if (doubleValue - Math.ceil(doubleValue) == 0) { long longValue = (long) doubleValue; if (longValue >= Integer.MIN_VALUE && longValue <= Integer.MAX_VALUE) { return (int) longValue; } return longValue; } return doubleValue; } @SuppressWarnings("rawtypes") private List readArray(JsonReader in) throws IOException { List list = new ArrayList(); in.beginArray(); while (in.peek() != JsonToken.END_ARRAY) { Object element = readValue(in); list.add(element); } in.endArray(); return list; } }; }
From source file:at.univie.sensorium.logging.JSONLogger.java
License:Open Source License
private void writeObject(AbstractSensor sensor) { if (externalMediaWriteable()) { JsonWriter jw = getWriterForName(sensor.getClass().getName()); List<SensorValue> valuelist = sensor.getSensorValues(); if (jw != null) { try { jw.beginObject();/*from w w w . j a va 2 s. c om*/ jw.name("privacy-level").value(sensor.getPrivacylevel().name()); for (SensorValue value : valuelist) { if (value.isNested()) { jw.name(value.getType().getName()); jw.beginArray(); List<NestedSensorValue> nested = (List<NestedSensorValue>) value.getValue(); for (NestedSensorValue nsv : nested) { List<SensorValue> values = nsv.getInnerSensorValues(); jw.beginObject(); for (SensorValue nestedvalue : values) { SensorValue privatized = Privacy.anonymize(nestedvalue, sensor.getPrivacylevel()); jw.name(privatized.getType().getName()) .value(privatized.getValueRepresentation()); } jw.endObject(); } jw.endArray(); } else { SensorValue privatized = Privacy.anonymize(value, sensor.getPrivacylevel()); jw.name(privatized.getType().getName()).value(privatized.getValueRepresentation()); } } jw.endObject(); writerMap.get(sensor.getClass().getName()).flush(); } catch (IOException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.d(SensorRegistry.TAG, sw.toString()); } } else { Log.d(SensorRegistry.TAG, "Can't get write access to log file, skipping"); } } }
From source file:at.yawk.votifier.VotifierKeyPair.java
License:Mozilla Public License
private void write(JsonWriter writer) throws IOException { writer.beginObject();//from w ww . jav a 2s . c om writer.name("public_key"); writer.value(getPubEncoded()); writer.name("private_key"); writer.value(getPrivEncoded()); writer.endObject(); }
From source file:bammerbom.ultimatecore.bukkit.resources.utils.JsonRepresentedObject.java
License:MIT License
public void writeJson(JsonWriter json) { try {//from w w w . j a v a 2s.c om json.beginObject(); text.writeJson(json); json.name("color").value(color.name().toLowerCase()); for (final ChatColor style : styles) { json.name(stylesToNames.get(style)).value(true); } if (clickActionName != null && clickActionData != null) { json.name("clickEvent").beginObject().name("action").value(clickActionName).name("value") .value(clickActionData).endObject(); } if (hoverActionName != null && hoverActionData != null) { json.name("hoverEvent").beginObject().name("action").value(hoverActionName).name("value"); hoverActionData.writeJson(json); json.endObject(); } if (insertionData != null) { json.name("insertion").value(insertionData); } if (translationReplacements.size() > 0 && text != null && TextualComponent.isTranslatableText(text)) { json.name("with").beginArray(); for (JsonRepresentedObject obj : translationReplacements) { obj.writeJson(json); } json.endArray(); } json.endObject(); } catch (IOException e) { Bukkit.getLogger().log(Level.WARNING, "A problem occured during writing of JSON string", e); } }
From source file:be.iminds.iot.dianne.coordinator.util.DianneCoordinatorWriter.java
License:Open Source License
public static void writeObject(JsonWriter writer, Object o) throws Exception { if (o == null) { writer.value("null"); } else if (o instanceof LearnResult) { writeLearnResult(writer, (LearnResult) o, 0); } else if (o instanceof EvaluationResult) { writeEvaluationResult(writer, (EvaluationResult) o); } else if (o instanceof AgentResult) { writeAgentResult(writer, (AgentResult) o, 0); } else if (o.getClass().equals(String.class) || o.getClass().isEnum() || o.getClass().equals(UUID.class)) { writer.value(o.toString());//from w w w .j ava 2s. c om } else if (o instanceof List) { List<?> l = (List<?>) o; writer.beginArray(); for (Object ll : l) { writeObject(writer, ll); } writer.endArray(); } else if (o instanceof Map) { Map<?, ?> m = (Map<?, ?>) o; writer.beginObject(); for (Object k : m.keySet()) { writer.name(k.toString()); writeObject(writer, m.get(k)); } writer.endObject(); } else if (o.getClass().isArray()) { int length = Array.getLength(o); writer.beginArray(); for (int i = 0; i < length; i++) { writeObject(writer, Array.get(o, i)); } writer.endArray(); } else { writer.beginObject(); writeFields(writer, o); writer.endObject(); } }
From source file:be.iminds.iot.dianne.coordinator.util.DianneCoordinatorWriter.java
License:Open Source License
public static void writeFields(JsonWriter writer, Object o) throws Exception { for (Field f : o.getClass().getFields()) { if (Modifier.isPublic(f.getModifiers())) { writer.name(f.getName()); if (f.getType().isPrimitive()) { switch (f.getType().getName()) { case "long": writer.value(f.getLong(o)); break; case "int": writer.value(f.getInt(o)); break; case "float": writer.value(f.getFloat(o)); break; case "double": writer.value(f.getDouble(o)); break; case "boolean": writer.value(f.getBoolean(o)); break; case "short": writer.value(f.getShort(o)); break; case "byte": writer.value(f.getByte(o)); break; }/*from w w w . ja v a 2s . c o m*/ } else { writeObject(writer, f.get(o)); } } } }
From source file:be.iminds.iot.dianne.coordinator.util.DianneCoordinatorWriter.java
License:Open Source License
public static void writeLearnResult(JsonWriter writer, LearnResult result, int limit) throws Exception { writer.beginArray();//from ww w. j a v a2s .c o m // merge progress and validation in single object // TODO for now select one learners minibatch loss as progress? if (result.progress.size() > 0) { List<LearnProgress> select = result.progress.values().iterator().next(); int step = 1000; if (limit > 0 && select.size() / step > limit) { step = select.size() / step * limit + 1; } for (int i = 0; i < select.size(); i += step) { LearnProgress p = select.get(i); Evaluation val = result.validations.get(p.iteration); writer.beginObject(); writeFields(writer, p); if (val != null) { writer.name("validationLoss"); writer.value(val.metric()); } writer.endObject(); } } writer.endArray(); }