List of usage examples for org.json JSONArray put
public JSONArray put(Object value)
From source file:com.grillecube.common.utils.JSONHelper.java
public static JSONArray arrayToJSONArray(float[] array, double precision) { JSONArray jsonarray = new JSONArray(); if (array == null) { return (null); }/*from w w w. j a va 2 s . c o m*/ for (float f : array) { jsonarray.put((double) Math.round(f * precision) / precision); // jsonarray.put(f); } return (jsonarray); }
From source file:com.grillecube.common.utils.JSONHelper.java
public static JSONArray arrayToJSONArray(int[] array) { JSONArray jsonarray = new JSONArray(); if (array == null) { return (null); }// w w w . j a va 2 s . c om for (int i : array) { jsonarray.put(i); } return (jsonarray); }
From source file:com.openerp.addons.note.NoteDBHelper.java
public JSONArray getSelectedTagId(HashMap<String, TagsItems> selectedTags) { JSONArray list = new JSONArray(); for (String key : selectedTags.keySet()) { list.put(selectedTags.get(key).getId()); }/* ww w . ja v a2 s .c o m*/ return list; }
From source file:com.basho.riak.client.mapreduce.filter.IntToStringFilter.java
public JSONArray toJson() { JSONArray filter = new JSONArray(); filter.put("int_to_string"); return filter; }
From source file:com.nextgis.maplib.map.LayerGroup.java
@Override public JSONObject toJSON() throws JSONException { JSONObject rootConfig = super.toJSON(); JSONArray jsonArray = new JSONArray(); rootConfig.put(JSON_LAYERS_KEY, jsonArray); for (ILayer layer : mLayers) { JSONObject layerObject = new JSONObject(); layerObject.put(JSON_PATH_KEY, layer.getPath().getName()); jsonArray.put(layerObject); }// ww w . ja va 2s . co m return rootConfig; }
From source file:com.groupon.odo.proxylib.BackupService.java
/** * 1. Resets profile to get fresh slate//from ww w. ja va2s .c o m * 2. Updates active server group to one from json * 3. For each path in json, sets request/response enabled * 4. Adds active overrides to each path * 5. Update arguments and repeat count for each override * * @param profileBackup JSON containing server configuration and overrides to activate * @param profileId Profile to update * @param clientUUID Client UUID to apply update to * @return * @throws Exception Array of errors for things that could not be imported */ public void setProfileFromBackup(JSONObject profileBackup, int profileId, String clientUUID) throws Exception { // Reset the profile before applying changes ClientService clientService = ClientService.getInstance(); clientService.reset(profileId, clientUUID); clientService.updateActive(profileId, clientUUID, true); JSONArray errors = new JSONArray(); // Change to correct server group JSONObject activeServerGroup = profileBackup.getJSONObject(Constants.BACKUP_ACTIVE_SERVER_GROUP); int activeServerId = getServerIdFromName(activeServerGroup.getString(Constants.NAME), profileId); if (activeServerId == -1) { errors.put(formErrorJson("Server Error", "Cannot change to '" + activeServerGroup.getString(Constants.NAME) + "' - Check Server Group Exists")); } else { Client clientToUpdate = ClientService.getInstance().findClient(clientUUID, profileId); ServerRedirectService.getInstance().activateServerGroup(activeServerId, clientToUpdate.getId()); } JSONArray enabledPaths = profileBackup.getJSONArray(Constants.ENABLED_PATHS); PathOverrideService pathOverrideService = PathOverrideService.getInstance(); OverrideService overrideService = OverrideService.getInstance(); for (int i = 0; i < enabledPaths.length(); i++) { JSONObject path = enabledPaths.getJSONObject(i); int pathId = pathOverrideService.getPathId(path.getString(Constants.PATH_NAME), profileId); // Set path to have request/response enabled as necessary try { if (path.getBoolean(Constants.REQUEST_ENABLED)) { pathOverrideService.setRequestEnabled(pathId, true, clientUUID); } if (path.getBoolean(Constants.RESPONSE_ENABLED)) { pathOverrideService.setResponseEnabled(pathId, true, clientUUID); } } catch (Exception e) { errors.put(formErrorJson("Path Error", "Cannot update path: '" + path.getString(Constants.PATH_NAME) + "' - Check Path Exists")); continue; } JSONArray enabledOverrides = path.getJSONArray(Constants.ENABLED_ENDPOINTS); /** * 2 for loops to ensure overrides are added with correct priority * 1st loop is priority currently adding override to * 2nd loop is to find the override with matching priority in profile json */ for (int j = 0; j < enabledOverrides.length(); j++) { for (int k = 0; k < enabledOverrides.length(); k++) { JSONObject override = enabledOverrides.getJSONObject(k); if (override.getInt(Constants.PRIORITY) != j) { continue; } int overrideId; // Name of method that can be used by error message as necessary later String overrideNameForError = ""; // Get the Id of the override try { // If method information is null, then the override is a default override if (override.get(Constants.METHOD_INFORMATION) != JSONObject.NULL) { JSONObject methodInformation = override.getJSONObject(Constants.METHOD_INFORMATION); overrideNameForError = methodInformation.getString(Constants.METHOD_NAME); overrideId = overrideService.getOverrideIdForMethod( methodInformation.getString(Constants.CLASS_NAME), methodInformation.getString(Constants.METHOD_NAME)); } else { overrideNameForError = "Default Override"; overrideId = override.getInt(Constants.OVERRIDE_ID); } // Enable override and set repeat number and arguments overrideService.enableOverride(overrideId, pathId, clientUUID); overrideService.updateRepeatNumber(overrideId, pathId, override.getInt(Constants.PRIORITY), override.getInt(Constants.REPEAT_NUMBER), clientUUID); overrideService.updateArguments(overrideId, pathId, override.getInt(Constants.PRIORITY), override.getString(Constants.ARGUMENTS), clientUUID); } catch (Exception e) { errors.put(formErrorJson("Override Error", "Cannot add/update override: '" + overrideNameForError + "' - Check Override Exists")); continue; } } } } // Throw exception if any errors occured if (errors.length() > 0) { throw new Exception(errors.toString()); } }
From source file:org.eclipse.orion.server.authentication.formopenid.ManageOpenidsServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { String pathInfo = req.getPathInfo() == null ? "" : req.getPathInfo(); //$NON-NLS-1$ try {/*from w ww . jav a2s .c o m*/ if (pathInfo.startsWith("/openid")) { //$NON-NLS-1$ String openid = req.getParameter(OpenIdHelper.OPENID); if (openid != null) { consumer = OpenIdHelper.redirectToOpenIdProvider(req, response, consumer); return; } String op_return = req.getParameter(OpenIdHelper.OP_RETURN); if (op_return != null) { OpenIdHelper.handleOpenIdReturn(req, response, consumer); return; } } } catch (OpenIdException e) { writeOpenIdError(e.getMessage(), req, response); return; } JSONArray providersJson = new JSONArray(); for (OpendIdProviderDescription provider : getSupportedOpenids(req)) { JSONObject providerJson = new JSONObject(); try { providerJson.put(ProtocolConstants.KEY_NAME, provider.getName()); providerJson.put(OpenIdConstants.KEY_IMAGE, provider.getImage()); providerJson.put(OpenIdConstants.KEY_URL, provider.getAuthSite()); providersJson.put(providerJson); } catch (JSONException e) { LogHelper.log(new Status(IStatus.ERROR, Activator.PI_AUTHENTICATION_SERVLETS, "Exception writing OpenId provider " + provider.getName(), e)); //$NON-NLS-1$ } } response.setContentType("application/json"); //$NON-NLS-1$ PrintWriter writer = response.getWriter(); writer.append(providersJson.toString()); writer.flush(); }
From source file:org.transdroid.daemon.Transmission.TransmissionAdapter.java
@Override public DaemonTaskResult executeTask(Log log, DaemonTask task) { try {/* ww w. j av a 2 s . c o m*/ // Get the server version if (rpcVersion <= -1) { // Get server session statistics JSONObject response = makeRequest(log, buildRequestObject("session-get", new JSONObject())); rpcVersion = response.getJSONObject("arguments").getInt("rpc-version"); } JSONObject request = new JSONObject(); switch (task.getMethod()) { case Retrieve: // Request all torrents from server JSONArray fields = new JSONArray(); final String[] fieldsArray = new String[] { RPC_ID, RPC_NAME, RPC_ERROR, RPC_ERRORSTRING, RPC_STATUS, RPC_DOWNLOADDIR, RPC_RATEDOWNLOAD, RPC_RATEUPLOAD, RPC_PEERSGETTING, RPC_PEERSSENDING, RPC_PEERSCONNECTED, RPC_ETA, RPC_DOWNLOADSIZE1, RPC_DOWNLOADSIZE2, RPC_UPLOADEDEVER, RPC_TOTALSIZE, RPC_DATEADDED, RPC_DATEDONE, RPC_AVAILABLE, RPC_COMMENT }; for (String field : fieldsArray) { fields.put(field); } request.put("fields", fields); JSONObject result = makeRequest(log, buildRequestObject("torrent-get", request)); return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonRetrieveTorrents(result.getJSONObject("arguments")), null); case GetStats: // Request the current server statistics JSONObject stats = makeRequest(log, buildRequestObject("session-get", new JSONObject())) .getJSONObject("arguments"); return new GetStatsTaskSuccessResult((GetStatsTask) task, stats.getBoolean("alt-speed-enabled"), rpcVersion >= 12 ? stats.getLong("download-dir-free-space") : -1); case GetTorrentDetails: // Request fine details of a specific torrent JSONArray dfields = new JSONArray(); dfields.put("trackers"); dfields.put("trackerStats"); JSONObject buildDGet = buildTorrentRequestObject(task.getTargetTorrent().getUniqueID(), null, false); buildDGet.put("fields", dfields); JSONObject getDResult = makeRequest(log, buildRequestObject("torrent-get", buildDGet)); return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task, parseJsonTorrentDetails(getDResult.getJSONObject("arguments"))); case GetFileList: // Request all details for a specific torrent JSONArray ffields = new JSONArray(); ffields.put("files"); ffields.put("fileStats"); JSONObject buildGet = buildTorrentRequestObject(task.getTargetTorrent().getUniqueID(), null, false); buildGet.put("fields", ffields); JSONObject getResult = makeRequest(log, buildRequestObject("torrent-get", buildGet)); return new GetFileListTaskSuccessResult((GetFileListTask) task, parseJsonFileList(getResult.getJSONObject("arguments"), task.getTargetTorrent())); case AddByFile: // Add a torrent to the server by sending the contents of a local .torrent file String file = ((AddByFileTask) task).getFile(); // Encode the .torrent file's data InputStream in = new Base64.InputStream(new FileInputStream(new File(URI.create(file))), Base64.ENCODE); StringWriter writer = new StringWriter(); int c; while ((c = in.read()) != -1) { writer.write(c); } in.close(); // Request to add a torrent by Base64-encoded meta data request.put("metainfo", writer.toString()); makeRequest(log, buildRequestObject("torrent-add", request)); return new DaemonTaskSuccessResult(task); case AddByUrl: // Request to add a torrent by URL String url = ((AddByUrlTask) task).getUrl(); request.put("filename", url); makeRequest(log, buildRequestObject("torrent-add", request)); return new DaemonTaskSuccessResult(task); case AddByMagnetUrl: // Request to add a magnet link by URL String magnet = ((AddByMagnetUrlTask) task).getUrl(); request.put("filename", magnet); makeRequest(log, buildRequestObject("torrent-add", request)); return new DaemonTaskSuccessResult(task); case Remove: // Remove a torrent RemoveTask removeTask = (RemoveTask) task; makeRequest(log, buildRequestObject("torrent-remove", buildTorrentRequestObject(removeTask.getTargetTorrent().getUniqueID(), "delete-local-data", removeTask.includingData()))); return new DaemonTaskSuccessResult(task); case Pause: // Pause a torrent PauseTask pauseTask = (PauseTask) task; makeRequest(log, buildRequestObject("torrent-stop", buildTorrentRequestObject(pauseTask.getTargetTorrent().getUniqueID(), null, false))); return new DaemonTaskSuccessResult(task); case PauseAll: // Resume all torrents makeRequest(log, buildRequestObject("torrent-stop", buildTorrentRequestObject(FOR_ALL, null, false))); return new DaemonTaskSuccessResult(task); case Resume: // Resume a torrent ResumeTask resumeTask = (ResumeTask) task; makeRequest(log, buildRequestObject("torrent-start", buildTorrentRequestObject(resumeTask.getTargetTorrent().getUniqueID(), null, false))); return new DaemonTaskSuccessResult(task); case ResumeAll: // Resume all torrents makeRequest(log, buildRequestObject("torrent-start", buildTorrentRequestObject(FOR_ALL, null, false))); return new DaemonTaskSuccessResult(task); case SetDownloadLocation: // Change the download location SetDownloadLocationTask sdlTask = (SetDownloadLocationTask) task; // Build request JSONObject sdlrequest = new JSONObject(); JSONArray sdlids = new JSONArray(); sdlids.put(Long.parseLong(task.getTargetTorrent().getUniqueID())); sdlrequest.put("ids", sdlids); sdlrequest.put("location", sdlTask.getNewLocation()); sdlrequest.put("move", true); makeRequest(log, buildRequestObject("torrent-set-location", sdlrequest)); return new DaemonTaskSuccessResult(task); case SetFilePriorities: // Set priorities of the files of some torrent SetFilePriorityTask prioTask = (SetFilePriorityTask) task; // Build request JSONObject prequest = new JSONObject(); JSONArray ids = new JSONArray(); ids.put(Long.parseLong(task.getTargetTorrent().getUniqueID())); prequest.put("ids", ids); JSONArray fileids = new JSONArray(); for (TorrentFile forfile : prioTask.getForFiles()) { fileids.put(Integer.parseInt(forfile.getKey())); // The keys are the indices of the files, so always numeric } switch (prioTask.getNewPriority()) { case Off: prequest.put("files-unwanted", fileids); break; case Low: prequest.put("files-wanted", fileids); prequest.put("priority-low", fileids); break; case Normal: prequest.put("files-wanted", fileids); prequest.put("priority-normal", fileids); break; case High: prequest.put("files-wanted", fileids); prequest.put("priority-high", fileids); break; } makeRequest(log, buildRequestObject("torrent-set", prequest)); return new DaemonTaskSuccessResult(task); case SetTransferRates: // Request to set the maximum transfer rates SetTransferRatesTask ratesTask = (SetTransferRatesTask) task; if (ratesTask.getUploadRate() == null) { request.put("speed-limit-up-enabled", false); } else { request.put("speed-limit-up-enabled", true); request.put("speed-limit-up", ratesTask.getUploadRate().intValue()); } if (ratesTask.getDownloadRate() == null) { request.put("speed-limit-down-enabled", false); } else { request.put("speed-limit-down-enabled", true); request.put("speed-limit-down", ratesTask.getDownloadRate().intValue()); } makeRequest(log, buildRequestObject("session-set", request)); return new DaemonTaskSuccessResult(task); case SetAlternativeMode: // Request to set the alternative speed mode (Tutle Mode) SetAlternativeModeTask altModeTask = (SetAlternativeModeTask) task; request.put("alt-speed-enabled", altModeTask.isAlternativeModeEnabled()); makeRequest(log, buildRequestObject("session-set", request)); return new DaemonTaskSuccessResult(task); case ForceRecheck: // Verify torrent data integrity ForceRecheckTask verifyTask = (ForceRecheckTask) task; makeRequest(log, buildRequestObject("torrent-verify", buildTorrentRequestObject(verifyTask.getTargetTorrent().getUniqueID(), null, false))); return new DaemonTaskSuccessResult(task); default: return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType())); } } catch (JSONException e) { return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString())); } catch (DaemonException e) { return new DaemonTaskFailureResult(task, e); } catch (FileNotFoundException e) { return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.FileAccessError, e.toString())); } catch (IOException e) { return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.FileAccessError, e.toString())); } }
From source file:org.transdroid.daemon.Transmission.TransmissionAdapter.java
private JSONObject buildTorrentRequestObject(long torrentID, String extraKey, boolean extraValue) throws JSONException { // Build request for one specific torrent JSONObject request = new JSONObject(); if (torrentID != FOR_ALL) { JSONArray ids = new JSONArray(); ids.put(torrentID); // The only id to add request.put("ids", ids); }/*from w w w . j a v a2 s. co m*/ if (extraKey != null) { request.put(extraKey, extraValue); } return request; }
From source file:pt.webdetails.cfr.CfrApi.java
@GET @Path("/setPermissions") @Produces(MimeTypes.JSON)/*from w w w . j ava2 s .co m*/ public String setPermissions(@QueryParam(MethodParams.PATH) String path, @QueryParam(MethodParams.ID) @DefaultValue("") List<String> ids, @QueryParam(MethodParams.PERMISSION) @DefaultValue("") List<String> permissions, @QueryParam(MethodParams.RECURSIVE) @DefaultValue("false") Boolean recursive) throws JSONException { path = checkRelativePathSanity(path); String[] userOrGroupId = ids.toArray(new String[ids.size()]); String[] _permissions = permissions.toArray(new String[permissions.size()]); boolean isDir; boolean admin = isUserAdmin(); boolean errorSetting = false; JSONObject result = new JSONObject(); if (path != null && userOrGroupId.length > 0 && _permissions.length > 0) { List<String> files = new ArrayList<String>(); if (recursive) { files = getFileNameTree(path); } else { files.add(path); } isDir = getRepository().getFile(path).isDirectory(); // build valid permissions set Set<FilePermissionEnum> validPermissions = new TreeSet<FilePermissionEnum>(); for (String permission : _permissions) { FilePermissionEnum perm = FilePermissionEnum.resolve(permission); if (perm != null) { validPermissions.add(perm); } } JSONArray permissionAddResultArray = new JSONArray(); for (String file : files) { CfrFile f = getRepository().getFile(file); if (isDir && f.isFile()) { continue; } for (String id : userOrGroupId) { boolean storeResult = storeFile(file, id, validPermissions); if (storeResult) { permissionAddResultArray.put(new JSONObject().put("status", String.format("Added permission for path %s and user/role %s", file, id))); } else { if (admin) { permissionAddResultArray.put(new JSONObject().put("status", String .format("Failed to add permission for path %s and user/role %s", file, id))); } else { errorSetting = true; } } } } result.put("status", "Operation finished. Check statusArray for details."); if (errorSetting) { permissionAddResultArray.put(new JSONObject().put("status", "Some permissions could not be set")); } result.put("statusArray", permissionAddResultArray); } else { result.put("status", "Path or user group parameters not found"); } return result.toString(2); }