List of usage examples for org.json.simple JSONObject containsKey
boolean containsKey(Object key);
From source file:com.nubits.nubot.trading.wrappers.AllCoinWrapper.java
private ApiResponse getBalanceImpl(Currency currency, CurrencyPair pair) { ApiResponse apiResponse = new ApiResponse(); boolean isGet = false; TreeMap<String, String> query_args = new TreeMap<>(); /*Params//from w w w . j ava2s. c o m */ String url = API_AUTH_URL; String method = API_GET_INFO; ApiResponse response = getQuery(url, method, query_args, true, isGet); if (response.isPositive()) { JSONObject httpAnswerJson = (JSONObject) response.getResponseObject(); JSONObject dataJson = (JSONObject) httpAnswerJson.get(TOKEN_DATA); JSONObject availableBal = (JSONObject) dataJson.get(TOKEN_BAL_AVAIL); //check for returned data if (availableBal == null) { //we return the balances as 0 if (currency == null) { //all balances were requested Amount PEGAvail = new Amount(0, pair.getPaymentCurrency()); Amount NBTAvail = new Amount(0, pair.getOrderCurrency()); Amount PEGonOrder = new Amount(0, pair.getPaymentCurrency()); Amount NBTonOrder = new Amount(0, pair.getOrderCurrency()); PairBalance balance = new PairBalance(PEGAvail, NBTAvail, PEGonOrder, NBTonOrder); apiResponse.setResponseObject(balance); } else { Amount total = new Amount(0, currency); apiResponse.setResponseObject(total); } } else { //we have returned data String s; if (currency == null) { //get all balances JSONObject holdBal = (JSONObject) dataJson.get(TOKEN_BAL_HOLD); Amount PEGAvail = new Amount(0, pair.getPaymentCurrency()); Amount NBTAvail = new Amount(0, pair.getOrderCurrency()); Amount PEGonOrder = new Amount(0, pair.getPaymentCurrency()); Amount NBTonOrder = new Amount(0, pair.getOrderCurrency()); if (availableBal.containsKey(pair.getPaymentCurrency().getCode().toUpperCase())) { s = availableBal.get(pair.getPaymentCurrency().getCode().toUpperCase()).toString(); PEGAvail.setQuantity(Double.parseDouble(s)); } if (availableBal.containsKey(pair.getOrderCurrency().getCode().toUpperCase())) { s = availableBal.get(pair.getOrderCurrency().getCode().toUpperCase()).toString(); NBTAvail.setQuantity(Double.parseDouble(s)); } if (holdBal != null && holdBal.containsKey(pair.getPaymentCurrency().getCode().toUpperCase())) { s = holdBal.get(pair.getPaymentCurrency().getCode().toUpperCase()).toString(); PEGonOrder.setQuantity(Double.parseDouble(s)); } if (holdBal != null && holdBal.containsKey((pair.getOrderCurrency().getCode().toUpperCase()))) { s = holdBal.get(pair.getOrderCurrency().getCode().toUpperCase()).toString(); NBTonOrder.setQuantity(Double.parseDouble(s)); } PairBalance balance = new PairBalance(PEGAvail, NBTAvail, PEGonOrder, NBTonOrder); apiResponse.setResponseObject(balance); } else { //specific currency requested Amount total = new Amount(0, currency); if (availableBal.containsKey(currency.getCode().toUpperCase())) { s = availableBal.get(currency.getCode().toUpperCase()).toString(); total.setQuantity(Double.parseDouble(s)); } apiResponse.setResponseObject(total); } } } else { apiResponse = response; } return apiResponse; }
From source file:hw.java
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // ResultSet rs1; // //from w ww . j a v a2 s . c o m // try { MongoCollection<Document> coll = db.getCollection("business"); //MongoCollection<Document> catcollection = db.getCollection("catout"); MongoCollection<Document> rcoll = db.getCollection("review"); //final DBCollection collection = db.getCollection("review"); MongoCollection<Document> ccoll = db.getCollection("checkin"); String from_dropdown = jComboBox3.getSelectedItem().toString(); String to_dropdown = jComboBox6.getSelectedItem().toString(); String from_value = jTextField9.getText(); String to_value = jTextField10.getText(); String check_count_value = jTextField11.getText(); String check_count_dropdown = jComboBox8.getSelectedItem().toString(); String fromdate_value = jTextField1.getText(); String todate_value = jTextField3.getText(); String stars_value = jTextField12.getText(); String votes_value = jTextField13.getText(); String stars_dropdown = jComboBox4.getSelectedItem().toString(); String votes_dropdown = jComboBox12.getSelectedItem().toString(); String select = jComboBox1.getSelectedItem().toString(); List<String> category_value = jList2.getSelectedValuesList(); String poi = jComboBox5.getSelectedItem().toString(); String proximity = jComboBox2.getSelectedItem().toString(); BasicDBObject qryBusiness = new BasicDBObject(); BasicDBObject qryReview = new BasicDBObject(); BasicDBList BusinessList = new BasicDBList(); BasicDBList ReviewList = new BasicDBList(); FindIterable<Document> cursor; FindIterable<Document> cursor1; List<String> catout = new ArrayList<String>(); List<String> proout = new ArrayList<String>(); List<String> checkinout = new ArrayList<String>(); List<String> reviewout = new ArrayList<String>(); List<String> finalout = new ArrayList<String>(); if (category_value.isEmpty())//&& poi == null && proximity == null && from_value == null && fromdate_value == null) { BasicDBObject nu = new BasicDBObject(); FindIterable<Document> fi; fi = coll.find(nu); jTextField8.setText("db.business.find()"); String Columnames[] = { "business_id", "state", "city", "stars" }; DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel(); dtm.setColumnCount(0); dtm.setRowCount(0); int numberOfColumns = Columnames.length; for (int i = 0; i < numberOfColumns; i++) { String name = Columnames[i]; dtm.addColumn(name); } fi.forEach(new Block<Document>() { @Override public void apply(final Document document) { Object rowData[] = new Object[numberOfColumns]; rowData[0] = document.get("business_id"); rowData[1] = document.get("state"); rowData[2] = document.get("city"); rowData[3] = document.get("stars"); dtm.addRow(rowData); rowData = null; } }); jTable1.setRowSelectionAllowed(true); jTable1.setModel(dtm); jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); dtm.fireTableDataChanged(); } else { Object[] l = jList2.getSelectedValues(); //BasicDBList subcat = new BasicDBList(); BasicDBList clist = new BasicDBList(); BasicDBObject qrycategory; if (l.length > 0) { for (int i = 0; i < l.length; i++) { BasicDBObject buinessop = new BasicDBObject("categories", l[i]); clist.add(buinessop); } } qrycategory = new BasicDBObject("$or", clist); // subcatquery = new BasicDBObject("$out","subcat"); // subcat.add(qrycategory); // subcat.add(subcatquery); // System.out.println(subcat); cursor = coll.find(qrycategory); System.out.println(qrycategory); //BasicDBObject category = new BasicDBObject(); cursor.forEach(new Block<Document>() { @Override public void apply(final Document document) { System.out.println(document.get("business_id")); //category.put((String)document.get("business_id"), db); catout.add((String) document.get("business_id")); // System.out.println(document.get("state")); // System.out.println(document.get("city")); // System.out.println(document.get("stars")); // } }); MongoCollection<Document> collecttest = db.getCollection("test"); String[] addresses5 = { "", "4840 E Indian School Rd\\nSte 101\\nPhoenix, AZ 85018", "631 S Main St\\nDe Forest, WI 53532", "5813 Main St\\nMc Farland, WI 53558", "2039 Allen Blvd\\nMiddleton, WI 53562", "6230 University Ave\\nMiddleton, WI 53562" }; String[][] latLong = { { "33.499313000000001", "-111.98375799999999" }, { "43.2408748", "-89.343721700000003" }, { "43.014164000000001", "-89.288567" }, { "43.090642000000003", "-89.485168999999999" }, { "43.0910607", "-89.487486700000005" } }; BasicDBObject queryBusiness = new BasicDBObject(); BasicDBList businessinputlist = new BasicDBList(); String selectedAddress = jComboBox5.getSelectedItem().toString(); String selectedProximity = jComboBox2.getSelectedItem().toString(); Double pro = Double.parseDouble(selectedProximity) / 3963.2; int index = Arrays.asList(addresses5).indexOf(selectedAddress); Double Latitude = Double.parseDouble(latLong[index][0]); Double Longitude = Double.parseDouble(latLong[index][1]); System.out.println("lat" + Latitude); System.out.println("longi" + Longitude); //BasicDBObject lat = new BasicDBObject(Latitude.toString(),Longitude); BasicDBList c1 = new BasicDBList(); BasicDBList cs = new BasicDBList(); cs.add(Latitude); cs.add(Longitude); c1.add(cs); c1.add(pro); BasicDBObject c = new BasicDBObject("$centerSphere", c1); BasicDBObject bq = new BasicDBObject("loc", new BasicDBObject("$geoWithin", c)); FindIterable<Document> fi; fi = collecttest.find(bq); System.out.println(bq); jTextField8.setText("db.test.find(" + bq + ")"); fi.forEach(new Block<Document>() { @Override public void apply(final Document document) { System.out.println(document.get("business_id")); proout.add((String) document.get("business_id")); //System.out.println(document.get("loc")); } }); int checkinempty = 0; if (from_value == null || to_value == null || check_count_value.equals("0")) { checkinempty = 1; List<String> pr = new ArrayList<String>(catout); System.out.println(pr.size()); pr.retainAll(proout); System.out.println(pr.size()); String Columnames[] = { "Business_id", "state", "city", "stars" }; DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel(); dtm.setColumnCount(0); dtm.setRowCount(0); int numberOfColumns = Columnames.length; Object rowData[] = new Object[numberOfColumns]; for (int i = 0; i < numberOfColumns; i++) { String name = Columnames[i]; dtm.addColumn(name); } for (int i = 0; i < pr.size(); i++) { rowData[0] = pr.get(i); BasicDBObject c11 = new BasicDBObject("business_id", pr.get(i)); FindIterable<Document> f1; f1 = coll.find(c11); f1.forEach(new Block<Document>() { @Override public void apply(final Document document) { Object rowData[] = new Object[numberOfColumns]; rowData[0] = document.get("business_id"); rowData[1] = document.get("state"); rowData[2] = document.get("city"); rowData[3] = document.get("stars"); dtm.addRow(rowData); rowData = null; } }); // // // } jTable1.setRowSelectionAllowed(true); jTable1.setModel(dtm); jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); dtm.fireTableDataChanged(); } if (checkinempty != 1) { BasicDBList checkinputlist = new BasicDBList(); // ArrayList<String> list1; list1 = new ArrayList<String>(); list1.add("0"); list1.add("1"); list1.add("2"); list1.add("3"); list1.add("4"); list1.add("5"); list1.add("6"); int from = list1.indexOf(from_dropdown); int to = list1.indexOf(to_dropdown); int count = to - from; int hoursfrom1 = Integer.parseInt(from_value); int hoursto1 = Integer.parseInt(to_value); int count1 = hoursto1 - hoursfrom1; FindIterable<Document> iterable = ccoll.find(); iterable.forEach(new Block<Document>() { @Override public void apply(final Document document) { //System.out.println(document.get("checkin_info")); String s = document.toJson(); s.replace("Document", ""); // System.out.println(s); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(s); JSONObject doc = (JSONObject) obj; //System.out.println(doc.get("checkin_info")); JSONObject cinfo = (JSONObject) doc.get("checkin_info"); if (count >= 0) { long num_checkin = 0; for (int i = from; i <= to; i++) { if (count1 >= 0) { for (int j = hoursfrom1; j <= hoursto1; j++) { //System.out.println(cinfo.get(j+"-"+i)); if (cinfo.containsKey(j + "-" + i)) { num_checkin = num_checkin + (long) cinfo.get(j + "-" + i); // System.out.println(document.get("checkin_info."+j+"-"+i)); } } } } if (num_checkin != 0) { if (jComboBox8.getSelectedItem().equals(">") && num_checkin > Long.parseLong(check_count_value)) { System.out .println(num_checkin + " checkins into " + doc.get("business_id")); checkinout.add((String) document.get("business_id")); } if (jComboBox8.getSelectedItem().equals("<") && num_checkin < Long.parseLong(check_count_value)) { System.out .println(num_checkin + " checkins into " + doc.get("business_id")); checkinout.add((String) document.get("business_id")); } if (jComboBox8.getSelectedItem().equals("=") && num_checkin == Long.parseLong(check_count_value)) { System.out .println(num_checkin + " checkins into " + doc.get("business_id")); checkinout.add((String) document.get("business_id")); } } num_checkin = 0; } } catch (Exception e) { System.out.println(e); } } }); if (fromdate_value != null && todate_value != null) { BasicDBObject fdv = new BasicDBObject("date", new BasicDBObject("$gte", fromdate_value)); ReviewList.add(fdv); BasicDBObject tdv = new BasicDBObject("date", new BasicDBObject("$lte", todate_value)); ReviewList.add(tdv); } if (stars_value != null) { if (stars_dropdown == ">") { BasicDBObject sv = new BasicDBObject("stars", new BasicDBObject("$gt", Integer.parseInt(stars_value))); ReviewList.add(sv); } if (stars_dropdown == "<") { BasicDBObject sv = new BasicDBObject("stars", new BasicDBObject("$lt", Integer.parseInt(stars_value))); ReviewList.add(sv); } if (stars_dropdown == "=") { BasicDBObject sv = new BasicDBObject("stars", Integer.parseInt(stars_value)); ReviewList.add(sv); } } if (votes_value != null) { if (votes_dropdown == ">") { BasicDBObject vv = new BasicDBObject("votes", new BasicDBObject("$gt", Integer.parseInt(votes_value))); //ReviewList.add(vv); } if (votes_dropdown == "<") { BasicDBObject vv = new BasicDBObject("votes", new BasicDBObject("$lt", Integer.parseInt(votes_value))); //ReviewList.add(vv); } if (votes_dropdown == "=") { BasicDBObject vv = new BasicDBObject("votes", Integer.parseInt(votes_value)); //ReviewList.add(vv); } } qryReview = new BasicDBObject("$and", ReviewList); if (qryReview == null) { //jTextField8.setText("db.review.find()"); cursor1 = rcoll.find(); } else { //jTextField8.setText("db.review.find("+qryReview.toString()+")"); cursor1 = rcoll.find(qryReview); } cursor1.forEach(new Block<Document>() { @Override public void apply(final Document document) { System.out.println(document.get("business_id")); reviewout.add((String) document.get("business_id")); } }); if ("AND".equals(jComboBox1.getSelectedItem().toString())) { //jTextField8.setText("db.checkin.find("+"{}"+","+"{business_id"+":1}"+")"); List<String> fin = new ArrayList<String>(catout); System.out.println(fin.size()); fin.retainAll(proout); System.out.println(fin.size()); fin.retainAll(checkinout); System.out.println(fin.size()); fin.retainAll(reviewout); // System.out.println(fin.size()); String Columnames[] = { "Business_id", "state", "city", "stars" }; DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel(); dtm.setColumnCount(0); dtm.setRowCount(0); int numberOfColumns = Columnames.length; Object rowData[] = new Object[numberOfColumns]; for (int i = 0; i < numberOfColumns; i++) { String name = Columnames[i]; dtm.addColumn(name); } for (int i = 0; i < fin.size(); i++) { rowData[0] = fin.get(i); BasicDBObject c11 = new BasicDBObject("business_id", fin.get(i)); FindIterable<Document> f1; f1 = coll.find(c11); f1.forEach(new Block<Document>() { @Override public void apply(final Document document) { Object rowData[] = new Object[numberOfColumns]; rowData[0] = document.get("business_id"); rowData[1] = document.get("state"); rowData[2] = document.get("city"); rowData[3] = document.get("stars"); dtm.addRow(rowData); rowData = null; } }); // // // } jTable1.setRowSelectionAllowed(true); jTable1.setModel(dtm); jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); dtm.fireTableDataChanged(); } if ("OR".equals(jComboBox1.getSelectedItem().toString())) { //MongoCollection<Document> = db.getCollection("business"); //jTextField8.setText("db.checkin.find("+"{}"+","+"{business_id"+":1}"+")"); List<String> fin = new ArrayList<String>(catout); //create a Set with all the elements in a fin.addAll(proout); System.out.println(fin.size()); fin.addAll(checkinout); System.out.println(fin.size()); fin.addAll(reviewout); System.out.println(fin.size()); String Columnames[] = { "Business_id", "state", "city", "stars" }; DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel(); dtm.setColumnCount(0); dtm.setRowCount(0); int numberOfColumns = Columnames.length; //Object rowData[] = new Object[numberOfColumns]; //Object rd1,rd2,rd3; for (int i = 0; i < numberOfColumns; i++) { String name = Columnames[i]; dtm.addColumn(name); } for (int i = 0; i < fin.size(); i++) { Object rowData[] = new Object[numberOfColumns]; rowData[0] = fin.get(i); BasicDBObject c11 = new BasicDBObject("business_id", fin.get(i)); FindIterable<Document> f1; f1 = coll.find(c11); f1.forEach(new Block<Document>() { @Override public void apply(final Document document) { Object rowData[] = new Object[numberOfColumns]; rowData[0] = document.get("business_id"); rowData[1] = document.get("state"); rowData[2] = document.get("city"); rowData[3] = document.get("stars"); dtm.addRow(rowData); rowData = null; } }); } // }); //Object rowData[] = new Object[numberOfColumns]; // // // jTable1.setRowSelectionAllowed(true); jTable1.setModel(dtm); jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); dtm.fireTableDataChanged(); } if (qryBusiness == null) { //jTextField8.setText("db.business.find()"); cursor = coll.find(); } else { //jTextField8.setText("db.business.find("+qryBusiness.toString()+")"); cursor = coll.find(qryBusiness); } // } catch (SQLException ex) { // Logger.getLogger(hw.class.getName()).log(Level.SEVERE, null, ex); // } // // // // } } }
From source file:com.photon.phresco.framework.rest.api.CIService.java
@GET @Path("/lastBuildStatus") @Produces(MediaType.APPLICATION_JSON)/*from w ww. j a v a2 s .com*/ @Consumes(MediaType.APPLICATION_JSON) public Response getLastBuildStatus(@QueryParam(REST_QUERY_NAME) String jobName, @QueryParam(REST_QUERY_CONTINOUSNAME) String continuousName, @QueryParam(REST_QUERY_PROJECTID) String projectId, @QueryParam(REST_QUERY_APPDIR_NAME) String appDir, @QueryParam(REST_QUERY_ROOT_MODULE_NAME) String rootModule, @QueryParam(REST_QUERY_CUSTOMERID) String customerId, @QueryParam(REST_QUERY_TYPE) String ciType, @QueryParam(BAMBOO_PLAN_KEY) String planKey) { ResponseInfo<String> responseData = new ResponseInfo<String>(); ResponseInfo<Boolean> finalOutput = null; CIBuild build = null; if (ciType != null && ciType.equalsIgnoreCase(BAMBOO)) { try { FrameworkConfiguration frameworkConfig = new FrameworkConfiguration(FRAMEWORK_CONFIG); StringBuilder resultUrl = new StringBuilder(); resultUrl.append(frameworkConfig.getBambooHome()).append(BAMBOO_RESULT_PATH).append(planKey) .append("?expand=results.result"); String response = getResponseGetMethod(resultUrl.toString()); JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser.parse(response); if (jsonObject.containsKey("results")) { JSONObject resultsObj = (JSONObject) jsonObject.get("results"); if (Integer.parseInt(resultsObj.get("size").toString()) > 0) { JSONArray results = (JSONArray) resultsObj.get("result"); JSONObject jsonObject1 = (JSONObject) results.get(0); build = getBuildInstanceFromJson(jsonObject1); } } } catch (ParseException e) { finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR810036); return Response.status(Status.OK).entity(finalOutput) .header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } catch (PhrescoException e) { finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR810036); return Response.status(Status.OK).entity(finalOutput) .header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } } else { String module = ""; String splitPath = ""; try { if (projectId == null || projectId.equals("null") || projectId.equals("")) { if (StringUtils.isNotEmpty(rootModule)) { module = appDir; appDir = rootModule; } splitPath = Utility.splitPathConstruction(appDir); if (StringUtils.isNotEmpty(rootModule)) { splitPath = splitPath + File.separator + module; } ProjectInfo projectInfo = FrameworkServiceUtil.getProjectInfo(splitPath); projectId = projectInfo.getId(); } CIManager ciManager = PhrescoFrameworkFactory.getCIManager(); CIJob job = null; List<ApplicationInfo> appInfos = FrameworkUtil.getAppInfos(customerId, projectId); String globalInfo = ""; if (CollectionUtils.isNotEmpty(appInfos)) { globalInfo = appInfos.get(0).getAppDirName(); globalInfo = Utility.splitPathConstruction(globalInfo); } if (StringUtils.isNotEmpty(appDir)) { appDir = splitPath; } List<ProjectDelivery> ciJobInfo = ciManager.getCiJobInfo(appDir, globalInfo, READ); List<CIJob> ciJobs = Utility.getJobs(continuousName, projectId, ciJobInfo); for (CIJob ciJob : ciJobs) { if (ciJob.getJobName().equals(jobName)) { job = ciJob; } } build = ciManager.getStatusInfo(job); } catch (PhrescoException e) { finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR810036); return Response.status(Status.OK).entity(finalOutput) .header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } catch (PhrescoPomException e) { finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR810036); return Response.status(Status.OK).entity(finalOutput) .header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } } finalOutput = responseDataEvaluation(responseData, null, build, RESPONSE_STATUS_SUCCESS, PHR800023); return Response.status(Status.OK).entity(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER) .build(); }
From source file:com.piusvelte.hydra.UnidataConnection.java
@SuppressWarnings("unchecked") @Override//from w w w. ja va 2 s. co m public JSONObject update(String object, String[] columns, String[] values, String selection) { JSONObject response = new JSONObject(); JSONArray errors = new JSONArray(); UniFile uFile = null; try { int[] locs = getDictLocs(object, columns); UniCommand uCommand = mSession.command(); if (selection == null) uCommand.setCommand(String.format(SIMPLE_QUERY_FORMAT, object).toString()); else uCommand.setCommand(String.format(SELECTION_QUERY_FORMAT, object, selection).toString()); UniSelectList uSelect = mSession.selectList(0); uCommand.exec(); uFile = mSession.openFile(object); UniString recordID = null; while ((recordID = uSelect.next()).length() > 0) { UniDynArray record = new UniDynArray(uFile.read(recordID)); for (int c = 0; c < columns.length; c++) { if ((locs[c] > 0) && !("@ID").equals(columns[c])) record.replace(locs[c], values[c]); } uFile.write(recordID, record); } JSONArray rows = new JSONArray(); JSONArray rowData = new JSONArray(); rows.add(rowData); response.put("result", rows); } catch (UniSessionException e) { e.printStackTrace(); errors.add(e.getMessage()); } catch (UniCommandException e) { e.printStackTrace(); errors.add(e.getMessage()); } catch (UniFileException e) { e.printStackTrace(); errors.add(e.getMessage()); } catch (UniSelectListException e) { e.printStackTrace(); errors.add(e.getMessage()); } catch (Exception e) { e.printStackTrace(); errors.add(e.getMessage()); } finally { if (uFile != null) { try { uFile.close(); } catch (UniFileException e) { e.printStackTrace(); } } } response.put("errors", errors); if (!response.containsKey("result")) { JSONArray rows = new JSONArray(); JSONArray rowData = new JSONArray(); rows.add(rowData); response.put("result", rows); } return response; }
From source file:com.photon.phresco.framework.rest.api.CIService.java
/** * @param jobName/*from w w w. j a v a 2 s. c o m*/ * @param continuousName * @param projectId * @param appDir * @return */ @GET @Path("/jobStatus") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response getStatus(@QueryParam(REST_QUERY_NAME) String jobName, @QueryParam(REST_QUERY_CONTINOUSNAME) String continuousName, @QueryParam(REST_QUERY_PROJECTID) String projectId, @QueryParam(REST_QUERY_APPDIR_NAME) String appDir, @QueryParam(REST_QUERY_ROOT_MODULE_NAME) String rootModule, @QueryParam(REST_QUERY_CUSTOMERID) String customerId, @QueryParam(REST_QUERY_TYPE) String ciType, @QueryParam(BAMBOO_PLAN_KEY) String planKey) { ResponseInfo<String> responseData = new ResponseInfo<String>(); ResponseInfo<Boolean> finalOutput = null; String jobStatus = ""; String splitPath = ""; if (ciType != null && ciType.equalsIgnoreCase(BAMBOO)) { try { FrameworkConfiguration frameworkConfig = new FrameworkConfiguration(FRAMEWORK_CONFIG); StringBuilder resultUrl = new StringBuilder(); if (planKey == null) { PhrescoException pe = new PhrescoException("Plan Key is NULL"); return Response.status(Status.OK).entity(pe).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER) .build(); } resultUrl.append(frameworkConfig.getBambooHome()).append(BAMBOO_RESULT_PATH).append(planKey); String response = getResponseGetMethod(resultUrl.toString()); JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser.parse(response); if (jsonObject.containsKey("results")) { JSONObject resultsObj = (JSONObject) jsonObject.get("results"); if (Integer.parseInt(resultsObj.get("size").toString()) > 0) { JSONArray results = (JSONArray) resultsObj.get("result"); JSONObject jsonObject1 = (JSONObject) results.get(0); jobStatus = (jsonObject1.get("state").equals("Failed")) ? "\"red\"" : "\"blue\""; } else { jobStatus = "\"notbuilt\""; } } else { String lifeCycleState = (String) jsonObject.get("lifeCycleState"); String state = (String) jsonObject.get("state"); if (lifeCycleState.equalsIgnoreCase("Finished")) { if (state.equalsIgnoreCase("Failed")) { jobStatus = "\"red\""; } else if (state.equalsIgnoreCase("Successful")) { jobStatus = "\"blue\""; } } else if (lifeCycleState.equalsIgnoreCase("NotBuilt")) { if (state.equalsIgnoreCase("unknown")) { jobStatus = "\"red\""; } } else if (lifeCycleState.equalsIgnoreCase("InProgress")) { jobStatus = "\"red_anime\""; } else if (lifeCycleState.equalsIgnoreCase("Queued")) { jobStatus = "\"Queued\""; } } finalOutput = responseDataEvaluation(responseData, null, jobStatus, RESPONSE_STATUS_SUCCESS, PHR800012); return Response.status(Status.OK).entity(finalOutput) .header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } catch (PhrescoException e) { finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR810018); return Response.status(Status.OK).entity(finalOutput) .header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } catch (ParseException e) { finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR810018); return Response.status(Status.OK).entity(finalOutput) .header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } } else { try { String module = ""; if (projectId == null || projectId.equals("null") || projectId.equals("")) { if (StringUtils.isNotEmpty(rootModule)) { module = appDir; appDir = rootModule; } splitPath = Utility.splitPathConstruction(appDir); if (StringUtils.isNotEmpty(rootModule)) { splitPath = splitPath + File.separator + module; } ProjectInfo projectInfo = FrameworkServiceUtil.getProjectInfo(splitPath); projectId = projectInfo.getId(); } CIManager ciManager = PhrescoFrameworkFactory.getCIManager(); CIJob job = null; List<ApplicationInfo> appInfos = FrameworkUtil.getAppInfos(customerId, projectId); String globalInfo = ""; if (CollectionUtils.isNotEmpty(appInfos)) { globalInfo = appInfos.get(0).getAppDirName(); globalInfo = Utility.splitPathConstruction(globalInfo); } if (StringUtils.isNotEmpty(appDir)) { appDir = splitPath; } List<ProjectDelivery> ciJobInfo = ciManager.getCiJobInfo(appDir, globalInfo, READ); List<CIJob> ciJobs = Utility.getJobs(continuousName, projectId, ciJobInfo); for (CIJob ciJob : ciJobs) { if (ciJob.getJobName().equals(jobName)) { job = ciJob; } } jobStatus = ciManager.getJobStatus(job); } catch (PhrescoException e) { finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR810018); return Response.status(Status.OK).entity(finalOutput) .header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } catch (PhrescoPomException e) { finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR810018); return Response.status(Status.OK).entity(finalOutput) .header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } } finalOutput = responseDataEvaluation(responseData, null, jobStatus, RESPONSE_STATUS_SUCCESS, PHR800012); return Response.status(Status.OK).entity(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER) .build(); }
From source file:eu.seaclouds.platform.discoverer.crawler.CloudTypes.java
private Offering generateIAASOffering(CloudHarmonyService chs, JSONObject locationInformation, JSONObject computeInstanceType) { /* tosca lines into ArrayList */ ArrayList<String> gt = new ArrayList<>(); String providerName = chs.name; /* name not sanitized (used to access SPECint table) */ String providerOriginalName = chs.originalName; String instanceId = (String) computeInstanceType.get("instanceId"); String locationCode = (String) locationInformation.get("providerCode"); /* name, taken as 'cloud service name'_'instance id'_'city where is located' */ String name = Offering.sanitizeName(providerName + "_" + instanceId + "_" + locationCode); Offering offering = new Offering(name); offering.setType("seaclouds.nodes.Compute." + Offering.sanitizeName(providerName)); offering.addProperty("resource_type", "compute"); offering.addProperty("hardwareId", instanceId); offering.addProperty("location", chs.serviceId); offering.addProperty("region", locationCode); /* Performance */ Integer performance = CloudHarmonySPECint.getSPECint(providerOriginalName, instanceId); if (performance != null) { offering.addProperty("performance", performance.toString()); }/* w ww . java 2 s.c o m*/ /* sla */ if (chs.sla != null) { offering.addProperty("availability", this.slaFormat.format(chs.sla / 100.0)); } /* location */ offering.addProperty("country", expandCountryCode((String) (locationInformation.get("country")))); offering.addProperty("city", expandCountryCode((String) (locationInformation.get("city")))); JSONArray pricings = (JSONArray) computeInstanceType.get("pricing"); if (pricings.size() > 0) { JSONObject pricing = ((JSONObject) ((JSONArray) computeInstanceType.get("pricing")).get(0)); Object price = pricing.get("price"); Object currency = pricing.get("currency"); Object priceInterval = pricing.get("priceInterval"); offering.addProperty("cost", price.toString() + " " + currency.toString() + "/" + priceInterval); } /* compute instance type - numbers */ for (String k : this.numbers.keySet()) { if (computeInstanceType.containsKey(k)) { Object vv = computeInstanceType.get(k); offering.addProperty(this.numbers.get(k), vv.toString()); } } /* compute instance type - strings */ if (computeInstanceType != null) { for (String k : this.strings.keySet()) { if (computeInstanceType.containsKey(k)) { String v = (String) (computeInstanceType.get(k)); offering.addProperty(this.strings.get(k), v); } } } return offering; }
From source file:com.piusvelte.hydra.UnidataConnection.java
@SuppressWarnings("unchecked") @Override/*from ww w. ja v a2s. co m*/ public JSONObject query(String object, String[] columns, String selection) { JSONObject response = new JSONObject(); JSONArray errors = new JSONArray(); UniFile uFile = null; try { JSONArray rows = new JSONArray(); UniCommand uCommand = mSession.command(); if (selection == null) uCommand.setCommand(String.format(SIMPLE_QUERY_FORMAT, object).toString()); else uCommand.setCommand(String.format(SELECTION_QUERY_FORMAT, object, selection).toString()); UniSelectList uSelect = mSession.selectList(0); uCommand.exec(); uFile = mSession.openFile(object); UniString recordID = null; while ((recordID = uSelect.next()).length() > 0) { uFile.setRecordID(recordID); // flatten out multi-values int maxSize = 1; ArrayList<String[]> colArr = new ArrayList<String[]>(); for (String column : columns) { String[] mvArr = uFile.readNamedField(column).toString().split(UniTokens.AT_VM, -1); if (mvArr.length > maxSize) maxSize = mvArr.length; colArr.add(mvArr); } for (int row = 0; row < maxSize; row++) { JSONArray rowData = new JSONArray(); for (int col = 0; col < columns.length; col++) { String[] mvArr = colArr.get(col); if (row < mvArr.length) rowData.add(mvArr[row]); else rowData.add(""); } rows.add(rowData); } } response.put("result", rows); } catch (UniSessionException e) { errors.add(e.getMessage()); } catch (UniCommandException e) { errors.add(e.getMessage()); } catch (UniFileException e) { errors.add(e.getMessage()); } catch (UniSelectListException e) { errors.add(e.getMessage()); } finally { if (uFile != null) { try { uFile.close(); } catch (UniFileException e) { errors.add(e.getMessage()); } } } response.put("errors", errors); if (!response.containsKey("result")) { JSONArray rows = new JSONArray(); JSONArray rowData = new JSONArray(); rows.add(rowData); response.put("result", rows); } return response; }
From source file:net.bashtech.geobot.Channel.java
private void loadProperties(String name) { setDefaults();/*from w w w . j a v a 2s . c om*/ parseYoutube = Boolean.valueOf((Boolean) config.get("parseYoutube")); lists = (JSONObject) config.get("lists"); shouldModerate = Boolean.valueOf((Boolean) config.get("shouldModerate")); rollLevel = ((String) config.get("rollLevel")); rollCooldown = ((Long) config.get("rollCooldown")).intValue(); rollDefault = ((Long) config.get("rollDefault")).intValue(); rollTimeout = Boolean.valueOf((Boolean) config.get("rollTimeout")); songRequestStatus = Boolean.valueOf((Boolean) config.get("songRequestStatus")); urbanEnabled = Boolean.valueOf((Boolean) config.get("urbanEnabled")); extraLifeID = ((Long) config.get("extraLifeID")); resubAlerts = Boolean.valueOf((Boolean) config.get("resubAlert")); resubMessage = (String) config.get("resubMessage"); try { subscriberAlerts = Boolean.valueOf((String) config.get("subscriberAlert")); } catch (Exception e) { subscriberAlerts = Boolean.valueOf((Boolean) config.get("subscriberAlert")); config.put("subscriberAlert", subscriberAlerts); } try { subscriberAlerts = Boolean.valueOf((Boolean) config.get("subscriberAlert")); } catch (Exception e) { subscriberAlerts = Boolean.valueOf((String) config.get("subscriberAlert")); config.put("subscriberAlert", subscriberAlerts); } subscriberMessage = (String) config.get("subMessage"); gamerTag = (String) config.get("gamerTag"); // channel = config.getString("channel"); subsRegsMinusLinks = Boolean.valueOf((Boolean) config.get("subsRegsMinusLinks")); updateDelay = ((Long) config.get("updateDelay")).intValue(); punishCount = ((Long) config.get("punishCount")).intValue(); streamAlive = (Boolean) config.get("streamAlive"); sinceWp = ((Long) config.get("sinceWp")); maxviewerDate = (String) config.get("maxviewerDate"); runningMaxViewers = ((Long) config.get("runningMaxViewers")).intValue(); streamNumber = ((Long) config.get("streamCount")).intValue(); streamMax = ((Long) config.get("maxViewersStream")).intValue(); maxViewers = ((Long) config.get("maxViewers")).intValue(); filterCaps = Boolean.valueOf((Boolean) config.get("filterCaps")); filterCapsPercent = ((Long) config.get("filterCapsPercent")).intValue(); filterCapsMinCharacters = ((Long) config.get("filterCapsMinCharacters")).intValue(); filterCapsMinCapitals = ((Long) config.get("filterCapsMinCapitals")).intValue(); filterLinks = Boolean.valueOf((Boolean) config.get("filterLinks")); filterOffensive = Boolean.valueOf((Boolean) config.get("filterOffensive")); filterEmotes = Boolean.valueOf((Boolean) config.get("filterEmotes")); wpOn = Boolean.valueOf((Boolean) config.get("wpTimer")); wpCount = ((Long) config.get("wpCount")).intValue(); bullet = (String) config.get("bullet"); cooldown = ((Long) config.get("cooldown")).intValue(); sincePunish = (Long) config.get("sincePunish"); filterSymbols = Boolean.valueOf((Boolean) config.get("filterSymbols")); filterSymbolsPercent = ((Long) config.get("filterSymbolsPercent")).intValue(); filterSymbolsMin = ((Long) config.get("filterSymbolsMin")).intValue(); filterEmotesMax = ((Long) config.get("filterEmotesMax")).intValue(); filterEmotesSingle = Boolean.valueOf((Boolean) config.get("filterEmotesSingle")); // announceJoinParts = // Boolean.parseBoolean(config.getString("announceJoinParts")); announceJoinParts = false; topic = (String) config.get("topic"); topicTime = ((Long) config.get("topicTime")).intValue(); useTopic = Boolean.valueOf((Boolean) config.get("useTopic")); useFilters = Boolean.valueOf((Boolean) config.get("useFilters")); enableThrow = Boolean.valueOf((Boolean) config.get("enableThrow")); signKicks = Boolean.valueOf((Boolean) config.get("signKicks")); lastfm = (String) config.get("lastfm"); steamID = (String) config.get("steamID"); logChat = Boolean.valueOf((Boolean) config.get("logChat")); mode = ((Long) config.get("mode")).intValue(); filterMaxLength = ((Long) config.get("filterMaxLength")).intValue(); commercialLength = ((Long) config.get("commercialLength")).intValue(); filterColors = Boolean.valueOf((Boolean) config.get("filterColors")); filterMe = Boolean.valueOf((Boolean) config.get("filterMe")); staticChannel = Boolean.valueOf((Boolean) config.get("staticChannel")); clickToTweetFormat = (String) config.get("clickToTweetFormat"); enableWarnings = Boolean.valueOf((Boolean) config.get("enableWarnings")); timeoutDuration = ((Long) config.get("timeoutDuration")).intValue(); prefix = (String) config.get("commandPrefix"); emoteSet = (String) config.get("emoteSet"); subscriberRegulars = Boolean.valueOf((Boolean) config.get("subscriberRegulars")); // timeAliveStart = (Long)config.get("timeAliveStart"); JSONArray jsonignoredUsers = (JSONArray) config.get("ignoredUsers"); for (int i = 0; i < jsonignoredUsers.size(); i++) { ignoredUsers.add((String) jsonignoredUsers.get(i)); } JSONArray quotesArray = (JSONArray) config.get("quotes"); for (int i = 0; i < quotesArray.size(); i++) { try { JSONObject quoteObj = (JSONObject) quotesArray.get(i); String quote = (String) quoteObj.get("quote"); if (!quote.equals("")) { quotes.add(quote); if (quoteObj.containsKey("editor") && quoteObj.get("editor") != null) { quoteAdders.put(quote, (String) quoteObj.get("editor")); } else quoteAdders.put(quote, null); if (quoteObj.containsKey("timestamp") && quoteObj.get("timestamp") != null) quoteTimestamps.put(quote, Long.valueOf((Long) quoteObj.get("timestamp"))); else quoteTimestamps.put(quote, null); } } catch (Exception e) { quotes.add((String) quotesArray.get(i)); } saveQuotes(false); } JSONArray raidWhitelistArray = (JSONArray) config.get("raidWhitelist"); for (int i = 0; i < raidWhitelistArray.size(); i++) { if (!raidWhitelistArray.get(i).equals("")) { raidWhitelist.add((String) raidWhitelistArray.get(i)); } } JSONArray commandsArray = (JSONArray) config.get("commands"); for (int i = 0; i < commandsArray.size(); i++) { JSONObject commandObject = (JSONObject) commandsArray.get(i); commands.put((String) commandObject.get("key"), (String) commandObject.get("value")); if (commandObject.containsKey("restriction")) { commandsRestrictions.put((String) commandObject.get("key"), ((Long) commandObject.get("restriction")).intValue()); } if (commandObject.containsKey("count") && commandObject.get("count") != null) { commandCounts.put((String) commandObject.get("key"), ((Long) commandObject.get("count")).intValue()); } else { commandCounts.put((String) commandObject.get("key"), 0); } if (commandObject.containsKey("editor") && commandObject.get("editor") != null) { commandAdders.put((String) commandObject.get("key"), (String) commandObject.get("editor")); } else { commandAdders.put((String) commandObject.get("key"), null); } } saveCommands(false); JSONArray repeatedCommandsArray = (JSONArray) config.get("repeatedCommands"); for (int i = 0; i < repeatedCommandsArray.size(); i++) { JSONObject repeatedCommandObj = (JSONObject) repeatedCommandsArray.get(i); RepeatCommand rc = new RepeatCommand(channel, ((String) repeatedCommandObj.get("name")).replaceAll("[^a-zA-Z0-9]", ""), ((Long) repeatedCommandObj.get("delay")).intValue(), ((Long) repeatedCommandObj.get("messageDifference")).intValue(), Boolean.valueOf((Boolean) repeatedCommandObj.get("active"))); commandsRepeat.put(((String) repeatedCommandObj.get("name")).replaceAll("[^a-zA-Z0-9]", ""), rc); } JSONArray scheduledCommandsArray = (JSONArray) config.get("scheduledCommands"); for (int i = 0; i < scheduledCommandsArray.size(); i++) { JSONObject scheduledCommandsObj = (JSONObject) scheduledCommandsArray.get(i); ScheduledCommand rc = new ScheduledCommand(channel, ((String) scheduledCommandsObj.get("name")).replaceAll("[^a-zA-Z0-9]", ""), (String) scheduledCommandsObj.get("pattern"), ((Long) scheduledCommandsObj.get("messageDifference")).intValue(), Boolean.valueOf((Boolean) scheduledCommandsObj.get("active"))); commandsSchedule.put(((String) scheduledCommandsObj.get("name")).replaceAll("[^a-zA-Z0-9]", ""), rc); } JSONArray autoReplyArray = (JSONArray) config.get("autoReplies"); for (int i = 0; i < autoReplyArray.size(); i++) { JSONObject autoReplyObj = (JSONObject) autoReplyArray.get(i); autoReplyTrigger.add(Pattern.compile((String) autoReplyObj.get("trigger"), Pattern.CASE_INSENSITIVE)); autoReplyResponse.add((String) autoReplyObj.get("response")); } JSONArray regularsJSONArray = (JSONArray) config.get("regulars"); synchronized (regulars) { for (int i = 0; i < regularsJSONArray.size(); i++) { String reg = ((String) regularsJSONArray.get(i)).toLowerCase(); if (reg != "" && reg != null) regulars.add(reg); } } JSONArray modsArray = (JSONArray) config.get("moderators"); synchronized (moderators) { for (int i = 0; i < modsArray.size(); i++) { moderators.add(((String) modsArray.get(i)).toLowerCase()); } } JSONArray ownersArray = (JSONArray) config.get("owners"); synchronized (owners) { for (int i = 0; i < ownersArray.size(); i++) { owners.add(((String) ownersArray.get(i)).toLowerCase()); } } JSONArray domainsArray = (JSONArray) config.get("permittedDomains"); synchronized (permittedDomains) { for (int i = 0; i < domainsArray.size(); i++) { permittedDomains.add(((String) domainsArray.get(i)).toLowerCase()); } } JSONArray offensiveArray = (JSONArray) config.get("offensiveWords"); synchronized (offensiveWords) { synchronized (offensiveWordsRegex) { for (int i = 0; i < offensiveArray.size(); i++) { String w = (String) offensiveArray.get(i); offensiveWords.add(w); if (w.startsWith("REGEX:")) { String line = w.substring(6); // System.out.println("Adding: " + line); Pattern tempP = Pattern.compile(line); offensiveWordsRegex.add(tempP); } else { String line = "(?i).*" + Pattern.quote(w) + ".*"; // System.out.println("Adding: " + line); Pattern tempP = Pattern.compile(line); offensiveWordsRegex.add(tempP); } } } } saveConfig(true); }
From source file:com.headswilllol.basiclauncher.Launcher.java
public void actionPerformed(ActionEvent e) { // button was pressed if (e.getActionCommand().equals("play")) { // play button was pressed // clear dem buttons this.remove(play); this.remove(force); this.remove(noUpdate); this.remove(quit); File dir = new File(appData(), FOLDER_NAME + File.separator + "resources"); if (!downloadDir.isEmpty()) // -d flag was used dir = new File(downloadDir, FOLDER_NAME + File.separator + "resources"); dir.mkdir();/*from ww w . jav a 2s. co m*/ try { progress = "Downloading JSON file list..."; paintImmediately(0, 0, width, height); Downloader jsonDl = new Downloader(new URL(JSON_LOCATION), dir.getPath() + File.separator + "resources.json", "JSON file list", true); Thread jsonT = new Thread(jsonDl); // download in a separate thread so the GUI will continue to update jsonT.start(); while (jsonT.isAlive()) { } // no need for a progress bar; it's tiny JSONArray files = (JSONArray) ((JSONObject) new JSONParser().parse(new InputStreamReader( new File(dir.getPath(), "resources.json").toURI().toURL().openStream()))).get("resources"); List<String> paths = new ArrayList<String>(); for (Object obj : files) { // iterate the entries in the JSON file JSONObject jFile = (JSONObject) obj; String launch = ((String) jFile.get("launch")); // if true, resource will be used as main binary if (launch != null && launch.equals("true")) main = new File(dir, ((String) jFile.get("localPath")).replace("/", File.separator)); paths.add(((String) jFile.get("localPath")).replace("/", File.separator)); File file = new File(dir, ((String) jFile.get("localPath")).replace("/", File.separator)); boolean reacquire = false; if (!file.exists() || // files doesn't exist (allowReacquire && // allow files to be reacquired (update || // update forced // mismatch between local and remote file !jFile.get("md5").equals(md5(file.getPath()))))) { reacquire = true; if (update) System.out.println( "Update forced, so file " + jFile.get("localPath") + " must be updated"); else if (!file.exists()) System.out.println("Cannot find local copy of file " + jFile.get("localPath")); else System.out.println("MD5 checksum for file " + jFile.get("localPath") + " does not match expected value"); System.out.println("Attempting to reacquire..."); file.delete(); file.getParentFile().mkdirs(); file.createNewFile(); progress = "Downloading " + jFile.get("id"); // update the GUI paintImmediately(0, 0, width, height); Downloader dl = new Downloader(new URL((String) jFile.get("location")), dir + File.separator + ((String) jFile.get("localPath")).replace("/", File.separator), (String) jFile.get("id"), !jFile.containsKey("doNotSpoofUserAgent") || !Boolean.parseBoolean((String) jFile.get("doNotSpoofUserAgent"))); Thread th = new Thread(dl); th.start(); eSize = getFileSize(new URL((String) jFile.get("location"))) / 8; // expected file size speed = 0; // stores the current download speed lastSize = 0; // stores the size of the downloaded file the last time the GUI was updated while (th.isAlive()) { // wait but don't hang the main thread aSize = file.length() / 8; if (lastTime != -1) { // wait so the GUI isn't constantly updating if (System.currentTimeMillis() - lastTime >= SPEED_UPDATE_INTERVAL) { speed = (aSize - lastSize) / ((System.currentTimeMillis() - lastTime) / 1000) * 8; // calculate new speed lastTime = System.currentTimeMillis(); lastSize = aSize; // update the downloaded file's size } } else { speed = 0; // reset the download speed lastTime = System.currentTimeMillis(); // and the last time } paintImmediately(0, 0, width, height); } eSize = -1; aSize = -1; } if (jFile.containsKey("extract")) { // file should be unzipped HashMap<String, JSONObject> elements = new HashMap<String, JSONObject>(); for (Object ex : (JSONArray) jFile.get("extract")) { elements.put((String) ((JSONObject) ex).get("path"), (JSONObject) ex); paths.add(((String) ((JSONObject) ex).get("localPath")).replace("/", File.separator)); File f = new File(dir, ((String) ((JSONObject) ex).get("localPath")).replace("/", File.separator)); if (!f.exists() || // file doesn't exist // file isn't directory and has checksum (!f.isDirectory() && ((JSONObject) ex).get("md5") != null && // mismatch between local and remote file !md5(f.getPath()).equals((((JSONObject) ex).get("md5"))))) reacquire = true; if (((JSONObject) ex).get("id").equals("natives")) // specific to LWJGL launching natives = new File(dir, ((String) ((JSONObject) ex).get("localPath")).replace("/", File.separator)); } if (reacquire) { try { ZipFile zip = new ZipFile(new File(dir, ((String) jFile.get("localPath")).replace("/", File.separator))); @SuppressWarnings("rawtypes") Enumeration en = zip.entries(); List<String> dirs = new ArrayList<String>(); while (en.hasMoreElements()) { // iterate entries in ZIP file ZipEntry entry = (ZipEntry) en.nextElement(); boolean extract = false; // whether the entry should be extracted String parentDir = ""; if (elements.containsKey(entry.getName())) // entry is in list of files to extract extract = true; else for (String d : dirs) if (entry.getName().contains(d)) { extract = true; parentDir = d; } if (extract) { progress = "Extracting " + (elements.containsKey(entry.getName()) ? elements.get(entry.getName()).get("id") : entry.getName() .substring(entry.getName().indexOf(parentDir), entry.getName().length()) .replace("/", File.separator)); // update the GUI paintImmediately(0, 0, width, height); if (entry.isDirectory()) { if (parentDir.equals("")) dirs.add((String) elements.get(entry.getName()).get("localPath")); } else { File path = new File(dir, (parentDir.equals("")) ? ((String) elements.get(entry.getName()).get("localPath")) .replace("/", File.separator) : entry.getName() .substring(entry.getName().indexOf(parentDir), entry.getName().length()) .replace("/", File.separator)); // path to extract to if (path.exists()) path.delete(); unzip(zip, entry, path); // *zziiiip* } } } } catch (Exception ex) { ex.printStackTrace(); createExceptionLog(ex); progress = "Failed to extract files from " + jFile.get("id"); fail = "Errors occurred; see log file for details"; launcher.paintImmediately(0, 0, width, height); } } } } checkFile(dir, dir, paths); } catch (Exception ex) { // can't open resource list ex.printStackTrace(); createExceptionLog(ex); progress = "Failed to read JSON file list"; fail = "Errors occurred; see log file for details"; launcher.paintImmediately(0, 0, width, height); } launch(); } else if (e.getActionCommand().equals("force")) { force.setActionCommand("noForce"); force.setText("Will Force!"); update = true; // reset do not reacquire button noUpdate.setActionCommand("noReacquire"); noUpdate.setText("Do Not Reacquire"); allowReacquire = true; } else if (e.getActionCommand().equals("noForce")) { force.setActionCommand("force"); force.setText("Force Update"); update = false; } else if (e.getActionCommand().equals("noReacquire")) { noUpdate.setActionCommand("yesReacquire"); noUpdate.setText("Will Not Reacquire!"); allowReacquire = false; // reset force update button force.setActionCommand("force"); force.setText("Force Update"); update = false; } else if (e.getActionCommand().equals("yesReacquire")) { noUpdate.setActionCommand("noReacquire"); noUpdate.setText("Do Not Reacquire"); allowReacquire = true; } else if (e.getActionCommand().equals("quit")) { pullThePlug(); } else if (e.getActionCommand().equals("kill")) gameProcess.destroyForcibly(); }
From source file:com.atlauncher.data.Settings.java
public void checkMojangStatus() { JSONParser parser = new JSONParser(); try {/* w w w . j av a 2s . c o m*/ Downloadable download = new Downloadable("http://status.mojang.com/check", false); String response = download.getContents(); if (response == null) { minecraftSessionServerUp = false; minecraftLoginServerUp = false; return; } Object obj = parser.parse(response); JSONArray jsonObject = (JSONArray) obj; Iterator<JSONObject> iterator = jsonObject.iterator(); while (iterator.hasNext()) { JSONObject object = iterator.next(); if (object.containsKey("authserver.mojang.com")) { if (((String) object.get("authserver.mojang.com")).equalsIgnoreCase("green")) { minecraftLoginServerUp = true; } } else if (object.containsKey("session.minecraft.net")) { if (((String) object.get("session.minecraft.net")).equalsIgnoreCase("green")) { minecraftSessionServerUp = true; } } } } catch (ParseException e) { this.logStackTrace(e); minecraftSessionServerUp = false; minecraftLoginServerUp = false; } }