List of usage examples for org.json.simple JSONObject toString
@Override
public String toString()
From source file:control.ParametrizacionServlets.ActualizarUnidadesMedida.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w ww . ja va 2 s. c om*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONObject respError = new JSONObject(); try { //Obtenemos la informacion del form. int codigo = Integer.parseInt(request.getParameter("codigo")); String descripcion = request.getParameter("descripcion"); UnidadesMedida manager = new UnidadesMedida(); respError = manager.actualizar(codigo, descripcion); //Armamos la respuesta JSON y la enviamos response.setContentType("application/json"); response.getWriter().write(respError.toString()); } catch (Exception ex) { //Armamos la respuesta JSON y la enviamos response.setContentType("application/json"); respError.put("error", 0); response.getWriter().write(respError.toString()); } }
From source file:csiro.pidsvc.servlet.controller.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)/*from w w w. j av a 2 s. c om*/ */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String cmd = request.getParameter("cmd"); if (cmd == null || cmd.isEmpty()) return; Manager mgr = null; try { Settings.init(this); mgr = new Manager(request); _logger.info("Processing \"{}\" command.", cmd); if (cmd.equalsIgnoreCase("create_mapping")) mgr.createMapping(request.getInputStream(), false); else if (cmd.equalsIgnoreCase("delete_mapping")) mgr.deleteMapping(request.getParameter("mapping_path")); else if (cmd.equalsIgnoreCase("import")) response.getWriter().write(mgr.importMappings(request)); else if (cmd.equalsIgnoreCase("merge_upload")) { String jsonRet = mgr.mergeMappingUpload(request); response.setStatus(302); response.addHeader("Location", "merge.html?json=" + URLEncoder.encode(jsonRet, "UTF-8").replace("+", "%20")); } else if (cmd.equalsIgnoreCase("merge")) { final String mappingPath = request.getParameter("mapping_path"); final String targetXml = request.getParameter("target_xml"); final String inputData = Stream.readInputStream(request.getInputStream()); final boolean replace = "1".equals(request.getParameter("replace")); JSONObject json = (mappingPath != null && !mappingPath.isEmpty()) ? mgr.mergeMappingByPath(mappingPath, inputData, replace) : mgr.mergeMappingImpl(targetXml, inputData, replace); response.setContentType("text/json"); response.getWriter().write(json.toString()); } else if (cmd.equalsIgnoreCase("bundle_restore")) { // Applies a set of mapping conditions to a mapping path. final String mappingPath = request.getParameter("mapping_path"); final String parent = request.getParameter("parent"); final String type = request.getParameter("type"); final String inputData = Stream.readInputStream(request.getInputStream()); String targetXml = "<mapping xmlns=\"urn:csiro:xmlns:pidsvc:backup:1.0\">" + " <path>" + StringEscapeUtils.escapeXml(mappingPath) + "</path>" + (parent != null && !parent.isEmpty() ? "<parent>" + StringEscapeUtils.escapeXml(parent) + "</parent>" : "") + " <type>" + StringEscapeUtils.escapeXml(type) + "</type>" + "</mapping>"; response.setContentType("text/json"); response.getWriter().write(mgr.mergeMappingImpl(targetXml, inputData, true).toString()); } else if (cmd.equalsIgnoreCase("purge_data_store")) mgr.purgeDataStore(); else if (cmd.equalsIgnoreCase("save_settings")) mgr.saveSettings(request.getParameterMap()); else if (cmd.equalsIgnoreCase("create_lookup")) mgr.createLookup(request.getInputStream()); else if (cmd.equalsIgnoreCase("delete_lookup")) mgr.deleteLookup(request.getParameter("ns")); else if (cmd.equalsIgnoreCase("import_lookup")) response.getWriter().write(mgr.importLookup(request)); else if (cmd.equalsIgnoreCase("create_condition_set")) mgr.createConditionSet(request.getInputStream()); else if (cmd.equalsIgnoreCase("delete_condition_set")) mgr.deleteConditionSet(request.getParameter("name")); else response.setStatus(404); } catch (Exception e) { _logger.error(e); Http.returnErrorCode(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } finally { if (mgr != null) mgr.close(); } }
From source file:com.unilever.audit.services2.Login.java
@GET @Path("MerchandiserData/{email}/{password}") @Produces("application/json") public Object Login(@PathParam("email") String email, @PathParam("password") String password) throws IOException { JSONObject result = new JSONObject(); Map<String, Object> hm = new HashMap<String, Object>(); hm.put("email", email); hm.put("password", password); Merchandisers merchidisers = (Merchandisers) merchandisersFacadeREST .findOneByQuery("Merchandisers.findMerchandiser", hm); if (merchidisers == null) { result.put("status", "fail"); result.put("error", "invalid email and password"); System.out.println("----------------" + result.toString()); return result.toString(); }/* ww w. j av a 2 s. c om*/ return (Object) merchidisers; }
From source file:cn.vlabs.duckling.vwb.service.ddl.DDLServiceImpl.java
@SuppressWarnings("unchecked") @Override// w w w.ja v a 2s. c o m public String createToken(VWBContext context) { if (context.getCurrentUser() != null) { String currentUser = context.getCurrentUser().getName(); Random random = new Random(); JSONObject obj = new JSONObject(); obj.put("email", currentUser); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); obj.put("date", format.format(new Date())); obj.put("random", Integer.valueOf(random.nextInt())); return encryptor.encrypt(obj.toString()); } else { return ""; } }
From source file:com.gendai.modcreatorfx.template.ItemTemplate.java
/** * Set up all the directory used then for generating the java files. * Also get the texture file and the json({@link JSONObject}) file and modify as needed. *//*from ww w . jav a 2 s. c om*/ @SuppressWarnings("unchecked") private void config() { javaDir = new File(Reference.OUTPUT_LOCATION + mod.getName() + "/java/" + mod.getName()); javaDir.mkdirs(); resDir = new File( Reference.OUTPUT_LOCATION + mod.getName() + "/resources/assets/" + mod.getName().toLowerCase()); resDir.mkdirs(); proxyDir = new File(javaDir + "/proxy"); proxyDir.mkdirs(); initDir = new File(javaDir + "/init"); initDir.mkdirs(); itemsDir = new File(javaDir + "/items"); itemsDir.mkdirs(); langDir = new File(resDir.getPath() + "/lang/en_US.lang"); langDir.getParentFile().mkdirs(); modelDir = new File(resDir.getPath() + "/models/item/" + item.getName().toLowerCase() + ".json"); modelDir.getParentFile().mkdirs(); try { langDir.createNewFile(); FileWriter fw = new FileWriter(langDir.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write("item." + item.getName() + ".name=" + item.getName()); bw.close(); //modeldir.createNewFile(); Files.copy( Paths.get(Resource.class.getResource(item.getType().name() + ".json").getPath().substring(3)), Paths.get(modelDir.toString())); JSONParser parser = new JSONParser(); Object obj = parser.parse(new FileReader(modelDir.toString())); JSONObject jsonObject = (JSONObject) obj; JSONObject arr = (JSONObject) jsonObject.get("textures"); arr.put("layer0", mod.getName().toLowerCase() + ":items/" + item.getName().toLowerCase()); FileWriter file = new FileWriter(modelDir.toString()); String rep = jsonObject.toString().replace("\\/", "/"); file.write(rep); file.flush(); file.close(); } catch (IOException | ParseException e1) { e1.printStackTrace(); } res = item.getTexturefile(); Path pathto = Paths.get(resDir.getPath() + "/textures/items/" + item.getName().toLowerCase() + ".png"); pathto.toFile().getParentFile().mkdirs(); try { Files.copy(res.toPath(), pathto); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.ls.zencat.ZenCat.java
protected String handleBuiltInCommand(String cmd, String sender) { String toks[] = cmd.split(" "); String method = toks[0];/*w ww . j a v a 2 s .c o m*/ // JOIN A CHANNEL if (method.equals("join") && toks.length >= 2) { if (toks.length == 3) joinChannel(toks[1], toks[2]); else joinChannel(toks[1]); sendMessage(toks[1], "<" + sender + "> !" + cmd); return "Joining: " + toks[1]; } // PART A CHANNEL if (method.equals("part") && toks.length == 2) { sendMessage(toks[1], "<" + sender + "> !" + cmd); partChannel(toks[1]); return "Leaving: " + toks[1]; } // BROADCAST MSG TO ALL CHANNELS if (method.equals("spam")) { this.catStuffToAll("<" + sender + "> " + cmd.substring(5)); } // LIST CHANNELS THE BOT IS IN if (method.equals("channels")) { String[] c = getChannels(); StringBuffer sb = new StringBuffer("I am in " + c.length + " channels: "); for (int i = 0; i < c.length; ++i) sb.append(c[i] + " "); return sb.toString(); } // ACK A ZENOSS ALERT if (method.equals("ack") && toks.length == 2) { String evid = toks[1]; try { JSONObject json = ja.ackEvent(evid); String resultString = new String(); if (json.toString().indexOf("true") > 0) { resultString = "Successfully ACKed event: " + evid; } else { resultString = "Failed to ACK event: " + evid; } sendNotice(defaultChannel, resultString); } catch (Exception e) { return e.getMessage(); } } // UNACK A ZENOSS ALERT if (method.equals("unack") && toks.length == 2) { String evid = toks[1]; try { JSONObject json = ja.unAckEvent(evid); String resultString = new String(); if (json.toString().indexOf("true") > 0) { resultString = "Successfully un-ACKed event: " + evid; } else { resultString = "Failed to un-ACK event: " + evid; } sendNotice(defaultChannel, resultString); } catch (Exception e) { return e.getMessage(); } } // CLOSE AN EVENT if (method.equals("close") && toks.length == 2) { String evid = toks[1]; try { JSONObject json = ja.closeEvent(evid); sendNotice(defaultChannel, json.toString()); } catch (Exception e) { return e.getMessage(); } } // SHOW ALL EVENTS if (method.equals("events")) { sendMessage(defaultChannel, "ALL CURRENT ZENOSS EVENTS:"); sendMessage(defaultChannel, "severity | eventID | device: summary (state)"); try { JSONObject json = ja.getEvents(); // Loop through the array Long numEvents = (Long) json.get("totalCount"); if (numEvents > 0) { JSONArray events = (JSONArray) json.get("events"); for (int i = 0; i < numEvents; i++) { JSONObject event = (JSONObject) events.get(i); String summary = event.get("summary").toString(); String evid = event.get("id").toString(); JSONObject device = (JSONObject) event.get("device"); String deviceString = device.get("text").toString(); String severity = event.get("severity").toString(); String eventState = event.get("eventState").toString(); String eventSummary = severity + " | " + evid + " | " + deviceString + ": " + summary + " (" + eventState + ")"; sendMessage(defaultChannel, eventSummary); } } } catch (Exception e) { return e.getMessage(); } } if (method.equals("help")) { sendMessage(defaultChannel, "MEOW MEOW MEOW MEOW"); String helpText = new String(); helpText = "I am the zencat. I send messages to IRC from Zenoss. You can also interact with Zenoss through me. To see all events, type !events. To acknowledge an event, type !ack [eventID]. To set an event back to new, type !unAck [eventID]. To close an event, type !close [eventID]."; sendMessage(defaultChannel, helpText); } // EXIT() if (method.equals("exit")) System.exit(0); return ""; }
From source file:com.fota.Link.sdpApi.java
public static String getCtnInfo(String ncn) throws JDOMException { String resultStr = ""; String logData = ""; try {/*w w w .ja va 2 s. co m*/ String cpId = PropUtil.getPropValue("sdp3g.id"); String cpPw = PropUtil.getPropValue("sdp3g.pw"); String authorization = cpId + ":" + cpPw; logData = "\r\n---------- Get Ctn Req Info start ----------\r\n"; logData += " getCtnRequestInfo - authorization : " + authorization; byte[] encoded = Base64.encodeBase64(authorization.getBytes()); authorization = new String(encoded); String contractType = "0"; String contractNum = ncn.substring(0, 9); String customerId = ncn.substring(10, ncn.length() - 1); JSONObject reqJObj = new JSONObject(); reqJObj.put("transactionid", ""); reqJObj.put("sequenceno", ""); reqJObj.put("userid", ""); reqJObj.put("screenid", ""); reqJObj.put("CONTRACT_NUM", contractNum); reqJObj.put("CUSTOMER_ID", customerId); reqJObj.put("CONTRACT_TYPE", contractType); authorization = "Basic " + authorization; String endPointUrl = PropUtil.getPropValue("sdp.oif555.url"); logData += "\r\n getCtnRequestInfo - endPointUrl : " + endPointUrl; logData += "\r\n getCtnRequestInfo - authorization(encode) : " + authorization; logData += "\r\n getCtnRequestInfo - Content-type : application/json"; logData += "\r\n getCtnRequestInfo - RequestMethod : POST"; logData += "\r\n getCtnRequestInfo - json : " + reqJObj.toString(); logData += "\r\n---------- Get Ctn Req Info end ----------"; logger.info(logData); // connection URL url = new URL(endPointUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", authorization); connection.setRequestProperty("Content-type", "application/json"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); // output DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(reqJObj.toJSONString()); wr.flush(); wr.close(); // input BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine = ""; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONParser jsonParser = new JSONParser(); JSONObject respJsonObject = (JSONObject) jsonParser.parse(response.toString()); // String respTransactionId = (String) respJsonObject.get("transactionid"); // String respSequenceNo = (String) respJsonObject.get("sequenceno"); // String respReturnCode = (String) respJsonObject.get("returncode"); // String respReturnDescription = (String) respJsonObject.get("returndescription"); // String respErrorCode = (String) respJsonObject.get("errorcode"); // String respErrorDescription = (String) respJsonObject.get("errordescription"); String respCtn = (String) respJsonObject.get("ctn"); // String respSubStatus = (String) respJsonObject.get("sub_status"); // String respSubStatusDate = (String) respJsonObject.get("sub_status_date"); resultStr = respCtn; //resultStr = resValue; // resultStr = java.net.URLDecoder.decode(resultStr, "euc-kr"); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return resultStr; }
From source file:io.personium.test.jersey.cell.ctl.RoleUpdateTest.java
/** * ?????????./*from w w w. jav a 2 s. c o m*/ * @param boxname */ @SuppressWarnings("unchecked") private void createRole(String boxname) { JSONObject body = new JSONObject(); body.put("Name", testRoleName); body.put("_Box.Name", boxname); TResponse response = Http.request("role-create.txt") .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", cellName) .with("body", body.toString()) .returns() .statusCode(HttpStatus.SC_CREATED); // ??? String location = UrlUtils.cellCtlWithoutSingleQuote("testcell1", "Role", "Name='" + testRoleName + "',_Box.Name='" + boxname + "'"); ODataCommon.checkCommonResponseHeader(response, location); // ??? Map<String, Object> additional = new HashMap<String, Object>(); additional.put("Name", testRoleName); additional.put("_Box.Name", boxname); ODataCommon.checkResponseBody(response.bodyAsJson(), location, ROLE_TYPE, additional); }
From source file:control.ProcesoVertimientosServlets.RegistrarProcesoSeco.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// ww w. ja va 2 s .com * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int codigoProceso = Integer.parseInt(request.getParameter("codigoProceso")); Integer laboratorioProcesoSeco = Integer.parseInt(request.getParameter("laboratorioProcesoSeco")); Integer consultorProcesoSeco = ApiManager.ponerNull(request.getParameter("consultorProcesoSeco")); String fechaEntregaProcesoSeco = request.getParameter("fechaEntregaProcesoSeco"); String fechaRadicacionProcesoSeco = request.getParameter("fechaRadicacionProcesoSeco"); String observacionesProcesoSeco = request.getParameter("observacionesProcesoSeco"); /*Campo de devolucion*/ String fechaEntDevolProcesoSeco = request.getParameter("fechaEntDevolProcesoSeco"); String fechaDevolProcesoSeco = request.getParameter("fechaDevolProcesoSeco"); String observacionDevolProsesoSeco = request.getParameter("observacionDevolProsesoSeco"); Integer tipoDevolProcesoSeco = ApiManager.ponerNull(request.getParameter("tipoDevolProcesoSeco")); JSONObject resultado = new JSONObject(); InformeProcesoSeco manager = new InformeProcesoSeco(); resultado = manager.registrar(codigoProceso, laboratorioProcesoSeco, consultorProcesoSeco, fechaEntregaProcesoSeco, fechaRadicacionProcesoSeco, fechaEntDevolProcesoSeco, fechaDevolProcesoSeco, observacionDevolProsesoSeco, tipoDevolProcesoSeco, observacionesProcesoSeco); //Armamos la respuesta JSON y la enviamos response.setContentType("application/json"); response.getWriter().write(resultado.toString()); }
From source file:io.personium.test.jersey.cell.ctl.AccountRoleLinkListTest.java
/** * ?????????./*w ww .j a v a 2 s.c om*/ * @param roleName * @param boxname * @return ? */ @SuppressWarnings("unchecked") private TResponse createRole(String roleName, String boxname) { JSONObject body = new JSONObject(); body.put("Name", roleName); body.put("_Box.Name", boxname); return Http.request("role-create.txt") .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", cellName) .with("body", body.toString()) .returns() .debug(); }