List of usage examples for org.json.simple JSONValue parseWithException
public static Object parseWithException(String s) throws ParseException
From source file:com.grokkingandroid.sampleapp.samples.gcm.ccs.server.CcsClient.java
/** * Connects to GCM Cloud Connection Server using the supplied credentials. * @throws XMPPException/*from ww w. j a va 2 s. c o m*/ */ public void connect() throws XMPPException { config = new ConnectionConfiguration(GCM_SERVER, GCM_PORT); config.setSecurityMode(SecurityMode.enabled); config.setReconnectionAllowed(true); config.setRosterLoadedAtLogin(false); config.setSendPresence(false); config.setSocketFactory(SSLSocketFactory.getDefault()); // NOTE: Set to true to launch a window with information about packets sent and received config.setDebuggerEnabled(mDebuggable); // -Dsmack.debugEnabled=true XMPPConnection.DEBUG_ENABLED = true; connection = new XMPPConnection(config); connection.connect(); connection.addConnectionListener(new ConnectionListener() { @Override public void reconnectionSuccessful() { logger.info("Reconnecting.."); } @Override public void reconnectionFailed(Exception e) { logger.log(Level.INFO, "Reconnection failed.. ", e); } @Override public void reconnectingIn(int seconds) { logger.log(Level.INFO, "Reconnecting in %d secs", seconds); } @Override public void connectionClosedOnError(Exception e) { logger.log(Level.INFO, "Connection closed on error."); } @Override public void connectionClosed() { logger.info("Connection closed."); } }); // Handle incoming packets connection.addPacketListener(new PacketListener() { @Override public void processPacket(Packet packet) { logger.log(Level.INFO, "Received []: " + packet.toXML()); Message incomingMessage = (Message) packet; GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage.getExtension(GCM_NAMESPACE); String json = gcmPacket.getJson(); logger.log(Level.INFO, "json []: " + json); try { @SuppressWarnings("unchecked") Map<String, Object> jsonMap = (Map<String, Object>) JSONValue.parseWithException(json); handleMessage(jsonMap); } catch (ParseException e) { logger.log(Level.SEVERE, "Error parsing JSON " + json, e); } catch (Exception e) { logger.log(Level.SEVERE, "Couldn't send echo.", e); } } }, new PacketTypeFilter(Message.class)); // Log all outgoing packets connection.addPacketInterceptor(new PacketInterceptor() { @Override public void interceptPacket(Packet packet) { logger.log(Level.INFO, "Sent: {0}", packet.toXML()); } }, new PacketTypeFilter(Message.class)); connection.login(mProjectId + "@gcm.googleapis.com", mApiKey); logger.log(Level.INFO, "logged in: " + mProjectId); }
From source file:com.nick.bpit.CcsClient.java
/** * Connects to GCM Cloud Connection Server using the supplied credentials. * * @throws XMPPException/*from w ww . j av a 2 s. co m*/ */ public void connect() throws XMPPException { config = new ConnectionConfiguration(GCM_SERVER, GCM_PORT); config.setSecurityMode(SecurityMode.enabled); config.setReconnectionAllowed(true); config.setRosterLoadedAtLogin(false); config.setSendPresence(false); config.setSocketFactory(SSLSocketFactory.getDefault()); // NOTE: Set to true to launch a window with information about packets sent and received config.setDebuggerEnabled(mDebuggable); // -Dsmack.debugEnabled=true XMPPConnection.DEBUG_ENABLED = true; connection = new XMPPConnection(config); connection.connect(); connection.addConnectionListener(new ConnectionListener() { @Override public void reconnectionSuccessful() { logger.info("Reconnecting.."); } @Override public void reconnectionFailed(Exception e) { logger.log(Level.INFO, "Reconnection failed.. ", e); } @Override public void reconnectingIn(int seconds) { logger.log(Level.INFO, "Reconnecting in %d secs", seconds); } @Override public void connectionClosedOnError(Exception e) { logger.log(Level.INFO, "Connection closed on error."); } @Override public void connectionClosed() { logger.info("Connection closed."); } }); // Handle incoming packets connection.addPacketListener(new PacketListener() { @Override public void processPacket(Packet packet) { logger.log(Level.INFO, "Received: " + packet.toXML()); Message incomingMessage = (Message) packet; GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage.getExtension(GCM_NAMESPACE); String json = gcmPacket.getJson(); try { @SuppressWarnings("unchecked") Map<String, Object> jsonMap = (Map<String, Object>) JSONValue.parseWithException(json); handleMessage(jsonMap); } catch (ParseException e) { logger.log(Level.SEVERE, "Error parsing JSON " + json, e); } catch (Exception e) { logger.log(Level.SEVERE, "Couldn't send echo.", e); } } }, new PacketTypeFilter(Message.class)); // Log all outgoing packets connection.addPacketInterceptor(new PacketInterceptor() { @Override public void interceptPacket(Packet packet) { logger.log(Level.INFO, "Sent: {0}", packet.toXML()); } }, new PacketTypeFilter(Message.class)); connection.login(mProjectId + "@gcm.googleapis.com", mApiKey); logger.log(Level.INFO, "logged in: " + mProjectId); }
From source file:eu.edisonproject.training.wsd.Wikidata.java
private List<String> getNumProperty(String id, String prop) throws MalformedURLException, IOException, ParseException { URL url = new URL(PAGE + "?action=wbgetclaims&format=json&props=&property=" + prop + "&entity=" + id); Logger.getLogger(Wikidata.class.getName()).log(Level.FINE, url.toString()); String jsonString = IOUtils.toString(url); JSONObject jsonObj = (JSONObject) JSONValue.parseWithException(jsonString); JSONObject claims = (JSONObject) jsonObj.get("claims"); JSONArray Jprop = (JSONArray) claims.get(prop); List<String> ids = new ArrayList<>(); if (Jprop != null) { for (Object obj : Jprop) { JSONObject jobj = (JSONObject) obj; JSONObject mainsnak = (JSONObject) jobj.get("mainsnak"); // System.err.println(mainsnak); JSONObject datavalue = (JSONObject) mainsnak.get("datavalue"); // System.err.println(datavalue); if (datavalue != null) { JSONObject value = (JSONObject) datavalue.get("value"); // System.err.println(value); java.lang.Long numericID = (java.lang.Long) value.get("numeric-id"); // System.err.println(id + " -> Q" + numericID); ids.add("Q" + numericID); }//from w w w . ja va 2 s . c om } } return ids; }
From source file:eu.edisonproject.training.wsd.BabelNet.java
private Pair<Term, Double> babelNetDisambiguation(String language, String lemma, String sentence) throws IOException, ParseException, Exception { if (lemma == null || lemma.length() < 1) { return null; }/* w w w . j a v a 2 s . c o m*/ String query = lemma + " " + sentence.replaceAll("_", " "); query = URLEncoder.encode(query, "UTF-8"); String genreJson = getFromDisambiguateDB(sentence); if (genreJson != null && genreJson.equals("NON-EXISTING")) { return null; } if (genreJson == null) { URL url = new URL( "http://babelfy.io/v1/disambiguate?text=" + query + "&lang=" + language + "&key=" + key); LOGGER.log(Level.FINE, url.toString()); genreJson = IOUtils.toString(url); handleKeyLimitException(genreJson); if (!genreJson.isEmpty() || genreJson.length() < 1) { putInDisambiguateDB(sentence, genreJson); } else { putInDisambiguateDB(sentence, "NON-EXISTING"); } } Object obj = JSONValue.parseWithException(genreJson); // Term term = null; if (obj instanceof JSONArray) { JSONArray ja = (JSONArray) obj; for (Object o : ja) { JSONObject jo = (JSONObject) o; String id = (String) jo.get("babelSynsetID"); Double score = (Double) jo.get("score"); Double globalScore = (Double) jo.get("globalScore"); Double coherenceScore = (Double) jo.get("coherenceScore"); double someScore = (score + globalScore + coherenceScore) / 3.0; String synet = getBabelnetSynset(id, language); String url = "http://babelnet.org/synset?word=" + URLEncoder.encode(id, "UTF-8"); Term t = TermFactory.create(synet, language, lemma, null, url); if (t != null) { List<Term> h = getHypernyms(language, t); if (h != null) { List<CharSequence> broader = new ArrayList<>(); for (Term hyper : h) { broader.add(hyper.getUid()); } t.setBuids(broader); } return new Pair<>(t, someScore); } } } return null; }
From source file:com.cms.view.ExportContractFromTaxCode.java
public void getCompany(String taxCode) { String url = "https://thongtindoanhnghiep.co/api/company/" + taxCode; try {/*from w ww . j av a2s. c o m*/ List<ConditionBean> lstCon = new ArrayList<>(); lstCon.add(new ConditionBean("taxCode", taxCode, ConditionBean.Operator.NAME_EQUAL, ConditionBean.Type.STRING)); List<CustomerDTO> customers = WSCustomer.getListCustomerByCondition(lstCon, 0, 1, "asc", "taxCode"); if (!DataUtil.isListNullOrEmpty(customers)) { customer = customers.get(0); } else { customer = new CustomerDTO(); } String genreJson = IOUtils.toString(new URL(url), "UTF-8"); JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson); String maSoThue = DataUtil.getStringNullOrZero((String) genreJsonObject.get("MaSoThue")); if (taxCode.equals(customer.getTaxCode()) || taxCode.equals(maSoThue)) { if (DataUtil.isStringNullOrEmpty(customer.getName())) { String name = DataUtil.getStringNullOrZero((String) genreJsonObject.get("Title")); txtName.setValue(name.toUpperCase()); } else { txtName.setValue(customer.getName().toUpperCase()); } // Lay cac thong tin lay duoc tu website if (DataUtil.isStringNullOrEmpty(customer.getOfficeAddress())) { String diachiCongty = DataUtil .getStringNullOrZero((String) genreJsonObject.get("DiaChiCongTy")); txtOfficeAddress.setValue(diachiCongty); } else { txtOfficeAddress.setValue(customer.getOfficeAddress()); } if (DataUtil.isStringNullOrEmpty(customer.getRepresentativeName())) { String chusohuu = DataUtil.getStringNullOrZero((String) genreJsonObject.get("ChuSoHuu")); txtTenNguoiDaidien.setValue(chusohuu); } else { txtTenNguoiDaidien.setValue(customer.getRepresentativeName()); } if (DataUtil.isStringNullOrEmpty(customer.getTelNumber())) { String dienthoaiTruso = DataUtil .getStringNullOrZero((String) genreJsonObject.get("NoiDangKyQuanLy_DienThoai")); txtTelNumber.setValue(dienthoaiTruso); } else { txtTelNumber.setValue(customer.getTelNumber()); } if (DataUtil.isStringNullOrEmpty(customer.getTaxDepartment())) { String coquanthue = DataUtil .getStringNullOrZero((String) genreJsonObject.get("NoiDangKyQuanLy_CoQuanTitle")); txtTaxDepartment.setValue(coquanthue); } else { String coquanthue = DataUtil .getStringNullOrZero((String) genreJsonObject.get("NoiDangKyQuanLy_CoQuanTitle")); txtTaxDepartment.setValue(coquanthue); } if (DataUtil.isStringNullOrEmpty(customer.getDeployAddress())) { String diachiCoquan = DataUtil .getStringNullOrZero((String) genreJsonObject.get("DiaChiNhanThongBaoThue")); txtDeployAddress.setValue(diachiCoquan); } else { txtDeployAddress.setValue(customer.getDeployAddress()); } if (!DataUtil.isStringNullOrEmpty(customer.getEmail())) { txtEmail.setValue(customer.getEmail()); } if (!DataUtil.isStringNullOrEmpty(customer.getRepresentativeId())) { txtCMND.setValue(customer.getRepresentativeId()); } if (!DataUtil.isStringNullOrEmpty(customer.getFax())) { txtFax.setValue(customer.getFax()); } String maMSTTinh = String.valueOf(genreJsonObject.get("TinhThanhID")); if (!DataUtil.isStringNullOrEmpty(maMSTTinh)) { TaxAuthorityDTO tinh = mapMaTinhIDToTaxAuthority.get(maMSTTinh); if (tinh != null) { txtTaxDepartment.setValue(tinh.getTenCqt()); customer.setTaxAuthority(tinh.getMaCqt()); } } } else { CommonUtils.showNotFountData(); txtTaxCode.focus(); } } catch (IOException | ParseException e) { e.printStackTrace(); } }
From source file:at.ac.tuwien.dsg.quelle.cloudDescriptionParsers.impl.AmazonCloudJSONDescriptionParser.java
private void addReservedCostOptions(String schemeName, String pricingSchemeURL, CloudProvider cloudProvider, Map<String, CloudOfferedService> units, Map<String, List<ElasticityCapability.Dependency>> costDependencies) throws MalformedURLException, IOException, ParseException { {/*from ww w . ja v a 2 s . com*/ URL url = new URL(pricingSchemeURL); BufferedReader reader = new BufferedReader( new InputStreamReader(url.openConnection().getInputStream())); String json = ""; String line = ""; while ((line = reader.readLine()) != null) { json += line; } //remove newline json = json.replace("\\n", ""); json = json.replace(" ", ""); //for some URLs, the JSON is not json, it does not contain {"name, instead is {name if (!json.contains("{\"")) { json = json.replace("{", "{\""); json = json.replace(":", "\":"); json = json.replace(",", ",\""); //fix overreplace from above json = json.replace("\"{", "{"); json = json.replace("\"\"", "\""); } //remove "callback" json = json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1); // System.out.println(json); // System.exit(1); JSONObject obj = (JSONObject) JSONValue.parseWithException(json); //get regions JSONArray regions = (JSONArray) ((JSONObject) obj.get("config")).get("regions"); for (int i = 0; i < regions.size(); i++) { JSONObject region = (JSONObject) regions.get(i); if (region.get("region").toString().equals("us-east")) { //types separate GeneralPurpose, and ComputeOptimized, etc JSONArray instanceTypes = (JSONArray) region.get("instanceTypes"); for (int instanceIndex = 0; instanceIndex < instanceTypes.size(); instanceIndex++) { JSONObject instance = (JSONObject) instanceTypes.get(instanceIndex); //sizes separate m1.small, etc // sizes:[{valueColumns:[{name:"yrTerm1",prices:{USD:"110"}},{name:"yrTerm1Hourly",rate:"perhr",prices:{USD:"0.064"}},{name:"yrTerm3",prices:{USD:"172"}},{name:"yrTerm3Hourly",rate:"perhr",prices:{USD:"0.05"}}],size:"m3.medium" JSONArray sizes = (JSONArray) instance.get("sizes"); for (int sizeIndex = 0; sizeIndex < sizes.size(); sizeIndex++) { JSONObject size = (JSONObject) sizes.get(sizeIndex); String sizeName = size.get("size").toString(); if (units.containsKey(sizeName)) { CostFunction _1YearReservedCost = new CostFunction( "1Year" + schemeName + "Cost_" + sizeName); CostFunction _3YearReservedCost = new CostFunction( "3Year" + schemeName + "Cost_" + sizeName); List<ElasticityCapability.Dependency> costElasticityTargets = null; if (costDependencies.containsKey(sizeName)) { costElasticityTargets = costDependencies.get(sizeName); } else { costElasticityTargets = new ArrayList<>(); costDependencies.put(sizeName, costElasticityTargets); } costElasticityTargets.add(new ElasticityCapability.Dependency(_1YearReservedCost, ElasticityCapability.Type.OPTIONAL_ASSOCIATION) .withVolatility(new Volatility(365 * 24, 1))); //365 days in 1 year, times 24 hours costElasticityTargets.add(new ElasticityCapability.Dependency(_3YearReservedCost, ElasticityCapability.Type.OPTIONAL_ASSOCIATION) .withVolatility(new Volatility(3 * 365 * 24, 1))); //365 days in 1 year, times 24 hours // ServiceUnit unit = units.get(sizeName); JSONArray prices = (JSONArray) size.get("valueColumns"); for (int priceIndex = 0; priceIndex < prices.size(); priceIndex++) { JSONObject price = (JSONObject) prices.get(priceIndex); String priceName = price.get("name").toString(); // ServiceUnit _1YearReservationScheme = new ServiceUnit("Management", "ReservationScheme", "1YearLightUtilization"); // cloudProvider.addCloudOfferedService(_1YearReservationScheme); // // Resource r = new Resource("ReservationPeriod"); // r.addProperty(new Metric("Reservation", "duration"), new MetricValue("1 year")); String priceValue = ((JSONObject) price.get("prices")).get("USD").toString(); try { Double convertedPriceValue = Double.parseDouble(priceValue); switch (priceName) { case "yrTerm1": { CostElement upfrontCost = new CostElement("UpfrontCost", new Metric("OneTimePay", "value", Metric.MetricType.COST), CostElement.Type.PERIODIC); upfrontCost.addBillingInterval(new MetricValue(1), convertedPriceValue); _1YearReservedCost.addCostElement(upfrontCost); } break; case "yrTerm1Hourly": { CostElement hourlyCost = new CostElement("vmCost", new Metric("instance", "#", Metric.MetricType.COST), CostElement.Type.PERIODIC) .withBillingCycle(CostElement.BillingCycle.HOUR); hourlyCost.addBillingInterval(new MetricValue(1), convertedPriceValue); _1YearReservedCost.addCostElement(hourlyCost); } break; case "yrTerm3": { CostElement upfrontCost = new CostElement("UpfrontCost", new Metric("OneTimePay", "value", Metric.MetricType.COST), CostElement.Type.PERIODIC); upfrontCost.addBillingInterval(new MetricValue(1), convertedPriceValue); _3YearReservedCost.addCostElement(upfrontCost); } break; case "yrTerm3Hourly": { CostElement hourlyCost = new CostElement("vmCost", new Metric("instance", "#", Metric.MetricType.COST), CostElement.Type.PERIODIC) .withBillingCycle(CostElement.BillingCycle.HOUR); hourlyCost.addBillingInterval(new MetricValue(1), convertedPriceValue); _3YearReservedCost.addCostElement(hourlyCost); } break; } } catch (java.lang.NumberFormatException exception) { log.error(exception.getMessage(), exception); } } } } } } } } }
From source file:at.ac.tuwien.dsg.quelle.cloudDescriptionParsers.impl.AmazonCloudJSONDescriptionParser.java
private void addOndemandCostOptions(String pricingSchemeURL, CloudProvider cloudProvider, Map<String, CloudOfferedService> units, Map<String, List<ElasticityCapability.Dependency>> costDependencies) throws MalformedURLException, IOException, ParseException { {//from w w w . j ava 2 s. c om URL url = new URL(pricingSchemeURL); BufferedReader reader = new BufferedReader( new InputStreamReader(url.openConnection().getInputStream())); String json = ""; String line = ""; while ((line = reader.readLine()) != null) { json += line; } //remove newline json = json.replace("\\n", ""); json = json.replace(" ", ""); //for some URLs, the JSON is not json, it does not contain {"name, instead is {name if (!json.contains("{\"")) { json = json.replace("{", "{\""); json = json.replace(":", "\":"); json = json.replace(",", ",\""); //fix overreplace from above json = json.replace("\"{", "{"); json = json.replace("\"\"", "\""); } //remove "callback" json = json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1); // System.out.println(json); // System.exit(1); JSONObject obj = (JSONObject) JSONValue.parseWithException(json); //get regions JSONArray regions = (JSONArray) ((JSONObject) obj.get("config")).get("regions"); for (int i = 0; i < regions.size(); i++) { JSONObject region = (JSONObject) regions.get(i); if (region.get("region").toString().equals("us-east")) { //types separate GeneralPurpose, and ComputeOptimized, etc JSONArray instanceTypes = (JSONArray) region.get("instanceTypes"); for (int instanceIndex = 0; instanceIndex < instanceTypes.size(); instanceIndex++) { JSONObject instance = (JSONObject) instanceTypes.get(instanceIndex); //sizes separate m1.small, etc // sizes:[{valueColumns:[{name:"yrTerm1",prices:{USD:"110"}},{name:"yrTerm1Hourly",rate:"perhr",prices:{USD:"0.064"}},{name:"yrTerm3",prices:{USD:"172"}},{name:"yrTerm3Hourly",rate:"perhr",prices:{USD:"0.05"}}],size:"m3.medium" JSONArray sizes = (JSONArray) instance.get("sizes"); for (int sizeIndex = 0; sizeIndex < sizes.size(); sizeIndex++) { JSONObject size = (JSONObject) sizes.get(sizeIndex); String sizeName = size.get("size").toString(); if (units.containsKey(sizeName)) { CloudOfferedService unit = units.get(sizeName); JSONArray prices = (JSONArray) size.get("valueColumns"); for (int priceIndex = 0; priceIndex < prices.size(); priceIndex++) { JSONObject price = (JSONObject) prices.get(priceIndex); // ServiceUnit _1YearReservationScheme = new ServiceUnit("Management", "ReservationScheme", "1YearLightUtilization"); // cloudProvider.addCloudOfferedService(_1YearReservationScheme); //curently i need diff CostFunctionNames CostFunction onDemand = new CostFunction("OndemandCost_" + sizeName); List<ElasticityCapability.Dependency> costElasticityTargets = null; if (costDependencies.containsKey(sizeName)) { costElasticityTargets = costDependencies.get(sizeName); } else { costElasticityTargets = new ArrayList<>(); costDependencies.put(sizeName, costElasticityTargets); } costElasticityTargets.add(new ElasticityCapability.Dependency(onDemand, ElasticityCapability.Type.OPTIONAL_ASSOCIATION) .withVolatility(new Volatility(1, 1))); //365 days in 1 year, times 24 hours String priceValue = ((JSONObject) price.get("prices")).get("USD").toString(); CostElement hourlyCost = new CostElement("vmCost", new Metric("instance", "#", Metric.MetricType.COST), CostElement.Type.PERIODIC) .withBillingCycle(CostElement.BillingCycle.HOUR); hourlyCost.addBillingInterval(new MetricValue(1), Double.parseDouble(priceValue)); onDemand.addCostElement(hourlyCost); } } } } } } } }
From source file:i5.las2peer.services.mobsos.SurveyService.java
/** * TODO: write documentation//from w w w. ja va 2s. c o m * * @param id * @param content * @return */ @POST @Consumes(MediaType.APPLICATION_JSON) @Path("surveys/{id}/questionnaire") @Summary("Set questionnaire for given survey.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Survey questionnaire set."), @ApiResponse(code = 400, message = "Invalid JSON for setting survey questionnaire."), @ApiResponse(code = 404, message = "Survey or questionnaire to be set does not exist.") }) public HttpResponse setSurveyQuestionnaire(@PathParam("id") int id, @ContentParam String content) { if (getActiveAgent().getId() == getActiveNode().getAnonymous().getId()) { HttpResponse noauth = new HttpResponse("Please authenticate to set questionnaire for survey!"); noauth.setStatus(401); } String onAction = "setting questionnaire for survey " + id; try { Connection conn = null; PreparedStatement stmt = null; ResultSet rset = null; try { int exown; exown = checkExistenceOwnership(id, 0); // check if survey exists; if not, return 404. if (exown == -1) { HttpResponse result = new HttpResponse("Survey " + id + " does not exist."); result.setStatus(404); return result; } // if survey exists, check if active agent is owner. if not, return 401. else if (exown == 0) { HttpResponse result = new HttpResponse("Survey " + id + " may only be managed by its owner."); result.setStatus(401); return result; } // if survey exists and active agent is owner, proceed. JSONObject o; // parse and validate content. If invalid, return 400 (bad request) try { o = (JSONObject) JSONValue.parseWithException(content); } catch (ParseException e) { HttpResponse result = new HttpResponse(e.getMessage()); result.setStatus(400); return result; } if (!(o.size() == 1 && o.keySet().contains("qid"))) { HttpResponse result = new HttpResponse( "Invalid JSON for setting questionnaire! Must only contain one field qid!"); result.setStatus(400); return result; } // now check if questionnaire really exists int qid = Integer.parseInt(o.get("qid") + ""); HttpResponse qresp = getQuestionnaire(qid); if (qresp.getStatus() != 200) { return qresp; } // if questionnaire exists, check if questionnaire form is defined already // if no form is defined, yet, return a not found. HttpResponse qformresp = downloadQuestionnaireForm(qid); if (qformresp.getStatus() == 404) { return qformresp; } // TODO: at this point we need to check, if users already submitted responses. What to do in this case to avoid data loss? // Responses should under no circumstances be deleted! Idea: respond with a forbidden error that asks user to first clear all // responses before changing questionnaire. Requires DELETE support in resource surveys/{id}/responses. int responses = countResponses(id); if (responses > 0) { String msg = "Forbidden to change questionnaire, because end-user responses exist! " + "To resolve this problem, first make sure to export existing survey response data. " + "Then delete existing responses data with a DELETE to resource surveys/" + id + "/responses." + "Then try again to change questionnaire."; HttpResponse forb = new HttpResponse(msg); forb.setStatus(403); return forb; } // if no responses are available, continue and change questionnaire conn = dataSource.getConnection(); stmt = conn.prepareStatement("update " + jdbcSchema + ".survey set qid=? where id =?"); stmt.setInt(1, qid); stmt.setInt(2, id); stmt.executeUpdate(); HttpResponse result = new HttpResponse("Questionnaire for survey " + id + " set successfully."); result.setStatus(200); return result; } catch (SQLException | UnsupportedOperationException e) { return internalError(onAction); } finally { try { if (rset != null) rset.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } try { if (stmt != null) stmt.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } try { if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } } } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } }
From source file:i5.las2peer.services.mobsos.SurveyService.java
@POST @Consumes(MediaType.APPLICATION_JSON)// w w w. j ava 2 s . c o m @Path("surveys/{id}/responses") @Summary("submit response data to given survey.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Survey response submitted successfully."), @ApiResponse(code = 400, message = "Survey response invalid -or- questionnaire form invalid. Cause: ..."), @ApiResponse(code = 404, message = "Survey does not exist -or- No questionnaire defined for survey."), @ApiResponse(code = 400, message = "Survey response already submitted."), }) public HttpResponse submitSurveyResponseJSON(@PathParam("id") int id, @ContentParam String answerJSON) { Date now = new Date(); String onAction = "submitting response to survey " + id; try { // retrieve survey by id; HttpResponse rs = getSurvey(id); if (rs.getStatus() != 200) { return rs; } JSONObject s = (JSONObject) JSONValue.parse(rs.getResult()); // check if survey expired/not started SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(TimeZone.getTimeZone("GMT")); Date start = df.parse((String) s.get("start")); Date end = df.parse((String) s.get("end")); if (now.getTime() > end.getTime()) { HttpResponse resp = new HttpResponse("Cannot submit response. Survey expired."); resp.setStatus(403); return resp; } else if (now.getTime() < start.getTime()) { HttpResponse resp = new HttpResponse("Cannot submit response. Survey has not begun, yet."); resp.setStatus(403); return resp; } // check for questionnaire form int qid = Integer.parseInt(s.get("qid") + ""); if (qid == -1) { HttpResponse result = new HttpResponse("No questionnaire defined for survey " + id + "!"); result.setStatus(404); return result; } // retrieve questionnaire form for survey to do answer validation HttpResponse r = downloadQuestionnaireForm(qid); if (200 != r.getStatus()) { // if questionnaire form does not exist, pass on response containing error status return r; } Document form; JSONObject answer; // parse form to XML document incl. validation try { form = validateQuestionnaireData(r.getResult()); } catch (SAXException e) { HttpResponse result = new HttpResponse("Questionnaire form is invalid! Cause: " + e.getMessage()); result.setStatus(400); return result; } try { //System.out.println(answerJSON); answer = (JSONObject) JSONValue.parseWithException(answerJSON); } catch (ParseException e) { HttpResponse result = new HttpResponse( "Survey response is not valid JSON! Cause: " + e.getMessage()); result.setStatus(400); return result; } JSONObject answerFieldTable; // validate if answer matches form. try { answerFieldTable = validateResponse(form, answer); } catch (IllegalArgumentException e) { HttpResponse result = new HttpResponse("Survey response is invalid! Cause: " + e.getMessage()); result.setStatus(400); return result; } // after all validation finally persist survey response in database int surveyId = id; String sub = (String) getActiveUserInfo().get("sub"); if (getActiveAgent().getId() == getActiveNode().getAnonymous().getId()) { sub += now.getTime(); } Connection conn = null; PreparedStatement stmt = null; ResultSet rset = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement( "insert into " + jdbcSchema + ".response(uid,sid,qkey,qval,time) values (?,?,?,?,?)"); Iterator<String> it = answerFieldTable.keySet().iterator(); while (it.hasNext()) { String qkey = it.next(); String qval = "" + answerFieldTable.get(qkey); stmt.setString(1, sub); stmt.setInt(2, surveyId); stmt.setString(3, qkey); stmt.setString(4, qval); stmt.setTimestamp(5, new Timestamp(now.getTime())); stmt.addBatch(); } stmt.executeBatch(); HttpResponse result = new HttpResponse("Response to survey " + id + " submitted successfully."); result.setStatus(200); return result; } catch (SQLException | UnsupportedOperationException e) { if (0 <= e.getMessage().indexOf("Duplicate")) { HttpResponse result = new HttpResponse("Survey response already submitted!"); result.setStatus(409); return result; } else { e.printStackTrace(); return internalError(onAction); } } finally { try { if (rset != null) rset.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } try { if (stmt != null) stmt.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } try { if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } } } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } }
From source file:i5.las2peer.services.mobsos.SurveyService.java
@PUT @Path("feedback/{client_id}") @Consumes(MediaType.APPLICATION_JSON)/* w ww . ja v a 2 s .co m*/ @Summary("Submit feedback for a given client as numeric rating and comment.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Client feedback submission complete."), @ApiResponse(code = 400, message = "Client feedback data invalid"), //@ApiResponse(code = 401, message = "Client feedback submission requires authentication."), @ApiResponse(code = 404, message = "Client does not exist.") }) public HttpResponse sumbitFeedback(@PathParam(value = "client_id") String cid, @ContentParam String data) { UserAgent me = (UserAgent) getActiveAgent(); JSONObject mej = (JSONObject) JSONValue.parse(me.getUserData().toString()); JSONObject fb; try { fb = (JSONObject) JSONValue.parseWithException(data); } catch (ParseException e) { HttpResponse result = new HttpResponse("Feedback data required in JSON format!"); result.setStatus(400); return result; } if (fb.get("rating") == null && fb.get("comment") == null) { HttpResponse result = new HttpResponse("Feedback data must include rating or comment!"); result.setStatus(400); return result; } Integer rating = null; String comment = null; if (fb.get("rating") != null) { try { rating = Integer.parseInt(fb.get("rating").toString()); } catch (NumberFormatException e) { HttpResponse result = new HttpResponse("Feedback rating must be number (0 <= x <= 5)!"); result.setStatus(400); return result; } if (rating > 5 || rating < 0) { HttpResponse result = new HttpResponse("Feedback rating must be number (0 <= x <= 5)!"); result.setStatus(400); return result; } } if (fb.get("comment") != null) { comment = fb.get("comment").toString(); } System.out.println("Feedback received from " + mej.get("sub")); System.out.println(" - Rating: " + rating); System.out.println(" - Comment: " + comment); HttpResponse result = new HttpResponse("Client feedback submission complete"); result.setStatus(200); return result; }