List of usage examples for org.json JSONObject toString
public String toString()
From source file:org.eclipse.orion.server.tests.servlets.git.GitRevertTest.java
private static WebRequest getPostGitRevertRequest(String location, String toRevert) throws JSONException, UnsupportedEncodingException { String requestURI = toAbsoluteURI(location); JSONObject body = new JSONObject(); body.put(GitConstants.KEY_REVERT, toRevert); WebRequest request = new PostMethodWebRequest(requestURI, IOUtilities.toInputStream(body.toString()), "UTF-8"); request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1"); setAuthentication(request);//from w ww .j av a2 s. c om return request; }
From source file:Logica.SesionWeb.java
@Override public void mandarMensaje(Mensaje mensaje) { try {//w w w .java 2s .c o m if (sesion.isOpen()) { JSONObject json = new JSONObject(); json.append("envia", mensaje.getEnvia()); json.append("recibe", mensaje.getRecibe()); json.append("mensaje", mensaje.getMensaje()); json.append("fecha", mensaje.getFecha()); json.append("tipo", "MENSAJE"); sesion.getBasicRemote().sendText(json.toString()); } } catch (IOException ex) { Logger.getLogger(SesionWeb.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Logica.SesionWeb.java
@Override public void notificarUsuariosLogeados(HashMap<String, Usuario> usuariosConectados) { try {/* w w w. ja va 2 s . c om*/ if (sesion.isOpen()) { JSONObject objetoJSON = new JSONObject(); JSONArray usuarios = new JSONArray(); for (Map.Entry<String, Usuario> entry : usuariosConectados.entrySet()) { String nick = entry.getKey(); usuarios.put(nick); } objetoJSON.put("usuarios", usuarios); objetoJSON.append("tipo", "CONTACTOS"); sesion.getBasicRemote().sendText(objetoJSON.toString()); } } catch (IOException ex) { Logger.getLogger(SesionWeb.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Logica.SesionWeb.java
@Override public void exitoAlLogear(Usuario usuario) { try {/*from ww w . ja va2 s . co m*/ if (sesion.isOpen()) { sesion.getUserProperties().put("nick", usuario.getNick()); JSONObject objetoJSON = new JSONObject(); objetoJSON.append("tipo", "OK"); objetoJSON.append("token", usuario.getToken()); System.out.println(usuario.toString()); System.out.println(usuario.getToken()); sesion.getBasicRemote().sendText(objetoJSON.toString()); } } catch (IOException ex) { Logger.getLogger(SesionWeb.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Logica.SesionWeb.java
@Override public void notificarError(TipoMensaje tipoMensaje, String mensaje) { try {//from w w w.ja v a2s. c o m JSONObject o = new JSONObject(); o.append("tipo", "" + tipoMensaje); o.append("mensaje", mensaje); sesion.getBasicRemote().sendText(o.toString()); sesion.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "Algo salio muy mal... o no tan mal(como login mal viste..)")); } catch (IOException ex) { Logger.getLogger(ChatEndpoint.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.comcast.oscar.sql.queries.DocsisSqlQuery.java
/** * //from www. j a v a 2 s . com * @param iRowID * @param iParentID * @param aliTlvEncodeHistory * @return JSONObject * @throws JSONException */ private JSONObject recursiveTlvDefinitionBuilder(Integer iRowID, Integer iParentID, ArrayList<Integer> aliTlvEncodeHistory) throws JSONException { Statement parentCheckStatement = null, getRowDefinitionStatement = null; ResultSet resultSetParentCheck = null, resultSetGetRowDefinition = null; aliTlvEncodeHistory.add(getTypeFromRowID(iParentID)); String sqlQuery; JSONObject tlvJsonObj = null; // This query will check for child rows that belong to a parent row sqlQuery = "SELECT " + " ID ," + " TYPE ," + " TLV_NAME," + " PARENT_ID " + "FROM " + " DOCSIS_TLV_DEFINITION " + "WHERE " + " PARENT_ID = '" + iRowID + "'"; try { //Create statement parentCheckStatement = sqlConnection.createStatement(); //Get Result Set of Query resultSetParentCheck = parentCheckStatement.executeQuery(sqlQuery); } catch (SQLException e) { e.printStackTrace(); } /* ****************************************************************************************************** * If resultSet return an empty, this means that the row does not have a child and is not a Major TLV * *****************************************************************************************************/ try { if ((SqlConnection.getRowCount(resultSetParentCheck) == 0) && (iParentID != MAJOR_TLV)) { // This query will check for child rows that belong to a parent row sqlQuery = "SELECT * FROM " + " DOCSIS_TLV_DEFINITION " + " WHERE ID = '" + iRowID + "'"; //Create statement to get Rows from ROW ID's getRowDefinitionStatement = sqlConnection.createStatement(); //Get Result Set resultSetGetRowDefinition = getRowDefinitionStatement.executeQuery(sqlQuery); //Advance to next index in result set, this is needed resultSetGetRowDefinition.next(); /************************************************* * Assemble JSON OBJECT *************************************************/ tlvJsonObj = new JSONObject(); tlvJsonObj.put(Dictionary.TYPE, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_TYPE)); tlvJsonObj.put(Dictionary.TLV_NAME, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_TLV_NAME)); tlvJsonObj.put(Dictionary.LENGTH_MIN, resultSetGetRowDefinition.getInt(Dictionary.DB_TBL_COL_LENGTH_MIN)); tlvJsonObj.put(Dictionary.LENGTH_MAX, resultSetGetRowDefinition.getInt(Dictionary.DB_TBL_COL_LENGTH_MAX)); tlvJsonObj.put(Dictionary.SUPPORTED_VERSIONS, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_SUPPORTED_VERSIONS)); tlvJsonObj.put(Dictionary.DATA_TYPE, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_DATA_TYPE)); tlvJsonObj.put(Dictionary.ARE_SUBTYPES, false); tlvJsonObj.put(Dictionary.BYTE_LENGTH, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_BYTE_LENGTH)); aliTlvEncodeHistory.add(resultSetGetRowDefinition.getInt(Dictionary.DB_TBL_COL_TYPE)); tlvJsonObj.put(Dictionary.PARENT_TYPE_LIST, aliTlvEncodeHistory); if (debug) System.out.println(tlvJsonObj.toString()); } else if (iParentID == MAJOR_TLV) { // This query will check for child rows that belong to a parent row sqlQuery = "SELECT * FROM " + " DOCSIS_TLV_DEFINITION " + " WHERE ID = '" + iRowID + "'"; getRowDefinitionStatement = sqlConnection.createStatement(); resultSetGetRowDefinition = getRowDefinitionStatement.executeQuery(sqlQuery); resultSetGetRowDefinition.next(); /************************************************* * Assemble JSON OBJECT *************************************************/ tlvJsonObj = new JSONObject(); tlvJsonObj.put(Dictionary.TYPE, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_TYPE)); tlvJsonObj.put(Dictionary.TLV_NAME, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_TLV_NAME)); tlvJsonObj.put(Dictionary.LENGTH_MIN, resultSetGetRowDefinition.getInt(Dictionary.DB_TBL_COL_LENGTH_MIN)); tlvJsonObj.put(Dictionary.LENGTH_MAX, resultSetGetRowDefinition.getInt(Dictionary.DB_TBL_COL_LENGTH_MAX)); tlvJsonObj.put(Dictionary.SUPPORTED_VERSIONS, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_SUPPORTED_VERSIONS)); tlvJsonObj.put(Dictionary.DATA_TYPE, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_DATA_TYPE)); tlvJsonObj.put(Dictionary.ARE_SUBTYPES, false); tlvJsonObj.put(Dictionary.BYTE_LENGTH, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_BYTE_LENGTH)); aliTlvEncodeHistory.add(resultSetGetRowDefinition.getInt("TYPE")); tlvJsonObj.put(Dictionary.PARENT_TYPE_LIST, aliTlvEncodeHistory); if (debug) System.out.println(tlvJsonObj.toString()); } if (SqlConnection.getRowCount(resultSetParentCheck) > 0) { // This query will check for child rows that belong to a parent row sqlQuery = "SELECT " + " TYPE , " + " TLV_NAME," + " PARENT_ID" + " FROM " + " DOCSIS_TLV_DEFINITION " + " WHERE ID = '" + iRowID + "'"; try { Integer iParentIdTemp = null; JSONArray tlvJsonArray = new JSONArray(); while (resultSetParentCheck.next()) { iParentIdTemp = resultSetParentCheck.getInt(Dictionary.DB_TBL_COL_PARENT_ID); ArrayList<Integer> aliTlvEncodeHistoryNext = new ArrayList<Integer>(); aliTlvEncodeHistoryNext.addAll(aliTlvEncodeHistory); if (debug) System.out.println("aliTlvEncodeHistoryNext: " + aliTlvEncodeHistoryNext); aliTlvEncodeHistoryNext.remove(aliTlvEncodeHistoryNext.size() - 1); //Keep processing each row using recursion until you get to to the bottom of the tree tlvJsonArray.put( recursiveTlvDefinitionBuilder(resultSetParentCheck.getInt(Dictionary.DB_TBL_COL_ID), iParentIdTemp, aliTlvEncodeHistoryNext)); } //Get Parent Definition tlvJsonObj = getRowDefinitionViaRowId(iParentIdTemp); tlvJsonObj.put(Dictionary.SUBTYPE_ARRAY, tlvJsonArray); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return tlvJsonObj; }
From source file:com.comcast.oscar.sql.queries.DocsisSqlQuery.java
/** * //from ww w. j a v a2s. co m * @param iRowID * @return JSONObject * @throws JSONException */ private JSONObject getRowDefinitionViaRowId(Integer iRowID) throws JSONException { Statement parentCheckStatement = null; ResultSet resultSetParentCheck = null; JSONObject tlvJsonObj = null; // This query will check for child rows that belong to a parent row String sqlQuery = "SELECT * FROM " + " DOCSIS_TLV_DEFINITION " + " WHERE " + " ID = '" + iRowID + "'"; try { parentCheckStatement = sqlConnection.createStatement(); resultSetParentCheck = parentCheckStatement.executeQuery(sqlQuery); resultSetParentCheck.next(); /************************************************* * Assemble JSON OBJECT *************************************************/ tlvJsonObj = new JSONObject(); tlvJsonObj.put(Dictionary.TYPE, resultSetParentCheck.getString(Dictionary.TYPE)); tlvJsonObj.put(Dictionary.TLV_NAME, resultSetParentCheck.getString(Dictionary.DB_TBL_COL_TLV_NAME)); tlvJsonObj.put(Dictionary.LENGTH_MIN, resultSetParentCheck.getInt(Dictionary.DB_TBL_COL_LENGTH_MIN)); tlvJsonObj.put(Dictionary.LENGTH_MAX, resultSetParentCheck.getInt(Dictionary.DB_TBL_COL_LENGTH_MAX)); tlvJsonObj.put(Dictionary.SUPPORTED_VERSIONS, resultSetParentCheck.getString(Dictionary.DB_TBL_COL_SUPPORTED_VERSIONS)); tlvJsonObj.put(Dictionary.DATA_TYPE, resultSetParentCheck.getString(Dictionary.DB_TBL_COL_DATA_TYPE)); tlvJsonObj.put(Dictionary.ARE_SUBTYPES, true); tlvJsonObj.put(Dictionary.BYTE_LENGTH, resultSetParentCheck.getString(Dictionary.DB_TBL_COL_BYTE_LENGTH)); if (debug) System.out.println(tlvJsonObj.toString()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return tlvJsonObj; }
From source file:uk.ac.imperial.presage2.web.SimulationsTreeServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logRequest(req);//from w ww . j a v a 2 s. com // check which node to check from String node = req.getParameter("node"); if (node == null) { resp.setStatus(400); return; } long nodeId; if (node.equalsIgnoreCase("root")) { nodeId = 0; } else { try { nodeId = Long.parseLong(node); } catch (NumberFormatException e) { resp.setStatus(400); return; } } List<PersistentSimulation> sims = new LinkedList<PersistentSimulation>(); for (Long simId : this.sto.getSimulations()) { PersistentSimulation sim = this.sto.getSimulationById(simId); PersistentSimulation parent = sim.getParentSimulation(); if ((nodeId == 0 && parent == null) || (parent != null && nodeId > 0 && parent.getID() == nodeId)) { sims.add(sim); } } // build JSON response try { JSONObject jsonResp = new JSONObject(); JSONArray jsonSims = new JSONArray(); for (PersistentSimulation sim : sims) { jsonSims.put(SimulationServlet.simulationToJSON(sim)); } jsonResp.put("data", jsonSims); jsonResp.put("success", true); resp.setStatus(200); resp.getWriter().write(jsonResp.toString()); } catch (JSONException e) { resp.setStatus(500); } }
From source file:de.decoit.visa.http.ajax.handlers.CreateComponentHandler.java
@Override public void handle(HttpExchange he) throws IOException { log.info(he.getRequestURI().toString()); // Get the URI of the request and extract the query string from it QueryString queryParameters = new QueryString(he.getRequestURI()); // Create StringBuilder for the response String response = null;//from www. j a v a 2 s . c o m // Check if the query parameters are valid for this handler if (this.checkQueryParameters(queryParameters)) { // Check oid scheme Pattern p = Pattern.compile("^new_(.+?)$"); Matcher m = p.matcher(queryParameters.get("oid").get()); if (m.matches()) { // Extract component type String compType = m.group(1); NetworkComponent newNC = null; // Any exception thrown during object creation will cause // failure of the AJAX request try { String name = queryParameters.get("name").get(); Dimension2D dim = new Dimension2D(Integer.parseInt(queryParameters.get("dimX").get()), Integer.parseInt(queryParameters.get("dimY").get())); ComponentGroup cg = TEBackend.TOPOLOGY_STORAGE .getComponentGroupByID(queryParameters.get("group").get()); JSONObject responseJSON = new JSONObject(); // Create the new object according to the component type // extracted above switch (compType) { case NCSwitch.TYPE: newNC = TEBackend.TOPOLOGY_STORAGE.createSwitch(queryParameters.get("ifori").toList(), name, dim, null); newNC.getConfig().setComponentGroup(cg.getName()); ((NCSwitch) newNC).createGroupSwitches(); responseJSON.put("newComponent", ((NCSwitch) newNC).toJSON()); responseJSON.put("switch", true); responseJSON.put("topology", TEBackend.TOPOLOGY_STORAGE.genTopologyJSON()); break; case NCVM.TYPE: newNC = TEBackend.TOPOLOGY_STORAGE.createVM(queryParameters.get("ifori").toList(), name, dim, null); newNC.getConfig().setComponentGroup(cg.getName()); responseJSON.put("newComponent", newNC.toJSON()); responseJSON.put("switch", false); responseJSON.put("topology", TEBackend.TOPOLOGY_STORAGE.genTopologyJSON()); break; default: responseJSON = null; } responseJSON.put("status", AJAXServer.AJAX_SUCCESS); // Set the HTTP response to the identifier string of the new // component response = responseJSON.toString(); } catch (Throwable ex) { TEBackend.logException(ex, log); try { // Synchronize the topology with the RDF model to // resolve // any errors caused by the caught exception TEBackend.RDF_MANAGER.syncTopologyToRDF(); JSONObject rv = new JSONObject(); rv.put("status", AJAXServer.AJAX_ERROR_EXCEPTION); rv.put("type", ex.getClass().getSimpleName()); rv.put("message", ex.getMessage()); rv.put("topology", TEBackend.TOPOLOGY_STORAGE.genTopologyJSON()); response = rv.toString(); } catch (Throwable e) { // Exception during synchronization, the model may have // been // corrupted so the whole backend was cleared JSONObject rv = new JSONObject(); try { rv.put("status", AJAXServer.AJAX_ERROR_EXCEPTION_UNRESOLVED); rv.put("topology", TEBackend.TOPOLOGY_STORAGE.genTopologyJSON()); } catch (JSONException exc) { /* Ignore */ } response = rv.toString(); } } } else { // Received object ID did not match the required scheme JSONObject rv = new JSONObject(); try { // Missing or malformed query string, set response to error // code rv.put("status", AJAXServer.AJAX_ERROR_MISSING_ARGS); } catch (JSONException exc) { /* Ignore */ } response = rv.toString(); } } else { // Missing or malformed query string, set response to error code JSONObject rv = new JSONObject(); try { rv.put("status", AJAXServer.AJAX_ERROR_MISSING_ARGS); } catch (JSONException exc) { /* Ignore */ } response = rv.toString(); } // Send the response sendResponse(he, response); }
From source file:com.karura.framework.utils.JsHelper.java
public static String jsFragmentForAsyncResponse(String receiver, String method, String action, int timeout, Pair... params) throws IllegalArgumentException { JSONObject payload = new JSONObject(); try {// w ww. j a v a 2s. c o m payload.put("receiver", receiver); String method2 = Character.toUpperCase(method.charAt(0)) + method.substring(1); payload.put("method", method2); if (timeout != INVALID_TIMEOUT) { payload.put("timeout", timeout); } if (action != null) { payload.put("action", action); } JSONObject apiPayload = new JSONObject(); for (Pair p : params) { apiPayload.put((String) p.first, p.second); } payload.put("data", apiPayload); } catch (JSONException e) { throw new IllegalArgumentException(); } String stringify = payload.toString(); return stringify; }