List of usage examples for com.google.gson GsonBuilder GsonBuilder
public GsonBuilder()
From source file:Licenses.java
License:Open Source License
@Override public String jsonProducer() { Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(this); }
From source file:SubscriberBatch.java
License:Open Source License
private void applyReminderNotifications(Connection sd, Connection cResults, String basePath, String serverName) {//from w w w .j a v a2 s . c o m // Sql to get notifications that need a reminder String sql = "select " + "t.id as t_id, " + "n.id as f_id, " + "a.id as a_id, " + "t.survey_ident, " + "t.update_id," + "t.p_id," + "n.target," + "n.remote_user," + "n.notify_details " + "from tasks t, assignments a, forward n " + "where t.tg_id = n.tg_id " + "and t.id = a.task_id " + "and n.enabled " + "and n.trigger = 'task_reminder' " + "and a.status = 'accepted' " //+ "and a.assigned_date < now() - cast(n.period as interval) " // use schedule at however could allow assigned date to be used + "and t.schedule_at < now() - cast(n.period as interval) " + "and a.id not in (select a_id from reminder where n_id = n.id)"; PreparedStatement pstmt = null; // Sql to record a reminder being sent String sqlSent = "insert into reminder (n_id, a_id, reminder_date) values (?, ?, now())"; PreparedStatement pstmtSent = null; try { pstmt = sd.prepareStatement(sql); pstmtSent = sd.prepareStatement(sqlSent); Gson gson = new GsonBuilder().disableHtmlEscaping().create(); HashMap<Integer, ResourceBundle> locMap = new HashMap<>(); MessagingManager mm = new MessagingManager(); ResultSet rs = pstmt.executeQuery(); int idx = 0; while (rs.next()) { if (idx++ == 0) { System.out.println("\n-------------"); } int tId = rs.getInt(1); int nId = rs.getInt(2); int aId = rs.getInt(3); String surveyIdent = rs.getString(4); String instanceId = rs.getString(5); int pId = rs.getInt(6); String target = rs.getString(7); String remoteUser = rs.getString(8); String notifyDetailsString = rs.getString(9); NotifyDetails nd = new Gson().fromJson(notifyDetailsString, NotifyDetails.class); int oId = GeneralUtilityMethods.getOrganisationIdForNotification(sd, nId); // Send the reminder SubmissionMessage subMgr = new SubmissionMessage(tId, surveyIdent, pId, instanceId, nd.from, nd.subject, nd.content, nd.attach, nd.include_references, nd.launched_only, nd.emailQuestion, nd.emailQuestionName, nd.emailMeta, nd.emails, target, remoteUser, "https", serverName, basePath); mm.createMessage(sd, oId, "reminder", "", gson.toJson(subMgr)); // record the sending of the notification pstmtSent.setInt(1, nId); pstmtSent.setInt(2, aId); pstmtSent.executeUpdate(); // Write to the log ResourceBundle localisation = locMap.get(nId); if (localisation == null) { Organisation organisation = GeneralUtilityMethods.getOrganisation(sd, oId); Locale orgLocale = new Locale(organisation.locale); localisation = ResourceBundle.getBundle("org.smap.sdal.resources.SmapResources", orgLocale); } String logMessage = "Reminder sent for: " + nId; if (localisation != null) { logMessage = localisation.getString("lm_reminder"); logMessage = logMessage.replaceAll("%s1", GeneralUtilityMethods.getNotificationName(sd, nId)); } lm.writeLogOrganisation(sd, oId, "subscriber", LogManager.REMINDER, logMessage); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } try { if (pstmtSent != null) { pstmtSent.close(); } } catch (SQLException e) { } } }
From source file:Api.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w.j av a 2s . c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ ArrayList lista = new ArrayList(); String modulo = request.getParameter("modulo"); String idCiudad = request.getParameter("id_ciudad"); String idPais = request.getParameter("id_pais"); Country pais = new Country(); // Paises if (modulo.equals("paises")) { ResultSet fila = pais.showAll(); try { while (fila.next()) { Country country = new Country(); country.setName(fila.getString("name")); country.setCountry_id(fila.getInt("country_id")); lista.add(country); } } catch (Exception ex) { } } // Ciudades if (modulo.equals("ciudades")) { if (idCiudad != null) { // devolvemos la ciudad con el id ciudad City ciudad = new City(); ciudad.setCity_id(Integer.parseInt(idCiudad)); ResultSet fila = ciudad.getOne(); try { while (fila.next()) { City c = new City(); c.setName(fila.getString("name")); c.setCity_id(fila.getInt("city_id")); c.setCountry_id(fila.getInt("country_id")); c.setState(fila.getInt("state")); lista.add(c); } } catch (Exception ex) { } } else if (idPais != null) { // devolvemos las ciudades con el pais al que pertenece City ciudad = new City(); ResultSet fila = ciudad.showAllFrom(Integer.parseInt(idPais)); try { while (fila.next()) { City c = new City(); c.setName(fila.getString("name")); c.setCity_id(fila.getInt("city_id")); c.setCountry_id(fila.getInt("country_id")); c.setState(fila.getInt("state")); lista.add(c); } } catch (Exception ex) { } } else { City ciudad = new City(); ResultSet fila = ciudad.showAll(); try { while (fila.next()) { City c = new City(); c.setName(fila.getString("name")); c.setCity_id(fila.getInt("city_id")); c.setCountry_id(fila.getInt("country_id")); c.setState(fila.getInt("state")); lista.add(c); } } catch (Exception ex) { } } } Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(lista); response.setContentType("application/json;charset=UTF-8"); out.write(json); } }
From source file:InventoryIncrementItemServlet.java
License:Open Source License
@Override public HttpResponse doWork(HttpRequest request, String rootDirectory) { HttpResponse response;/* w w w. ja va2s. c o m*/ try { String inventoryUrl = "./web/inventory.json"; File inventory = new File(inventoryUrl); StringBuilder sb = new StringBuilder(); Scanner sc = new Scanner(inventory); while (sc.hasNext()) { sb.append(sc.nextLine()); } sc.close(); // Add this new book to the list of existing books Gson gson = new Gson(); InventoryObject[] inventoryArray = gson.fromJson(sb.toString(), InventoryObject[].class); ArrayList<InventoryObject> inventoryList = new ArrayList<InventoryObject>( Arrays.asList(inventoryArray)); String body = new String(request.getBody()); System.out.println(body); String[] newItem = body.split("&"); // Find existing item and add passed quantity int id = Integer.parseInt(newItem[0].split("=")[1]); int quant = Integer.parseInt(newItem[1].split("=")[1]); for (InventoryObject item : inventoryList) { if (item.getID() == id) { if (item.getQuantity() == 0 && quant == -1) { return HttpResponseFactory.create400BadRequest(Protocol.CLOSE); } else { item.setQuantity(item.getQuantity() + quant); } } } // Serialize new list Gson gsonBuilder = new GsonBuilder().setPrettyPrinting().create(); String arrayListToJson = gsonBuilder.toJson(inventoryList); BufferedWriter bw = new BufferedWriter(new FileWriter(inventory)); bw.write(arrayListToJson); bw.close(); response = HttpResponseFactory.create200OK(inventory, Protocol.CLOSE); } catch (Exception e) { response = HttpResponseFactory.create404NotFound(Protocol.CLOSE); } return response; }
From source file:InventoryAddNewItemServlet.java
License:Open Source License
@Override public HttpResponse doWork(HttpRequest request, String rootDirectory) { HttpResponse response;/*from ww w. j a v a 2 s . c om*/ try { String inventoryUrl = "./web/inventory.json"; File inventory = new File(inventoryUrl); StringBuilder sb = new StringBuilder(); Scanner sc = new Scanner(inventory); while (sc.hasNext()) { sb.append(sc.nextLine()); } sc.close(); // Add this new book to the list of existing books Gson gson = new Gson(); InventoryObject[] inventoryArray = gson.fromJson(sb.toString(), InventoryObject[].class); ArrayList<InventoryObject> inventoryList = new ArrayList<InventoryObject>( Arrays.asList(inventoryArray)); String body = new String(request.getBody()); System.out.println(body); String[] newItem = body.split("&"); // Add new item int id, quant; String name; try { id = Integer.parseInt(newItem[0].split("=")[1]); name = newItem[1].split("=")[1].replace("+", " "); quant = Integer.parseInt(newItem[2].split("=")[1]); } catch (Exception e) { return HttpResponseFactory.create400BadRequest(Protocol.CLOSE); } InventoryObject item = new InventoryObject(id, name, quant); if (quant < 0) { return HttpResponseFactory.create400BadRequest(Protocol.CLOSE); } for (InventoryObject existingItem : inventoryList) { if (existingItem.getID() == id) { return HttpResponseFactory.create400BadRequest(Protocol.CLOSE); } } inventoryList.add(item); // Serialize new list Gson gsonBuilder = new GsonBuilder().setPrettyPrinting().create(); String arrayListToJson = gsonBuilder.toJson(inventoryList); BufferedWriter bw = new BufferedWriter(new FileWriter(inventory)); bw.write(arrayListToJson); bw.close(); response = HttpResponseFactory.create200OK(inventory, Protocol.CLOSE); } catch (Exception e) { response = HttpResponseFactory.create404NotFound(Protocol.CLOSE); } return response; }
From source file:DataConverter.java
License:Open Source License
public static void main(String args[]) { try {/* www . j a va 2 s . co m*/ Scanner customer = new Scanner(new BufferedReader(new FileReader("data/Customers.dat"))); Scanner persons = new Scanner(new BufferedReader(new FileReader("data/Persons.dat"))); Scanner products = new Scanner(new BufferedReader(new FileReader("data/Products.dat"))); int customerSize = customer.nextInt(); int personsSize = persons.nextInt(); int productsSize = products.nextInt(); String customerArray[] = new String[9]; String personsArray[] = new String[personsSize]; String productsArray[] = new String[productsSize]; Customer butters[] = new Customer[customerSize]; int i = 0; while (customer.hasNextLine()) { String array[] = new String[5]; char[] arr = customer.nextLine().toCharArray(); String blah = ""; int k = 0; for (int j = 0; j < arr.length; j++) { if (" ".equals(String.valueOf(arr[j])) && String.valueOf(arr[j - 1]).equals(";")) { } else if (";".equals(String.valueOf(arr[j])) || j == arr.length - 1) { array[k] = blah; blah = ""; System.out.println(array[k]); k++; } else { blah = blah + String.valueOf(arr[j]); } } String code = array[0]; String type = array[1]; String pCode = array[2]; String name = array[3]; String address = array[4]; Customer c = new Customer(code, type, pCode, name, address); c.setCustomerCode(code); c.setCustomerType(type); c.setPrimaryCode(pCode); c.setName(name); c.setAddress(address); butters[i] = c; i++; } Gson gson = new GsonBuilder().create(); for (int a = 0; a < customerSize; a++) { } // for(int j=0; j<; j++) { // int k = 0; // if(arr[j] == scrotum.charAt(0)) { // array[k] = balls; // balls = ""; // } else { // balls = balls + String.valueOf(arr[j]); // } // } // for(int i=0; i < customerSize; i++) { // String split[] = customerArray[i].split(";"); // String code = split[0]; // String type = split[1]; // String pCode = split[2]; // String name = split[3]; // String address = split[4]; // System.out.print(code + type + pCode + name + address); // } } catch (Exception e) { throw new RuntimeException(e); } // int customerSize = customer.nextInt(); // int personsSize = persons.nextInt(); // int productsSize = products.nextInt(); // // String customerArray[] = new String[customerSize]; // String personsArray[] = new String[personsSize]; // String productsArray[] = new String[productsSize]; // ArrayList<String> customerSplit = new ArrayList<String>(); // // while(customer.hasNext()){ // int i = 0; // customerArray[i] = customer.nextLine(); // } // while(persons.hasNext()) { // int i = 0; // personsArray[i] = persons.nextLine(); // i++; // } // // while(products.hasNext()) { // int i = 0; // productsArray[i] = customer.next(); // i++; // } // for(int i=0; i < customerSize; i++) { // String split[] = customerArray[i].split(";"); // String code = split[0]; // String type = split[1]; // String pCode = split[2]; // String name = split[3]; // String address = split[4]; // System.out.print(code + type + pCode + name + address); // while(customerArray[i].matches(";")) { // // customerSplit.set()= customerArray[i]; // j++; // } }
From source file:CBDocUtil.java
String prettyPrint(String uglyJSONString) { String prettyJsonString = uglyJSONString; try {//from www. j a va 2 s .c o m Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(uglyJSONString); prettyJsonString = gson.toJson(je); } catch (Exception e1) { logger.log(java.util.logging.Level.INFO, "Excepton {0} {1} ", new Object[] { e1.getMessage(), getPrintStackTrace(e1) }); } return prettyJsonString; }
From source file:InventoryDeleteItemServlet.java
License:Open Source License
@Override public HttpResponse doWork(HttpRequest request, String rootDirectory) { HttpResponse response;/*from www . j ava 2 s .c om*/ try { String inventoryUrl = "./web/inventory.json"; File inventory = new File(inventoryUrl); StringBuilder sb = new StringBuilder(); Scanner sc = new Scanner(inventory); while (sc.hasNext()) { sb.append(sc.nextLine()); } sc.close(); // Add this new book to the list of existing books Gson gson = new Gson(); InventoryObject[] inventoryArray = gson.fromJson(sb.toString(), InventoryObject[].class); ArrayList<InventoryObject> inventoryList = new ArrayList<InventoryObject>( Arrays.asList(inventoryArray)); String body = new String(request.getBody()); System.out.println(body); // Find existing item and remove it int id = Integer.parseInt(body.split("=")[1]); for (InventoryObject item : inventoryList) { if (item.getID() == id) { inventoryList.remove(item); break; } } // Serialize new list Gson gsonBuilder = new GsonBuilder().setPrettyPrinting().create(); String arrayListToJson = gsonBuilder.toJson(inventoryList); BufferedWriter bw = new BufferedWriter(new FileWriter(inventory)); bw.write(arrayListToJson); bw.close(); response = HttpResponseFactory.create200OK(inventory, Protocol.CLOSE); } catch (Exception e) { response = HttpResponseFactory.create404NotFound(Protocol.CLOSE); } return response; }
From source file:AppSpringLayout.java
protected ArrayList<String> searchToDisplayOnJList(String text, String imageType, String sizeType, String licenseType, String safeSearchType, String numberOfImg) { SearchForSimilarImages bingSearch = new SearchForSimilarImages(); // String responseBing = bingSearch.GetUrlContentAsString(bingToken, // text, imageType, sizeType, licenseType, // safeSearchType); String responseBing = bingSearch.GetUrlContentAsStringWithNumber(bingToken, text, imageType, sizeType, licenseType, safeSearchType, numberOfImg); GsonBuilder gsonBingBuilder = new GsonBuilder(); Gson gsonBing = gsonBingBuilder.create(); RootBing rootBing = gsonBing.fromJson(responseBing, RootBing.class); // created temporary array list with all urls ArrayList<Urls> originalUrls = rootBing.getValue(); // filtered only working links ArrayList<String> checkedUrls = checkLinks(originalUrls); // System.out.println("Links to display: "); // converted it to a string array linksResponse = new String[checkedUrls.size()]; linksResponse = checkedUrls.toArray(linksResponse); listModel.clear();/* ww w . j a v a 2s . com*/ for (String item : linksResponse) { // String listItemText = item; displayImageOnJList(item); // shows only for the last one // TODO modify - may be with ListCellRenderer // subclass DefaultListCellRenderer and override the // getListCellRendererComponent() method // list.setToolTipText("<html><img src=\"" + item + "\">"); listModel.addElement(icon); } list.setModel(listModel); System.out.println("found all links"); progressBar.setVisible(false); lblFoundLinks.setText(""); return checkedUrls; }
From source file:AppSpringLayout.java
protected String analyse() { AnalyseImage computerVisionSearch = new AnalyseImage(); String response = computerVisionSearch.describeImage(originalImage, computerVisionImageToken); GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create();/*from w w w. j av a 2s . com*/ RootComputerVision root = gson.fromJson(response, RootComputerVision.class); String[] tags = root.getDescription().getTags(); System.out.println("============="); System.out.println("tags " + Arrays.toString(tags)); int numberOfTags; // limit number of tags displayed to maximum first five if (tags.length >= 5) { numberOfTags = 5; } else { numberOfTags = tags.length; } tagsTextArea.setText(""); numberOfImagesToSearchFor.setText(""); for (int i = 0; i < numberOfTags; i++) { tagsTextArea.append(tags[i] + "\n"); // get tags from string array to a string variable tagsString = tagsString + tags[i] + "%20"; } for (Captions currentCaption : root.getDescription().getCaptions()) { text = currentCaption.getText(); System.out.println("description: " + text); System.out.println("============="); descriptionTextArea.setText(text); } String textString = text.replace(" ", "%20"); return tagsString + textString; }