List of usage examples for org.json JSONObject put
public JSONObject put(String key, Object value) throws JSONException
From source file:com.lukasz.chat.Pusher.java
private void sendSubscribeMessage(PusherChannel channel) { if (!isConnected()) return;/*from w w w.j a v a 2 s . co m*/ try { String eventName = PUSHER_EVENT_SUBSCRIBE; JSONObject eventData = new JSONObject(); eventData.put("channel", channel.getName()); if (channel.isPrivate()) { String authInfo = authenticate(channel.getName()); eventData.put("auth", authInfo); } sendEvent(eventName, eventData, null); Log.d(LOG_TAG, "subscribed to channel " + channel.getName()); } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.lukasz.chat.Pusher.java
private void sendUnsubscribeMessage(PusherChannel channel) { if (!isConnected()) return;//from w w w.j a v a2 s . co m try { String eventName = PUSHER_EVENT_UNSUBSCRIBE; JSONObject eventData = new JSONObject(); eventData.put("channel", channel.getName()); sendEvent(eventName, eventData, null); Log.d(LOG_TAG, "unsubscribed from channel " + channel.getName()); } catch (JSONException e) { e.printStackTrace(); } }
From source file:edu.lafayette.metadb.web.authentication.CheckSession.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *//*from w ww.ja va 2s .c om*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out = response.getWriter(); JSONObject output = new JSONObject(); try { HttpSession session = request.getSession(false); if (session != null && checkUser(session)) { String name = (String) session.getAttribute(Global.SESSION_USERNAME); User user = UserManDAO.getUserData(name); long last_login = ((Long) session.getAttribute(Global.SESSION_LOGIN_TIME)).longValue(); Date date = new Date(last_login + 5 * 3600 * 1000); output.put("username", name); output.put("admin", user.getType().equals(Global.USER_ADMIN)); output.put("local", user.getAuthType().equals("Local")); output.put("last_login", date.toString()); output.put("success", true); output.put("parser_running", MetaDbHelper.getParserStatus()); output.put("record_count", MetaDbHelper.getItemCount()); output.put("log_types", Global.eventTypes); String[] last_page = UserManDAO.getLastProj(name).split(";"); if (last_page.length > 1) { output.put("last_proj", last_page[0]); output.put("last_item", last_page[1]); } } else { output.put("success", false); output.put("message", "Your session has expired"); } out.print(output); } catch (Exception e) { MetaDbHelper.logEvent(e); } response.setContentType("application/x-json"); out.flush(); }
From source file:com.intel.iotkitlib.LibModules.AdvancedDataEnquiry.java
private String createBodyForAdvancedDataInquiry() throws JSONException { JSONObject dataInquiryJson = new JSONObject(); if (this.msgType == null) { dataInquiryJson.put("msgType", "advancedDataInquiryRequest"); } else {/*from w ww. jav a 2s.c o m*/ dataInquiryJson.put("msgType", this.msgType); } if (this.gatewayIds != null) { JSONArray gatewayArray = new JSONArray(); for (String gatewayId : this.gatewayIds) { gatewayArray.put(gatewayId); } dataInquiryJson.put("gatewayIds", gatewayArray); } if (this.deviceIds != null) { JSONArray deviceIdArray = new JSONArray(); for (String deviceId : this.deviceIds) { deviceIdArray.put(deviceId); } dataInquiryJson.put("deviceIds", deviceIdArray); } if (this.componentIds != null) { JSONArray componentIdArray = new JSONArray(); for (String componentId : this.componentIds) { componentIdArray.put(componentId); } dataInquiryJson.put("componentIds", componentIdArray); } dataInquiryJson.put("startTimestamp", this.startTimestamp); dataInquiryJson.put("endTimestamp", this.endTimestamp); /*dataInquiryJson.put("from", this.startTimestamp); dataInquiryJson.put("to", this.endTimestamp);*/ //returnedMeasureAttributes if (this.returnedMeasureAttributes != null) { JSONArray returnedMeasureAttributesArray = new JSONArray(); for (String attribute : this.returnedMeasureAttributes) { returnedMeasureAttributesArray.put(attribute); } dataInquiryJson.put("returnedMeasureAttributes", returnedMeasureAttributesArray); } if (this.showMeasureLocation) { dataInquiryJson.put("showMeasureLocation", this.showMeasureLocation); } if (this.componentRowLimit > 0) { dataInquiryJson.put("componentRowLimit", this.componentRowLimit); } //sort if (this.sort != null) { JSONArray sortArray = new JSONArray(); for (NameValuePair nameValuePair : this.sort) { JSONObject nameValueJson = new JSONObject(); nameValueJson.put(nameValuePair.getName(), nameValuePair.getValue()); sortArray.put(nameValueJson); } dataInquiryJson.put("sort", sortArray); } if (this.countOnly) { dataInquiryJson.put("countOnly", this.countOnly); } if (this.devCompAttributeFilter != null) { JSONObject devCompAttributeJson = new JSONObject(); for (AttributeFilter attributeFilter : this.devCompAttributeFilter.filterData) { JSONArray filterValuesArray = new JSONArray(); for (String filterValue : attributeFilter.filterValues) { filterValuesArray.put(filterValue); } devCompAttributeJson.put(attributeFilter.filterName, filterValuesArray); } dataInquiryJson.put("devCompAttributeFilter", devCompAttributeJson); } if (this.measurementAttributeFilter != null) { JSONObject measurementAttributeJson = new JSONObject(); for (AttributeFilter attributeFilter : this.measurementAttributeFilter.filterData) { JSONArray filterValuesArray = new JSONArray(); for (String filterValue : attributeFilter.filterValues) { filterValuesArray.put(filterValue); } measurementAttributeJson.put(attributeFilter.filterName, filterValuesArray); } dataInquiryJson.put("measurementAttributeFilter", measurementAttributeJson); } if (this.valueFilter != null) { JSONObject valueFilterJson = new JSONObject(); JSONArray filterValuesArray = new JSONArray(); for (String filterValue : this.valueFilter.filterValues) { filterValuesArray.put(filterValue); } valueFilterJson.put(this.valueFilter.filterName, filterValuesArray); dataInquiryJson.put("valueFilter", valueFilterJson); } return dataInquiryJson.toString(); }
From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java
/** * Create an error object based on the passed in errorCode * @param errorCode the error/*from w ww .j a va 2s.c o m*/ * @return JSONObject containing the error */ private static JSONObject createFileTransferError(int errorCode, String source, String target, String body, Integer httpStatus) { JSONObject error = null; try { error = new JSONObject(); error.put("code", errorCode); error.put("source", source); error.put("target", target); if (body != null) { error.put("body", body); } if (httpStatus != null) { error.put("http_status", httpStatus); } } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); } return error; }
From source file:com.cloudstudio.BarcodeScanner.java
/** * Called when the barcode scanner intent completes. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). *///from ww w . j a v a 2s. c om @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { JSONObject obj = new JSONObject(); try { obj.put(TEXT, intent.getStringExtra("SCAN_RESULT")); obj.put(FORMAT, intent.getStringExtra("SCAN_RESULT_FORMAT")); obj.put(CANCELLED, false); } catch (JSONException e) { Log.d(LOG_TAG, "This should never happen"); } //this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback); this.callbackContext.success(obj); } else if (resultCode == Activity.RESULT_CANCELED) { JSONObject obj = new JSONObject(); try { obj.put(TEXT, ""); obj.put(FORMAT, ""); obj.put(CANCELLED, true); } catch (JSONException e) { Log.d(LOG_TAG, "This should never happen"); } //this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback); this.callbackContext.success(obj); } else { //this.error(new PluginResult(PluginResult.Status.ERROR), this.callback); this.callbackContext.error("Unexpected error"); } } }
From source file:org.eclipse.orion.internal.server.servlets.project.ProjectDecorator.java
public void addAtributesFor(HttpServletRequest request, URI resource, JSONObject representation) { if (!"/file".equals(request.getServletPath())) //$NON-NLS-1$ return;/* ww w . j a v a2 s. c o m*/ String pathInfo = request.getPathInfo(); Path path = new Path(pathInfo); if (path.segmentCount() < 2) { return; } try { ProjectInfo project = OrionConfiguration.getMetaStore().readProject(path.segment(0), path.segment(1)); Project projectData = Project.fromProjectInfo(project); if (projectData.exists()) { JSONObject projectJson = new JSONObject(); //TODO decide what project information should be included in decorator projectJson.put(ProtocolConstants.KEY_LOCATION, URIUtil .append(URIUtil.append(resource.resolve("/project/"), path.segment(0)), path.segment(1)) .toString()); representation.put(ProtocolConstants.KEY_PROJECT_INFO, projectJson); } } catch (Exception e) { LogHelper.log(e); } }
From source file:com.liferay.mobile.android.v7.layoutrevision.LayoutRevisionService.java
public JSONObject addLayoutRevision(long userId, long layoutSetBranchId, long layoutBranchId, long parentLayoutRevisionId, boolean head, long plid, long portletPreferencesPlid, boolean privateLayout, String name, String title, String description, String keywords, String robots, String typeSettings, boolean iconImage, long iconImageId, String themeId, String colorSchemeId, String css, JSONObjectWrapper serviceContext) throws Exception { JSONObject _command = new JSONObject(); try {/*from w ww. j a v a2s . c om*/ JSONObject _params = new JSONObject(); _params.put("userId", userId); _params.put("layoutSetBranchId", layoutSetBranchId); _params.put("layoutBranchId", layoutBranchId); _params.put("parentLayoutRevisionId", parentLayoutRevisionId); _params.put("head", head); _params.put("plid", plid); _params.put("portletPreferencesPlid", portletPreferencesPlid); _params.put("privateLayout", privateLayout); _params.put("name", checkNull(name)); _params.put("title", checkNull(title)); _params.put("description", checkNull(description)); _params.put("keywords", checkNull(keywords)); _params.put("robots", checkNull(robots)); _params.put("typeSettings", checkNull(typeSettings)); _params.put("iconImage", iconImage); _params.put("iconImageId", iconImageId); _params.put("themeId", checkNull(themeId)); _params.put("colorSchemeId", checkNull(colorSchemeId)); _params.put("css", checkNull(css)); mangleWrapper(_params, "serviceContext", "com.liferay.portal.kernel.service.ServiceContext", serviceContext); _command.put("/layoutrevision/add-layout-revision", _params); } catch (JSONException _je) { throw new Exception(_je); } JSONArray _result = session.invoke(_command); if (_result == null) { return null; } return _result.getJSONObject(0); }
From source file:org.projectbuendia.client.models.Order.java
public JSONObject toJson() throws JSONException { JSONObject json = new JSONObject(); json.put("patient_uuid", patientUuid); json.put("instructions", instructions); json.put("start_millis", start.getMillis()); // Use `JSONObject.NULL` instead of `null` so that the value is actually set. json.put("stop_millis", stop == null ? JSONObject.NULL : stop.getMillis()); return json;//from w ww. j a va 2 s.com }
From source file:cc.redpen.server.api.RedPenConfigurationResource.java
@Path("/redpens") @GET//from w ww .j av a 2s .co m @Produces(MediaType.APPLICATION_JSON) @WinkAPIDescriber.Description("Return the configuration for available redpens matching the supplied language (default is any language)") public Response getRedPens(@QueryParam("lang") @DefaultValue("") String lang) throws RedPenException { JSONObject response = new JSONObject(); // add the known document formats try { response.put("version", RedPen.VERSION); response.put("documentParsers", DocumentParser.PARSER_MAP.keySet()); // add matching configurations Map<String, RedPen> redpens = getRedPenService().getRedPens(); final JSONObject redpensJSON = new JSONObject(); response.put("redpens", redpensJSON); redpens.forEach((configurationName, redPen) -> { if ((lang == null) || lang.isEmpty() || redPen.getConfiguration().getLang().contains(lang)) { try { // add specific configuration items JSONObject config = new JSONObject(); config.put("lang", redPen.getConfiguration().getLang()); config.put("variant", redPen.getConfiguration().getVariant()); config.put("tokenizer", redPen.getConfiguration().getTokenizer().getClass().getName()); // add the names of the validators JSONObject validatorConfigs = new JSONObject(); for (Validator validator : redPen.getValidators()) { JSONObject validatorJSON = new JSONObject(); String name = validator.getClass().getSimpleName().endsWith("Validator") ? validator.getClass().getSimpleName().substring(0, validator.getClass().getSimpleName().length() - 9) : validator.getClass().getSimpleName(); validatorJSON.put("languages", validator.getSupportedLanguages()); validatorJSON.put("properties", validator.getConfigAttributes()); validatorConfigs.put(name, validatorJSON); } config.put("validators", validatorConfigs); // add the symbol table JSONObject symbolConfigs = new JSONObject(); for (SymbolType symbolType : redPen.getConfiguration().getSymbolTable().getNames()) { JSONObject symbolJSON = new JSONObject(); Symbol symbol = redPen.getConfiguration().getSymbolTable().getSymbol(symbolType); symbolJSON.put("value", String.valueOf(symbol.getValue())); symbolJSON.put("invalid_chars", String.valueOf(symbol.getInvalidChars())); symbolJSON.put("after_space", symbol.isNeedAfterSpace()); symbolJSON.put("before_space", symbol.isNeedBeforeSpace()); symbolConfigs.put(symbolType.toString(), symbolJSON); } config.put("symbols", symbolConfigs); redpensJSON.put(configurationName, config); } catch (Exception e) { LOG.error("Exception when rendering RedPen to JSON for configuration " + configurationName, e); } } }); } catch (Exception e) { LOG.error("Exception when rendering RedPen to JSON", e); } return Response.ok().entity(response).build(); }