net.sf.json.JSON Java Examples
The following examples show how to use
net.sf.json.JSON.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Freebase.java From BotLibre with Eclipse Public License 1.0 | 6 votes |
/** * Process the mql query and convert the result to a JSON object. */ public JSON processQuery(String query) throws IOException { log("MQL", Level.FINEST, query); URL get = null; if (KEY.isEmpty()) { get = Utils.safeURL(query); } else { get = Utils.safeURL(query + "&key=" + KEY); } Reader reader = new InputStreamReader(get.openStream(), "UTF-8"); StringWriter output = new StringWriter(); int next = reader.read(); while (next != -1) { output.write(next); next = reader.read(); } String result = output.toString(); log("JSON", Level.FINEST, result); return JSONSerializer.toJSON(result); }
Example #2
Source File: Http.java From BotLibre with Eclipse Public License 1.0 | 6 votes |
/** * Return the JSON data object from the URL. */ public Vertex requestJSON(String url, String attribute, Map<String, String> headers, Network network) { log("GET JSON", Level.INFO, url, attribute); try { String json = Utils.httpGET(url, headers); log("JSON", Level.FINE, json); JSON root = (JSON)JSONSerializer.toJSON(json.trim()); if (root == null) { return null; } Object value = root; if (attribute != null) { value = ((JSONObject)root).get(attribute); if (value == null) { return null; } } Vertex object = convertElement(value, network); return object; } catch (Exception exception) { log(exception); return null; } }
Example #3
Source File: HttpPanelJsonView.java From zap-extensions with Apache License 2.0 | 6 votes |
@Override public void dataChanged(HttpPanelViewModelEvent e) { String body = ((AbstractStringHttpPanelViewModel) e.getSource()).getData(); try { JSON json = toJson(body); if (json instanceof JSONNull) { // avoid the string "null" for empty bodies httpPanelJsonArea.setText(""); } else { httpPanelJsonArea.setText(json.toString(2)); } } catch (JSONException ex) { httpPanelJsonArea.setText(body); } if (!isEditable()) { httpPanelJsonArea.discardAllEdits(); } // TODO: scrolling to top when new message is opened // httpPanelJsonArea.setCaretPosition(0); }
Example #4
Source File: WebhookJobPropertyDescriptor.java From office-365-connector-plugin with Apache License 2.0 | 6 votes |
@Override public WebhookJobProperty newInstance(StaplerRequest req, JSONObject formData) { List<Webhook> webhooks = new ArrayList<>(); if (formData != null && !formData.isNullObject()) { JSON webhooksData = (JSON) formData.get("webhooks"); if (webhooksData != null && !webhooksData.isEmpty()) { if (webhooksData.isArray()) { JSONArray webhooksArrayData = (JSONArray) webhooksData; webhooks.addAll(req.bindJSONToList(Webhook.class, webhooksArrayData)); } else { JSONObject webhooksObjectData = (JSONObject) webhooksData; webhooks.add(req.bindJSON(Webhook.class, webhooksObjectData)); } } } return new WebhookJobProperty(webhooks); }
Example #5
Source File: BlazeMeterHttpUtils.java From jmeter-bzm-plugins with Apache License 2.0 | 6 votes |
@Override protected String extractErrorMessage(String response) { if (response != null && !response.isEmpty()) { try { JSON jsonResponse = JSONSerializer.toJSON(response, new JsonConfig()); if (jsonResponse instanceof JSONObject) { JSONObject object = (JSONObject) jsonResponse; JSONObject errorObj = object.getJSONObject("error"); if (errorObj.containsKey("message")) { return errorObj.getString("message"); } } } catch (JSONException ex) { log.debug("Cannot parse JSON error response: " + response); } } return response; }
Example #6
Source File: WebSocketAPI.java From zap-extensions with Apache License 2.0 | 6 votes |
private String responseWrapper(JSON response, String id, String caller) { // OK, so its nasty wrapping JSON using strings, but the net.sf.json classes do way too much // auto conversion from strings that are valid JSON to JSON objects - this has proved to be // the safest option. StringBuilder sb = new StringBuilder(); sb.append("{ \"id\": \""); sb.append(id); sb.append("\", "); if (caller.length() > 0) { sb.append("caller\": \""); sb.append(caller); sb.append("\", "); } sb.append("\"response\": "); sb.append(response.toString()); sb.append(" }"); return sb.toString(); }
Example #7
Source File: Google.java From BotLibre with Eclipse Public License 1.0 | 6 votes |
public String newAccessToken() { try { Map<String, String> params = new HashMap<String, String>(); params.put("refresh_token", this.refreshToken); params.put("client_id", CLIENTID); params.put("client_secret", CLIENTSECRET); //params.put("redirect_uri", "urn:ietf:wg:oauth:2.0:oob"); params.put("grant_type", "refresh_token"); String json = Utils.httpPOST("https://accounts.google.com/o/oauth2/token", params); JSON root = (JSON)JSONSerializer.toJSON(json); if (!(root instanceof JSONObject)) { return null; } return ((JSONObject)root).getString("access_token"); } catch (Exception exception) { log(exception); return null; } }
Example #8
Source File: GlobalConfigurationService.java From sonar-quality-gates-plugin with MIT License | 5 votes |
protected void initGlobalDataConfig(JSON globalDataConfigs) { JSONArray array = getGlobalConfigsArray(globalDataConfigs); for (int i = 0; i < array.size(); i++) { JSONObject jsonobject = array.getJSONObject(i); addGlobalConfigDataForSonarInstance(jsonobject); } }
Example #9
Source File: BlazeMeterHttpUtilsEmul.java From jmeter-bzm-plugins with Apache License 2.0 | 5 votes |
public JSON getResponse(HttpRequestBase request) throws IOException { log.info("Simulating request: " + request); if (responses.size() > 0) { JSON resp = responses.remove(); log.info("Response: " + resp); return resp; } else { throw new IOException("No responses to emulate"); } }
Example #10
Source File: GlobalConfigurationService.java From sonar-quality-gates-plugin with MIT License | 5 votes |
protected JSONArray getGlobalConfigsArray(JSON globalDataConfigs) { JSONArray array; if (globalDataConfigs.isArray()) { array = JSONArray.class.cast(globalDataConfigs); } else { array = createJsonArrayFromObject((JSONObject) globalDataConfigs); } return array; }
Example #11
Source File: GlobalConfigurationServiceTest.java From sonar-quality-gates-plugin with MIT License | 5 votes |
@Test public void testInstantiateGlobalConfigData() { JSONObject json = new JSONObject(); json.put("listOfGlobalConfigData", JSONArray.fromObject("[{\"name\":\"Sonar\",\"url\":\"http://localhost:9000\",\"account\":\"admin\",\"password\":\"admin\"}]")); JSON globalDataConfig = (JSON) json.opt("listOfGlobalConfigData"); doNothing().when(spyGlobalConfigurationService).initGlobalDataConfig(globalDataConfig); assertEquals(listOfGlobalConfigData, spyGlobalConfigurationService.instantiateGlobalConfigData(json)); }
Example #12
Source File: Feature.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
public static String ConvertXMLtoJSON(String xml) { XMLSerializer xmlSerializer = new XMLSerializer(); JSON json =null; json = xmlSerializer.read(xml); return json.toString(1); }
Example #13
Source File: ReadJSONStepExecution.java From pipeline-utility-steps-plugin with MIT License | 5 votes |
@Override protected Object doRun() throws Exception { String fName = step.getDescriptor().getFunctionName(); if (isNotBlank(step.getFile()) && isNotBlank(step.getText())) { throw new IllegalArgumentException(Messages.ReadJSONStepExecution_tooManyArguments(fName)); } JSON json = null; if (!isBlank(step.getFile())) { FilePath f = ws.child(step.getFile()); if (f.exists() && !f.isDirectory()) { try (InputStream is = f.read()) { json = JSONSerializer.toJSON(IOUtils.toString(is, "UTF-8")); } } else if (f.isDirectory()) { throw new IllegalArgumentException(Messages.JSONStepExecution_fileIsDirectory(f.getRemote())); } else if (!f.exists()) { throw new FileNotFoundException(Messages.JSONStepExecution_fileNotFound(f.getRemote())); } } if (!isBlank(step.getText())) { json = JSONSerializer.toJSON(step.getText().trim()); } if (step.getReturnPojo()) { return transformToJavaLangStructures(json); } return json; }
Example #14
Source File: WriteJSONStepTest.java From pipeline-utility-steps-plugin with MIT License | 5 votes |
@Test public void writeFile() throws Exception { int elements = 3; String input = getJSON(elements); File output = temp.newFile(); WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " def json = readJSON text: '" + input + "'\n" + " json[0] = null\n" + " json[" + elements + "] = 45\n" + " writeJSON file: '" + FilenameTestsUtils.toPath(output) + "', json: json\n" + "}", true)); j.assertBuildStatusSuccess(p.scheduleBuild2(0)); // file exists by default so we check that should not be empty assertThat(output.length(), greaterThan(0l)); String jsonResult = new String(Files.readAllBytes(Paths.get(output.toURI()))); JSON json = JSONSerializer.toJSON(jsonResult); assertThat(json, instanceOf(JSONArray.class)); JSONArray jsonArray = (JSONArray) json; assertFalse("Saved json is an empty array", jsonArray.isEmpty()); assertThat(jsonArray.size(), is(elements + 1)); assertNotNull("Unexpected element value", jsonArray.get(0)); assertEquals("Unexpected element value", 45, jsonArray.get(elements)); }
Example #15
Source File: WebSocketAPI.java From zap-extensions with Apache License 2.0 | 5 votes |
private void optionalResponse(WebSocketProxy proxy, JSON response, JSONObject request) throws IOException { if (request != null) { String id = request.optString("id", ""); if (id.length() > 0) { // Only send a response if they've specified an id in the call sendWebSocketMessage( proxy, responseWrapper(response, id, request.optString("caller", ""))); } } }
Example #16
Source File: AjaxSpiderAPI.java From zap-extensions with Apache License 2.0 | 5 votes |
@Override public JSON toJSON() { JSONObject scopes = new JSONObject(); scopes.put(inScope.getName(), ((JSONObject) inScope.toJSON()).get(inScope.getName())); scopes.put( outOfScope.getName(), ((JSONObject) outOfScope.toJSON()).get(outOfScope.getName())); scopes.put(errors.getName(), ((JSONObject) errors.toJSON()).get(errors.getName())); JSONObject jo = new JSONObject(); jo.put(getName(), scopes); return jo; }
Example #17
Source File: HttpPanelJsonView.java From zap-extensions with Apache License 2.0 | 5 votes |
private static JSON toJson(String s) throws JSONException { JSON object; s = s.trim(); if (s.isEmpty()) { object = JSONNull.getInstance(); } else if (s.startsWith("{")) { object = JSONObject.fromObject(s); } else if (s.startsWith("[")) { object = JSONArray.fromObject(s); } else { throw new JSONException("Expected a '{', '[', or an empty message"); } return object; }
Example #18
Source File: UberallsClient.java From phabricator-jenkins-plugin with MIT License | 5 votes |
public CodeCoverageMetrics getParentCoverage(String sha) { if (sha == null) { return null; } try { String coverageJSON = getCoverage(sha); JsonSlurper jsonParser = new JsonSlurper(); JSON responseJSON = jsonParser.parseText(coverageJSON); if (responseJSON instanceof JSONNull) { return null; } JSONObject coverage = (JSONObject) responseJSON; return new CodeCoverageMetrics( ((Double) coverage.getDouble(PACKAGE_COVERAGE_KEY)).floatValue(), ((Double) coverage.getDouble(FILES_COVERAGE_KEY)).floatValue(), ((Double) coverage.getDouble(CLASSES_COVERAGE_KEY)).floatValue(), ((Double) coverage.getDouble(METHOD_COVERAGE_KEY)).floatValue(), ((Double) coverage.getDouble(LINE_COVERAGE_KEY)).floatValue(), ((Double) coverage.getDouble(CONDITIONAL_COVERAGE_KEY)).floatValue(), (coverage.getLong(LINES_COVERED_KEY)), (coverage.getLong(LINES_TESTED_KEY))); } catch (Exception e) { e.printStackTrace(logger.getStream()); } return null; }
Example #19
Source File: Wikidata.java From BotLibre with Eclipse Public License 1.0 | 5 votes |
/** * Process the mql query and convert the result to a JSON object. */ public JSON processQuery(String query) throws IOException { log("API", Level.FINEST, query); URL get = Utils.safeURL(query); Reader reader = new InputStreamReader(get.openStream(), "UTF-8"); StringWriter output = new StringWriter(); int next = reader.read(); while (next != -1) { output.write(next); next = reader.read(); } String result = output.toString(); log("JSON", Level.FINEST, result); return JSONSerializer.toJSON(result); }
Example #20
Source File: Google.java From BotLibre with Eclipse Public License 1.0 | 5 votes |
public void resetRefreshToken(String authCode) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("code", authCode); params.put("client_id", CLIENTID); params.put("client_secret", CLIENTSECRET); params.put("redirect_uri", "urn:ietf:wg:oauth:2.0:oob"); params.put("grant_type", "authorization_code"); String json = Utils.httpPOST("https://accounts.google.com/o/oauth2/token", params); JSON root = (JSON)JSONSerializer.toJSON(json); if (!(root instanceof JSONObject)) { throw new BotException("Invalid response"); } this.refreshToken = ((JSONObject)root).getString("refresh_token"); }
Example #21
Source File: JSONToXMLConverter.java From jmeter-plugins with Apache License 2.0 | 5 votes |
@Deprecated private String ConvertToXML(String jsonData) { XMLSerializer serializer = new XMLSerializer(); JSON json = JSONSerializer.toJSON(jsonData); serializer.setRootName("xmlOutput"); serializer.setTypeHintsEnabled(false); return serializer.write(json); }
Example #22
Source File: JsonAction.java From openemm with GNU Affero General Public License v3.0 | 5 votes |
public static <T> T fromJsonString(final String string, Class<T> rootClass) { final JsonConfig config = new JsonConfig(); config.setRootClass(rootClass); final JSON json = JSONSerializer.toJSON(string); @SuppressWarnings("unchecked") final T result = (T)JSONSerializer.toJava(json, config); return result; }
Example #23
Source File: JsonAction.java From openemm with GNU Affero General Public License v3.0 | 5 votes |
private final void sendJson(final Object obj, final HttpServletResponse response) throws IOException { final JSON json = toJson(obj); response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); try(PrintWriter writer = response.getWriter()) { json.write(writer); writer.flush(); } }
Example #24
Source File: QueryBuilderToEqlConverter.java From openemm with GNU Affero General Public License v3.0 | 5 votes |
public final String convertQueryBuilderJsonToEql(String queryBuilderRules, int companyID) throws QueryBuilderToEqlConversionException { //final JSONObject jsonObject = JSONObject.fromObject(queryBuilderRules); final JSON jsonObject = JSONSerializer.toJSON(queryBuilderRules, JSON_CONFIG); final Object resultNode = JSONSerializer.toJava(jsonObject, JSON_CONFIG); if(resultNode instanceof QueryBuilderGroupNode) { final QueryBuilderGroupNode groupNode = (QueryBuilderGroupNode) resultNode; return convertGroupNodeToEql(groupNode, companyID); } else if(resultNode instanceof QueryBuilderRuleNode) { final QueryBuilderRuleNode ruleNode = (QueryBuilderRuleNode) resultNode; return convertRuleNodeToEql(ruleNode, companyID); } else { return ""; } }
Example #25
Source File: JSONToXMLConverter.java From jmeter-plugins with Apache License 2.0 | 5 votes |
private void convertToXML() { XMLSerializer serializer = new XMLSerializer(); JSON json = JSONSerializer.toJSON(this.getJsonInput()); serializer.setRootName("xmlOutput"); serializer.setTypeHintsEnabled(false); setXmlOutput(serializer.write(json)); }
Example #26
Source File: HttpUtils.java From jmeter-bzm-plugins with Apache License 2.0 | 5 votes |
/** * Create Patch Request */ public HttpPatch createPatch(String url, JSON data) { HttpPatch patch = new HttpPatch(url); patch.setHeader("Content-Type", "application/json"); String string = data.toString(1); try { patch.setEntity(new StringEntity(string, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } return patch; }
Example #27
Source File: HttpUtils.java From jmeter-bzm-plugins with Apache License 2.0 | 5 votes |
/** * Execute Http request and verify response * @param request - HTTP Request * @param expectedCode - expected response code * @return - response in JSONObject */ public JSONObject queryObject(HttpRequestBase request, int expectedCode) throws IOException { JSON res = query(request, expectedCode); if (!(res instanceof JSONObject)) { throw new IOException("Unexpected response: " + res); } return (JSONObject) res; }
Example #28
Source File: HttpUtils.java From jmeter-bzm-plugins with Apache License 2.0 | 5 votes |
/** * Execute Http request and response code * @param request - HTTP Request * @param expectedCode - expected response code * @return - response in JSONObject */ public JSON query(HttpRequestBase request, int expectedCode) throws IOException { log.info("Requesting: " + request); addRequiredHeader(request); HttpParams requestParams = request.getParams(); requestParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT * 1000); requestParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT * 1000); synchronized (httpClient) { String response; try { HttpResponse result = httpClient.execute(request); int statusCode = result.getStatusLine().getStatusCode(); response = getResponseEntity(result); if (statusCode != expectedCode) { notifier.notifyAbout("Response with code " + statusCode + ": " + extractErrorMessage(response)); throw new IOException("API responded with wrong status code: " + statusCode); } else { log.debug("Response: " + response); } } finally { request.abort(); } if (response == null || response.isEmpty()) { return JSONNull.getInstance(); } else { return JSONSerializer.toJSON(response, new JsonConfig()); } } }
Example #29
Source File: FreebaseUtil.java From xcurator with Apache License 2.0 | 5 votes |
public static JSONArray fetch(String query_template_file, Map<String, String> params) { try { properties.load(new FileInputStream(FREEBASE_PROPERTIES_LOC)); HttpTransport httpTransport = new NetHttpTransport(); HttpRequestFactory requestFactory = httpTransport.createRequestFactory(); String query = IOUtils.toString(new FileInputStream(query_template_file)); query = manipulateQuery(query, params); GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/mqlread"); url.put("query", query); url.put("key", properties.get("API_KEY")); System.out.println("URL:" + url); HttpRequest request = requestFactory.buildGetRequest(url); HttpResponse httpResponse = request.execute(); JSON obj = JSONSerializer.toJSON(httpResponse.parseAsString()); if (obj.isEmpty()) { return null; } JSONObject jsonObject = (JSONObject) obj; JSONArray results = jsonObject.getJSONArray("result"); System.out.println(results.toString()); return results; } catch (IOException ex) { ex.printStackTrace(); } return null; }
Example #30
Source File: HttpUtilsEmul.java From jmeter-bzm-plugins with Apache License 2.0 | 5 votes |
public JSON getResponse(HttpRequestBase request) throws IOException { log.info("Simulating request: " + request); if (responses.size() > 0) { JSON resp = responses.remove(); log.info("Response: " + resp); return resp; } else { throw new IOException("No responses to emulate"); } }