/** * Create a response containing the supplied "data". * @param data The data. */ JSONObjectResponse(@Nonnull Map<?,?> data) { this(); this.jsonObject.put("data", JSONObject.fromObject(data)); }
@Override public JSONObject createContent() { if (traces.size() == 0) { return null; } Map<String, Object> info = new TreeMap<>(); info.put("components", buildComponentInformation()); info.put("dispatches", buildDispatches()); return JSONObject.fromObject(info); }
/** * Merge a list of ToolInstallerList and removes duplicate tool installers (ie having the same id) * @param jsonList the list of ToolInstallerList to merge * @return the merged ToolInstallerList wrapped in a JSONObject */ private JSONObject reduce(List<JSONObject> jsonList) { List<ToolInstallerEntry> reducedToolEntries = new LinkedList<>(); HashSet<String> processedIds = new HashSet<String>(); for (JSONObject jsonToolList : jsonList) { ToolInstallerList toolInstallerList = (ToolInstallerList) JSONObject.toBean(jsonToolList, ToolInstallerList.class); for(ToolInstallerEntry entry : toolInstallerList.list) { // being able to add the id into the processedIds set means this tool has not been processed before if (processedIds.add(entry.id)) { reducedToolEntries.add(entry); } } } ToolInstallerList toolInstallerList = new ToolInstallerList(); toolInstallerList.list = new ToolInstallerEntry[reducedToolEntries.size()]; reducedToolEntries.toArray(toolInstallerList.list); JSONObject reducedToolEntriesJsonList = JSONObject.fromObject(toolInstallerList); //return the list with no duplicates return reducedToolEntriesJsonList; }
private FormValidation updateData(String json, boolean signatureCheck) throws IOException { dataTimestamp = System.currentTimeMillis(); JSONObject o = JSONObject.fromObject(json); try { int v = o.getInt("updateCenterVersion"); if (v != 1) { throw new IllegalArgumentException("Unrecognized update center version: " + v); } } catch (JSONException x) { throw new IllegalArgumentException("Could not find (numeric) updateCenterVersion in " + json, x); } if (signatureCheck) { FormValidation e = verifySignature(o); if (e.kind!=Kind.OK) { LOGGER.severe(e.toString()); return e; } } LOGGER.info("Obtained the latest update center data file for UpdateSource " + id); retryWindow = 0; getDataFile().write(json); data = new Data(o); return FormValidation.ok(); }
/** * Loads the current file into JSON and returns it, or null * if no data exists. */ public JSONObject getData() throws IOException { TextFile df = getDataFile(); if(df.exists()) try { return JSONObject.fromObject(df.read()); } catch (JSONException e) { df.delete(); // if we keep this file, it will cause repeated failures throw new IOException("Failed to parse "+df+" into JSON",e); } return null; }
return HttpResponses.okJSON(JSONObject.fromObject(response)); } catch (Exception e) { return HttpResponses.errorJSON(String.format("ERROR: %s", e.getMessage()));
/** * Gets the raw update center JSON data. */ public JSONObject getJSONObject() { TextFile df = getDataFile(); if(df.exists()) { try { return JSONObject.fromObject(df.read()); } catch (JSONException e) { LOGGER.log(Level.SEVERE,"Failed to parse "+df,e); df.delete(); // if we keep this file, it will cause repeated failures return null; } catch (IOException e) { LOGGER.log(Level.SEVERE,"Failed to parse "+df,e); df.delete(); // if we keep this file, it will cause repeated failures return null; } } else { return null; } }
continue; JSONObject o = JSONObject.fromObject(jsonString); if (signatureCheck) { FormValidation e = updatesite.getJsonSignatureValidator(signatureValidatorPrefix +" '"+id+"'").verifySignature(o);
private JSONObject getPluginVersions(UpdateSite updateSite) { // TODO use jenkins-core API for this once UpdateSite offers. try { return pluginVersions.get(updateSite.getId(), () -> { final File file = new File(Jenkins.getInstance().getRootDir(), "updates/" + updateSite.getId() + "plugin-versions.json"); boolean needUpdate = !file.exists() || System.currentTimeMillis() - file.lastModified() > TimeUnit.DAYS.toMillis(1); if (needUpdate) { final URI metadata = new URI(updateSite.getUrl()).resolve("./plugin-versions.json"); try (InputStream is = ProxyConfiguration.open(metadata.toURL()).getInputStream()) { FileUtils.copyInputStreamToFile(is, file); } catch (IOException e) { logger.log(Level.WARNING, "Failed to download plugin-versions metadata from " + updateSite.getUrl(), e); } } try { return JSONObject.fromObject(FileUtils.readFileToString(file)).getJSONObject("plugins"); } catch (IOException e) { return null; } }); } catch (ExecutionException e) { return null; } }
/** * Installs a list of plugins from a JSON POST. * @param req The request object. * @return A JSON response that includes a "correlationId" in the "data" element. * That "correlationId" can then be used in calls to * {@link UpdateCenter#doInstallStatus(org.kohsuke.stapler.StaplerRequest)}. * @throws IOException Error reading JSON payload fro request. */ @RequirePOST @Restricted(DoNotUse.class) // WebOnly public HttpResponse doInstallPlugins(StaplerRequest req) throws IOException { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); String payload = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding()); JSONObject request = JSONObject.fromObject(payload); JSONArray pluginListJSON = request.getJSONArray("plugins"); List<String> plugins = new ArrayList<>(); for (int i = 0; i < pluginListJSON.size(); i++) { plugins.add(pluginListJSON.getString(i)); } UUID correlationId = UUID.randomUUID(); try { boolean dynamicLoad = request.getBoolean("dynamicLoad"); install(plugins, dynamicLoad, correlationId); JSONObject responseData = new JSONObject(); responseData.put("correlationId", correlationId.toString()); return hudson.util.HttpResponses.okJSON(responseData); } catch (Exception e) { return hudson.util.HttpResponses.errorJSON(e.getMessage()); } }
info.put("properties", security); return JSONObject.fromObject(info);
@RequestMapping("/hello") public ResponseEntity<?> hello(){ City city = cityMapper.selectByPrimaryKey(12); System.out.println(JSONObject.fromObject(city).toString()); return new ResponseEntity<Object>("hello", HttpStatus.OK); } }
@RequestMapping("/hello") public ResponseEntity<?> hello(){ City city = cityMapper.selectByPrimaryKey(12); System.out.println(JSONObject.fromObject(city).toString()); return new ResponseEntity<Object>("hello", HttpStatus.OK); } }
@SuppressWarnings("unchecked") private Map<String, Object> jsonToParamsMap(final String paramsInJson) { if (StringUtils.isBlank(paramsInJson)) { return Collections.emptyMap(); } return JSONObject.fromObject(paramsInJson); }
/** * Create a response containing the supplied "data". * @param data The data. */ JSONObjectResponse(@Nonnull Map<?,?> data) { this(); this.jsonObject.put("data", JSONObject.fromObject(data)); }
private JSONObject callStepsToJson(String jenkinsFileContent) throws IOException { JenkinsRule.WebClient wc = j.createWebClient(); WebRequest req = new WebRequest(new URL(wc.getContextPath() + ModelConverterAction.PIPELINE_CONVERTER_URL + "/stepsToJson"), HttpMethod.POST); assertNotNull(jenkinsFileContent); NameValuePair pair = new NameValuePair("jenkinsfile", jenkinsFileContent); req.setRequestParameters(Collections.singletonList(pair)); String rawResult = wc.getPage(req).getWebResponse().getContentAsString(); assertNotNull(rawResult); return JSONObject.fromObject(rawResult); } }
private JSONObject callStepToJenkinsFile(String jsonFileName) throws IOException { JenkinsRule.WebClient wc = j.createWebClient(); WebRequest req = new WebRequest(new URL(wc.getContextPath() + ModelConverterAction.PIPELINE_CONVERTER_URL + "/stepsToJenkinsfile"), HttpMethod.POST); String simpleJson = fileContentsFromResources(jsonFileName); assertNotNull(simpleJson); NameValuePair pair = new NameValuePair("json", simpleJson); req.setRequestParameters(Collections.singletonList(pair)); String rawResult = wc.getPage(req).getWebResponse().getContentAsString(); assertNotNull(rawResult); return JSONObject.fromObject(rawResult); }
@Test public void groovyToASTEqualsJSONToAST() throws Exception { ModelASTPipelineDef groovyRoot = Converter.urlToPipelineDef(getClass().getResource("/" + configName + ".groovy")); assertNotNull(groovyRoot); JSONObject origJson = JSONObject.fromObject(fileContentsFromResources("json/" + configName + ".json")); assertNotNull("Couldn't parse JSON for " + configName, origJson); JSONParser jp = new JSONParser(Converter.jsonTreeFromJSONObject(origJson)); ModelASTPipelineDef jsonRoot = jp.parse(); assertNotNull(jsonRoot); assertEquals(groovyRoot, jsonRoot); } }
@Test public void parseAndValidateJSON() throws Exception { JSONObject json = JSONObject.fromObject(fileContentsFromResources("json/" + configName + ".json")); assertNotNull("Couldn't parse JSON for " + configName, json); JSONParser jp = new JSONParser(Converter.jsonTreeFromJSONObject(json)); ModelASTPipelineDef pipelineDef = jp.parse(); assertEquals(getJSONErrorReport(jp, configName), 0, jp.getErrorCollector().getErrorCount()); assertNotNull("Pipeline null for " + configName, pipelineDef); } }
@Test public void jsonToASTToJSON() throws Exception { JSONObject origJson = JSONObject.fromObject(fileContentsFromResources("json/" + configName + ".json")); assertNotNull("Couldn't parse JSON for " + configName, origJson); JSONParser jp = new JSONParser(Converter.jsonTreeFromJSONObject(origJson)); ModelASTPipelineDef pipelineDef = jp.parse(); assertEquals(getJSONErrorReport(jp, configName), 0, jp.getErrorCollector().getErrorCount()); assertNotNull("Pipeline null for " + configName, pipelineDef); assertEquals(origJson, pipelineDef.toJSON()); }