List of usage examples for org.json.simple JSONArray JSONArray
JSONArray
From source file:com.imagelake.android.search.Servlet_Search.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); try {// ww w . ja v a 2 s . c o m String type = request.getParameter("type"); System.out.println(type); //---------------------- int page = 1; int recordsPerPage = 10; if (request.getParameter("page") != null) { page = Integer.parseInt(request.getParameter("page")); } //--------------------- //get the session SearchResults sr = new SearchResults(); // //check that the session has already have a SearchResult object // if (ses.getAttribute("results") == null) { // System.out.println("no previous session"); // sr = new SearchResults(); // // } else { // // sr = (SearchResults) ses.getAttribute("results"); // } // sr.setImList(new ArrayList<Images>()); // if (type.equals("SearchImages")) { jja = new JSONArray(); //int noOfRecords = 0; String ca = request.getParameter("cat"); String ke = request.getParameter("key"); //String colo=request.getParameter("colo"); String credFrom = request.getParameter("from"); String credTo = request.getParameter("to"); String seller = request.getParameter("sell"); String size = request.getParameter("size"); System.out.println(ca); System.out.println(ke); System.out.println(credFrom); System.out.println(credTo); System.out.println(seller); System.out.println(size); String A = "A" + ca + "A"; String B = "B" + ke + "B"; //String C = "C" + colo + "C"; String D = "D" + credFrom + "D"; String G = "G" + credTo + "G"; String E = "E" + seller + "E"; String F = "F" + size + "F"; System.out.println("cat:" + ca + "-------------" + A); System.out.println("Key:" + ke + "-------------" + B); //System.out.println("colo:" + colo + "-------------" + C); System.out.println("cred:" + credFrom + "-------------" + D); System.out.println("cred:" + credTo + "-------------" + G); System.out.println("seller:" + seller + "-------------" + E); System.out.println("size:" + size + "-------------" + F); String key[] = ke.split("-"); String ky = ""; for (int i = 0; i < key.length; i++) { if (i == (key.length - 1)) { ky += key[i]; } else { ky += key[i] + " "; } } if (ca != null && ca != "" && !A.equals("AA") && !A.equals("A0A")) { System.out.println("cat is not null" + ca); sr.setCategory(ca); System.out.println("cat is not null" + sr.getCategory()); } else if (A.equals("AcloseA")) { sr.setCategory(null); } if (ke != null && ke != "" && !B.equals("BB") && !B.equals("BnullB")) { System.out.println("key is not null" + ky); sr.setKeyWord(ky); System.out.println("key is not null" + sr.getKeyWord()); } else if (B.equals("BcloseB")) { sr.setKeyWord(null); } // if(colo!=null && colo!="" && !C.equals("CnullC") &&!C.equals("CC")&&!C.equals("CcloseC")){ // System.out.println("color is not null"+colo); // HexaToRBG hrg=new HexaToRBG(); // String rgbColo=hrg.convertHexToRGB("0x00"+colo); // sr.setColor(rgbColo); // System.out.println("color is not null"+sr.getColor()); // }else if(C.equals("CcloseC")){ // sr.setColor(null); // } if (credFrom != null && credFrom != "" && !D.equals("DD") && !D.equals("DnullD") && !D.equals("D0D") && credTo != null && credTo != "" && !G.equals("GG") && !G.equals("GnullG") && !G.equals("G0G")) { System.out.println("credits is not null" + credFrom); sr.setCreditFrom(Integer.parseInt(credFrom)); System.out.println("key is not null" + sr.getCreditFrom()); sr.setCreditTo(Integer.parseInt(credTo)); System.out.println("key is not null" + sr.getCreditTo()); } else if (D.equals("D0D") && G.equals("G0G")) { sr.setCreditFrom(0); sr.setCreditTo(0); } if (seller != null && seller != "" && !E.equals("EE") && !E.equals("EnullE") && !E.equals("E0E")) { System.out.println("color is not null" + seller); sr.setSellerId(Integer.parseInt(seller)); System.out.println("color is not null" + sr.getSellerId()); } else if (E.equals("E0E")) { sr.setSellerId(0); } if (size != null && size != "" && !F.equals("FF") && !F.equals("FnullF") && !F.equals("F0F")) { System.out.println("credits is not null" + size); String c[] = size.split("x"); sr.setSize(c[0] + " x " + c[1]); System.out.println("key is not null" + sr.getSize()); } else if (F.equals("FcloseF")) { sr.setSize(null); } String sql = "SELECT SQL_CALC_FOUND_ROWS * FROM images WHERE image_state_image_state_id='1' AND "; if (sr.getCategory() != null) { sql += "categories_category_id='" + sr.getCategory() + "'"; if (sr.getColor() != null || sr.getCreditFrom() != 0 && sr.getCreditTo() != 0 || sr.getKeyWord() != null || sr.getSellerId() != 0 || sr.getSize() != null) { sql += " AND "; } } if (sr.getSellerId() != 0) { sql += "user_user_id='" + sr.getSellerId() + "'"; if (sr.getColor() != null || sr.getCreditFrom() != 0 && sr.getCreditTo() != 0 || sr.getKeyWord() != null || sr.getSize() != null) { sql += " AND "; } } // if (sr.getColor() != null) { // sql += "images_id IN(SELECT images_id FROM images WHERE dominate_color='" + sr.getColor() + "' OR color_1='" + sr.getColor() + "' OR color_2='" + sr.getColor() + "' OR color_3='" + sr.getColor() + "' OR color_4='" + sr.getColor() + "' OR color_5='" + sr.getColor() + "' OR color_6='" + sr.getColor() + "' OR color_7='" + sr.getColor() + "' OR color_8='" + sr.getColor() + "' OR color_9='" + sr.getColor() + "')"; // if (sr.getCreditFrom() != 0 && sr.getCreditTo() != 0 || sr.getKeyWord() != null || sr.getSize() != null) { // sql += " AND "; // } // } if (sr.getCreditFrom() != 0 && sr.getCreditTo() != 0) { sql += "images_id IN(SELECT images_images_id FROM sub_images WHERE credits IN(SELECT credit_id FROM credits WHERE credits BETWEEN '" + sr.getCreditTo() + "' AND '" + sr.getCreditFrom() + "'))"; if (sr.getKeyWord() != null || sr.getSize() != null) { sql += " AND "; } } if (sr.getKeyWord() != null) { sql += "images_id IN(SELECT images_images_id FROM key_words WHERE key_word LIKE '%" + sr.getKeyWord() + "%')"; if (sr.getSize() != null) { sql += " AND "; } } if (sr.getSize() != null) { sql += "images_id IN(SELECT images_images_id FROM sub_images WHERE dimention='" + sr.getSize() + "')"; } if (sr.getCategory() == null && sr.getColor() == null && sr.getCreditFrom() == 0 && sr.getCreditTo() == 0 && sr.getKeyWord() == null && sr.getSellerId() == 0 && sr.getSize() == null) { sql += "image_state_image_state_id='1' "; } sql += " ORDER BY date DESC LIMIT " + (page - 1) * recordsPerPage + ", " + recordsPerPage; System.out.println(sql); try { PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql); ResultSet rs = ps.executeQuery(); ja = new JSONArray(); jja = new JSONArray(); while (rs.next()) { System.out.println("Image id from category:" + rs.getInt(1)); c = ctdi.getCategory(rs.getInt(19)); us = udi.getUser(rs.getInt(18)); //isb = idi.getSubImage(rs.getInt(1)); JSONObject jo = new JSONObject(); jo.put("id", rs.getInt(1)); jo.put("cat", c.getCategory()); jo.put("title", rs.getString(2)); jo.put("seller", us.getUser_name()); jo.put("url", rs.getString(15)); jo.put("dimention", rs.getString(16)); List<CartHasImages> chiList = cdi.getRattingList(rs.getInt(1)); rate = 0.0; userCount = 0.0; totalRate = 0.0; if (!chiList.isEmpty()) { for (CartHasImages chi : chiList) { totalRate += chi.getRatting(); userCount++; rate = totalRate / userCount; } } jo.put("rate", rate); ja.add(jo); } jja.add(ja); rs.close(); PreparedStatement ps2 = DBFactory.getConnection().prepareStatement(sql); ResultSet rs2 = ps.executeQuery(); rs2 = ps2.executeQuery("SELECT FOUND_ROWS()"); if (rs2.next()) { this.noOfRecords = rs2.getInt(1); System.out.println(rs2.getInt(1)); } //jja.add(ja); } catch (Exception e) { e.printStackTrace(); } int noOfRecords = getNoOfRecords(); int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage); JSONObject jo = new JSONObject(); jo.put("noOfPages", noOfPages); jo.put("currentPage", page); jja.add(jo); // System.out.println("list empty: " + sr.getImList().isEmpty()); // ses.setAttribute("results", sr); // ses.setAttribute("noOfPages", noOfPages); // ses.setAttribute("currentPage", page); System.out.println(jja.toJSONString()); out.write("json=" + jja.toJSONString()); } else if (type.equals("AllImages")) { //int noOfRecords = 0; String sql = "SELECT SQL_CALC_FOUND_ROWS * FROM images WHERE image_state_image_state_id='1'"; sql += " ORDER BY date DESC LIMIT " + (page - 1) * recordsPerPage + ", " + recordsPerPage; System.out.println(sql); try { PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql); ResultSet rs = ps.executeQuery(); ja = new JSONArray(); jja = new JSONArray(); while (rs.next()) { System.out.println("Image id from category:" + rs.getInt(1)); c = ctdi.getCategory(rs.getInt(19)); us = udi.getUser(rs.getInt(18)); //isb = idi.getSubImage(rs.getInt(1)); JSONObject jo = new JSONObject(); jo.put("id", rs.getInt(1)); jo.put("cat", c.getCategory()); jo.put("title", rs.getString(2)); jo.put("seller", us.getUser_name()); jo.put("url", rs.getString(15)); jo.put("dimention", rs.getString(16)); List<CartHasImages> chiList = cdi.getRattingList(rs.getInt(1)); rate = 0.0; userCount = 0.0; totalRate = 0.0; if (!chiList.isEmpty()) { for (CartHasImages chi : chiList) { totalRate += chi.getRatting(); userCount++; rate = totalRate / userCount; } } jo.put("rate", rate); ja.add(jo); } jja.add(ja); rs.close(); PreparedStatement ps2 = DBFactory.getConnection().prepareStatement(sql); ResultSet rs2 = ps.executeQuery(); rs2 = ps2.executeQuery("SELECT FOUND_ROWS()"); if (rs2.next()) { this.noOfRecords = rs2.getInt(1); System.out.println(rs2.getInt(1)); } } catch (Exception e) { e.printStackTrace(); } int noOfRecords = getNoOfRecords(); int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage); System.out.println("No of records" + noOfRecords); System.out.println("No of pages" + noOfPages); JSONObject jo = new JSONObject(); jo.put("noOfPages", noOfPages); jo.put("currentPage", page); jja.add(jo); // System.out.println("list empty: " + sr.getImList().isEmpty()); // ses.setAttribute("results", sr); // ses.setAttribute("noOfPages", noOfPages); // ses.setAttribute("currentPage", page); System.out.println(jja.toJSONString()); out.write("json=" + jja.toJSONString()); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.assignment4.productdetails.java
@GET @Path("{id}") @Produces(MediaType.APPLICATION_JSON)//from w ww . j a v a 2 s.c o m public String getproduct(@PathParam("id") int id) throws SQLException { if (conn == null) { return "it not able to connect"; } else { String query = "Select * from products where product_id = ?"; PreparedStatement prestmt = conn.prepareStatement(query); prestmt.setInt(1, id); ResultSet res = prestmt.executeQuery(); String results = ""; JSONArray podtAr = new JSONArray(); while (res.next()) { Map pdtmap = new LinkedHashMap(); pdtmap.put("productID", res.getInt("product_id")); pdtmap.put("name", res.getString("name")); pdtmap.put("description", res.getString("description")); pdtmap.put("quantity", res.getInt("quantity")); podtAr.add(pdtmap); } results = podtAr.toString(); return results; } }
From source file:jenkins.plugins.testrail.util.TestRailJsonParser.java
/** * * @param oldPlanJson//from ww w .j a v a2s . c o m * @param oldPlanTestsJson * @return */ public String createNewPlan(String oldPlanJson, Map<String, String> oldPlanTestsJson) throws ParseException { LOGGER.debug("createNewPlan() called."); LOGGER.debug(oldPlanJson); final JSONObject oldRootJsonObject = (JSONObject) new JSONParser().parse(oldPlanJson); LOGGER.debug("Grabbing first JSON entries"); final String testName = oldRootJsonObject.get("name").toString(); final String testDescription = oldRootJsonObject.get("description").toString(); final String testMilestoneId = oldRootJsonObject.get("milestone_id").toString(); LOGGER.debug("testName: " + testName); LOGGER.debug("testDescription: " + testDescription); LOGGER.debug("testMilestoneId: " + testMilestoneId); this.newTestPlanJsonObject.put("name", testName); this.newTestPlanJsonObject.put("description", testDescription); this.newTestPlanJsonObject.put("milestone_id", testMilestoneId); // Create new "entries" array and populate it LOGGER.debug("Parsing entries..."); JSONArray newEntriesArray = new JSONArray(); JSONArray oldEntriesArray = (JSONArray) oldRootJsonObject.get("entries"); for (Object oldEntryObject : oldEntriesArray) { JSONObject oldEntryJsonObject = (JSONObject) oldEntryObject; JSONObject newEntryJsonObject = new JSONObject(); newEntryJsonObject.put("suite_id", oldEntryJsonObject.get("suite_id").toString()); newEntryJsonObject.put("include_all", false); JSONArray newCaseIdsArray = new JSONArray(); JSONArray newConfigIdsArray = new JSONArray(); JSONArray oldRunsJsonArray = (JSONArray) oldEntryJsonObject.get("runs"); JSONArray newRunsJsonArray = new JSONArray(); for (Object oldRunObj : oldRunsJsonArray) { JSONObject oldRunJsonObj = (JSONObject) oldRunObj; JSONObject newRunJsonObj = new JSONObject(); JSONArray newRunCaseIdsArray = new JSONArray(); JSONArray newRunConfigIdsArray = new JSONArray(); //newCaseIdsArray.add(((JSONObject) run_obj).get("id")); String testId = oldRunJsonObj.get("id").toString(); JSONArray testJsonArray = (JSONArray) new JSONParser().parse(oldPlanTestsJson.get(testId)); for (Object testObject : testJsonArray) { JSONObject testJsonObject = (JSONObject) testObject; newCaseIdsArray.add(testJsonObject.get("case_id")); newRunCaseIdsArray.add(testJsonObject.get("case_id")); } JSONArray oldConfigIdsJsonArray = (JSONArray) oldRunJsonObj.get("config_ids"); for (Object configIdObject : oldConfigIdsJsonArray) { final String configIdString = configIdObject.toString(); newConfigIdsArray.add(configIdString); newRunConfigIdsArray.add(configIdString); } newRunJsonObj.put("include_all", false); newRunJsonObj.put("assignedto_id", null); newRunJsonObj.put("case_ids", newRunCaseIdsArray); newRunJsonObj.put("config_ids", newRunConfigIdsArray); newRunsJsonArray.add(newRunJsonObj); } newEntryJsonObject.put("case_ids", newCaseIdsArray); newEntryJsonObject.put("config_ids", newConfigIdsArray); newEntryJsonObject.put("runs", newRunsJsonArray); newEntriesArray.add(newEntryJsonObject); } // Insert new "entries" array this.newTestPlanJsonObject.put("entries", newEntriesArray); this.newTestPlanJsonString = this.newTestPlanJsonObject.toJSONString(); return this.newTestPlanJsonString; }
From source file:com.flaptor.indextank.api.resources.Search.java
/** * @see java.lang.Runnable#run()//from w ww .ja va 2 s . c o m */ public void run() { IndexEngineApi api = (IndexEngineApi) ctx().getAttribute("api"); HttpServletResponse res = res(); String characterEncoding = api.getCharacterEncoding(); try { req().setCharacterEncoding(characterEncoding); res.setCharacterEncoding(characterEncoding); res.setContentType("application/json"); } catch (UnsupportedEncodingException ignored) { } String q = params("q"); String fetchVariables = params("fetch_variables"); String fetchCategories = params("fetch_categories"); String fetch = params("fetch"); String snippet = params("snippet"); int start = QueryHelper.parseIntParam(params("start"), 0); int len = QueryHelper.parseIntParam(params("len"), 10); int function = QueryHelper.parseIntParam(params("function"), 0); Map<Integer, Double> vars = Maps.newHashMap(); List<CategoryFilter> facetFilters = Lists.newArrayList(); List<RangeFilter> variableRangeFilters = Lists.newArrayList(); List<RangeFilter> functionRangeFilters = Lists.newArrayList(); Map<String, String> extras = createExtraParameters(fetch, snippet, fetchVariables, fetchCategories); try { long t0 = System.currentTimeMillis(); SearchResults results = api.search(q, start, len, function, vars, facetFilters, variableRangeFilters, functionRangeFilters, extras); long t1 = System.currentTimeMillis(); double searchTime = (t1 - t0) / 1000; int matches = results.getMatches(); Map<String, Map<String, Integer>> facets = toFacets(results.getFacets()); String didYouMean = results.getDidYouMean(); JSONArray ja = new JSONArray(); for (SearchResult result : results.getResults()) { addResult(ja, result); } JSONObject jo = createResponse(q, searchTime, ja, matches, facets, didYouMean); print(jo.toJSONString()); return; } catch (IndexEngineApiException e) { e.printStackTrace(); } res.setStatus(503); print("Service unavailable"); // TODO: descriptive error msg }
From source file:modelo.ParametrizacionManagers.TiposContactos.java
/** * * Obtiene la informacion del tipo de contacto mediante un codigo y * guarda todo en un JSONArray para entregarselo a la vista. * * @return JSONArray/*from w w w . java2 s. com*/ * @throws SQLException */ public JSONArray getTipoContacto(int codigo) throws Exception { //Ejecutamos la consulta y obtenemos el ResultSet SeleccionarTiposContactos seleccionar = new SeleccionarTiposContactos(); ResultSet rst = seleccionar.getTipoContacto(codigo); //Creamos los JSONArray para guardar los objetos JSON JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = new JSONObject(); while (rst.next()) { //Creamos el objecto JSON jsonObject.put("descripcion", rst.getString("DESCRIPCION")); jsonObject.put("codigo", rst.getString("CODIGO")); //Creamos el Array JSON jsonArray.add(jsonObject.clone()); } seleccionar.desconectar(); return jsonArray; }
From source file:org.kitodo.data.index.elasticsearch.type.TaskType.java
@SuppressWarnings("unchecked") @Override//from www . j ava 2 s .c o m public HttpEntity createDocument(Task task) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); LinkedHashMap<String, String> orderedTaskMap = new LinkedHashMap<>(); orderedTaskMap.put("title", task.getTitle()); String priority = task.getPriority() != null ? task.getPriority().toString() : "null"; orderedTaskMap.put("priority", priority); String ordering = task.getOrdering() != null ? task.getOrdering().toString() : "null"; orderedTaskMap.put("ordering", ordering); String processingStatus = task.getProcessingStatusEnum() != null ? task.getProcessingStatusEnum().toString() : "null"; orderedTaskMap.put("processingStatus", processingStatus); String processingTime = task.getProcessingTime() != null ? dateFormat.format(task.getProcessingTime()) : null; orderedTaskMap.put("processingTime", processingTime); String processingBegin = task.getProcessingBegin() != null ? dateFormat.format(task.getProcessingBegin()) : null; orderedTaskMap.put("processingBegin", processingBegin); String processingEnd = task.getProcessingEnd() != null ? dateFormat.format(task.getProcessingEnd()) : null; orderedTaskMap.put("processingEnd", processingEnd); orderedTaskMap.put("homeDirectory", String.valueOf(task.getHomeDirectory())); orderedTaskMap.put("typeMetadata", String.valueOf(task.isTypeMetadata())); orderedTaskMap.put("typeAutomatic", String.valueOf(task.isTypeAutomatic())); orderedTaskMap.put("typeImportFileUpload", String.valueOf(task.isTypeImportFileUpload())); orderedTaskMap.put("typeExportRussian", String.valueOf(task.isTypeExportRussian())); orderedTaskMap.put("typeImagesRead", String.valueOf(task.isTypeImagesRead())); orderedTaskMap.put("typeImagesWrite", String.valueOf(task.isTypeImagesWrite())); orderedTaskMap.put("batchStep", String.valueOf(task.isBatchStep())); String processingUser = task.getProcessingUser() != null ? task.getProcessingUser().getId().toString() : "null"; orderedTaskMap.put("processingUser", processingUser); String process = task.getProcess() != null ? task.getProcess().getId().toString() : "null"; orderedTaskMap.put("process", process); JSONObject taskObject = new JSONObject(orderedTaskMap); JSONArray users = new JSONArray(); List<User> taskUsers = task.getUsers(); for (User user : taskUsers) { JSONObject propertyObject = new JSONObject(); propertyObject.put("id", user.getId()); users.add(propertyObject); } taskObject.put("users", users); JSONArray userGroups = new JSONArray(); List<UserGroup> taskUserGroups = task.getUserGroups(); for (UserGroup userGroup : taskUserGroups) { JSONObject userGroupObject = new JSONObject(); userGroupObject.put("id", userGroup.getId().toString()); userGroups.add(userGroupObject); } taskObject.put("userGroups", userGroups); return new NStringEntity(taskObject.toJSONString(), ContentType.APPLICATION_JSON); }
From source file:modelo.ParametrizacionManagers.MotivosVisitas.java
/** * * Obtiene la informacion del tipo de contacto mediante un codigo y * guarda todo en un JSONArray para entregarselo a la vista. * * @return JSONArray//from w ww. j ava2s . c o m * @throws SQLException */ public JSONArray getMotivoVisita(int codigo) throws Exception { //Ejecutamos la consulta y obtenemos el ResultSet SeleccionarMotivosVisitas seleccionar = new SeleccionarMotivosVisitas(); ResultSet rst = seleccionar.getMotivoVisita(codigo); //Creamos los JSONArray para guardar los objetos JSON JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = new JSONObject(); while (rst.next()) { //Creamos el objecto JSON jsonObject.put("descripcion", rst.getString("DESCRIPCION")); jsonObject.put("codigo", rst.getString("CODIGO")); //Creamos el Array JSON jsonArray.add(jsonObject.clone()); } seleccionar.desconectar(); return jsonArray; }
From source file:control.ProcesoVertimientosServlets.SeleccionarVisitas.java
private void getVisitas(HttpServletRequest request, HttpServletResponse response) { try {/*from w w w. j a v a2s . c o m*/ //Parametros que envia el plugin jQuery FullCalendar, estos son enviados en formato TimeStamp String fechaInicio = request.getParameter("fechaInicio"); String fechaFin = request.getParameter("fechaFin"); String tipoVisita = request.getParameter("tipoVisita"); String codigoProceso = request.getParameter("codigoProceso"); String estadoVisita = request.getParameter("estadoVisita"); String contrato = request.getParameter("contrato"); String nit = request.getParameter("nit"); String razonSocial = request.getParameter("razonSocial"); String motivoVisita = request.getParameter("motivoVisita"); JSONArray jsonArray = new JSONArray(); //Este parametro es enviado automaticamente por Kendoui int take = ApiManager.numeroNull(request.getParameter("take")); //Este parametro es enviado automaticamente por Kendoui int skip = ApiManager.numeroNull(request.getParameter("skip")); Integer filaInicio = skip + 1; Integer filaFin = take + skip; Visitas manager = new Visitas(); jsonArray = manager.getVisitasPorProceso(filaInicio.toString(), filaFin.toString(), tipoVisita, fechaInicio, fechaFin, codigoProceso, estadoVisita, contrato, nit, razonSocial, motivoVisita); //Armamos la respuesta JSON y la enviamos response.setContentType("application/json"); for (Object jsonObject : jsonArray) { response.getWriter().write(jsonObject.toString()); } } catch (Exception e) { } }
From source file:com.nubits.nubot.tasks.SubmitLiquidityinfoTask.java
private void initFiles() { if (SessionManager.sessionInterrupted()) return; //external interruption this.outputFile_orders = Global.sessionLogFolder + "/" + Settings.ORDERS_FILENAME + ".csv"; this.jsonFile_orders = Global.sessionLogFolder + "/" + Settings.ORDERS_FILENAME + ".json"; this.jsonFile_balances = Global.sessionLogFolder + "/" + Settings.BALANCES_FILEAME + ".json"; //create json file if it doesn't already exist LOG.debug("init files"); File jsonF1 = new File(this.jsonFile_orders); if (!jsonF1.exists()) { try {//from w w w .ja va 2 s. c om jsonF1.createNewFile(); LOG.debug("created " + jsonF1); } catch (Exception e) { LOG.error("error creating file " + jsonF1 + " " + e); } JSONObject history = new JSONObject(); JSONArray orders = new JSONArray(); history.put("orders", orders); FilesystemUtils.writeToFile(history.toJSONString(), this.jsonFile_orders, true); } if (SessionManager.sessionInterrupted()) return; //external interruption //create json file if it doesn't already exist File jsonF2 = new File(this.jsonFile_balances); if (!jsonF2.exists()) { try { jsonF2.createNewFile(); LOG.debug("created " + jsonF2); } catch (Exception e) { LOG.error("error creating file " + jsonF1 + " " + e); } JSONObject history = new JSONObject(); JSONArray balances = new JSONArray(); history.put("balances", balances); FilesystemUtils.writeToFile(history.toJSONString(), this.jsonFile_balances, true); } if (SessionManager.sessionInterrupted()) return; //external interruption File of = new File(this.outputFile_orders); if (!of.exists()) { try { of.createNewFile(); LOG.debug("created " + of); } catch (Exception e) { LOG.error("error creating file " + of + " " + e); } } FilesystemUtils.writeToFile("timestamp,activeOrders, sells,buys, digest\n", this.outputFile_orders, false); }
From source file:de.hstsoft.sdeep.NoteManager.java
@SuppressWarnings("unchecked") private void saveNotes() { JSONObject envelope = new JSONObject(); envelope.put("version", VERSION); JSONArray jsonArray = new JSONArray(); for (Note n : notes) { jsonArray.add(n.toJson());/* ww w .java 2 s . c om*/ } envelope.put("notes", jsonArray); try { File file = new File(directory + FILENAME); FileWriter fileWriter = new FileWriter(file); fileWriter.append(envelope.toJSONString()); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } }