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 Project: jmeter-bzm-plugins   Author: Blazemeter   File: BlazeMeterHttpUtils.java    License: Apache License 2.0 6 votes vote down vote up
@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 #2
Source Project: office-365-connector-plugin   Author: jenkinsci   File: WebhookJobPropertyDescriptor.java    License: Apache License 2.0 6 votes vote down vote up
@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 #3
Source Project: zap-extensions   Author: zaproxy   File: WebSocketAPI.java    License: Apache License 2.0 6 votes vote down vote up
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 #4
Source Project: zap-extensions   Author: zaproxy   File: HttpPanelJsonView.java    License: Apache License 2.0 6 votes vote down vote up
@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 #5
Source Project: BotLibre   Author: BotLibre   File: Http.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 #6
Source Project: BotLibre   Author: BotLibre   File: Freebase.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 #7
Source Project: BotLibre   Author: BotLibre   File: Google.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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 Project: openemm   Author: agnitas-org   File: JsonAction.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 #9
Source Project: openemm   Author: agnitas-org   File: JsonAction.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 #10
Source Project: openemm   Author: agnitas-org   File: QueryBuilderToEqlConverter.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 #11
Source Project: jmeter-bzm-plugins   Author: Blazemeter   File: HttpUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 #12
Source Project: jmeter-bzm-plugins   Author: Blazemeter   File: HttpUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 #13
Source Project: jmeter-bzm-plugins   Author: Blazemeter   File: HttpUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 #14
Source Project: jmeter-bzm-plugins   Author: Blazemeter   File: HttpUtilsEmul.java    License: Apache License 2.0 5 votes vote down vote up
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 #15
Source Project: jmeter-bzm-plugins   Author: Blazemeter   File: LoadosophiaAPIClientEmul.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JSON query(HttpRequestBase request, int expectedCode) 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 #16
Source Project: jmeter-bzm-plugins   Author: Blazemeter   File: BlazemeterAPIClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUserFlow() throws Exception {

    URL url = BlazemeterAPIClientTest.class.getResource("/responses.json");
    JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(FileUtils.readFileToString(new File(url.getPath())), new JsonConfig());


    StatusNotifierCallbackTest.StatusNotifierCallbackImpl notifier = new StatusNotifierCallbackTest.StatusNotifierCallbackImpl();
    BlazeMeterReport report = new BlazeMeterReport();
    report.setShareTest(true);
    report.setProject("New project");
    report.setTitle("New test");
    report.setToken("123456");

    BlazeMeterHttpUtilsEmul emul = new BlazeMeterHttpUtilsEmul(notifier, "https://a.blazemeter.com/", "data_address", new BlazeMeterReport());
    for (Object resp : jsonArray) {
        emul.addEmul((JSON) resp);
    }
    BlazeMeterAPIClient apiClient = new BlazeMeterAPIClient(emul, notifier, report);
    apiClient.prepare();

    // if share user test
    String linkPublic = apiClient.startOnline();
    System.out.println(linkPublic);
    assertFalse(linkPublic.isEmpty());
    assertEquals("https://a.blazemeter.com//app/?public-token=public_test_token#/masters/master_id/summary", linkPublic);

    // if private user test
    report.setShareTest(false);
    String linkPrivate = apiClient.startOnline();
    System.out.println(linkPrivate);
    assertFalse(linkPrivate.isEmpty());
    assertEquals("https://a.blazemeter.com//app/#/masters/master_id", linkPrivate);


    List<SampleResult> sampleResults = generateResults();
    apiClient.sendOnlineData(JSONConverter.convertToJSON(sampleResults, sampleResults));
    apiClient.endOnline();
}
 
Example #17
Source Project: jmeter-bzm-plugins   Author: Blazemeter   File: BlazeMeterHttpUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
private BlazeMeterHttpUtils createMockUtils(StatusNotifierCallbackTest.StatusNotifierCallbackImpl callbackTest,
                                            String address, BlazeMeterReport report) {
    return new BlazeMeterHttpUtils(callbackTest, address, address, report) {
        @Override
        public JSON query(HttpRequestBase request, int expectedCode) throws IOException {
            try {
                super.query(request, expectedCode);
                fail("Cannot send request to " + address);
            } catch (IllegalStateException ex) {
                assertEquals("Target host must not be null, or set in parameters.", ex.getMessage());
            }
            return JSONSerializer.toJSON("{\"message\" : \"ok\"}", new JsonConfig());
        }
    };
}
 
Example #18
Source Project: jmeter-bzm-plugins   Author: Blazemeter   File: BlazeMeterHttpUtilsEmul.java    License: Apache License 2.0 5 votes vote down vote up
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 #19
Source Project: sonar-quality-gates-plugin   Author: jenkinsci   File: GlobalConfigurationService.java    License: MIT License 5 votes vote down vote up
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 #20
Source Project: sonar-quality-gates-plugin   Author: jenkinsci   File: GlobalConfigurationService.java    License: MIT License 5 votes vote down vote up
protected JSONArray getGlobalConfigsArray(JSON globalDataConfigs) {

        JSONArray array;

        if (globalDataConfigs.isArray()) {
            array = JSONArray.class.cast(globalDataConfigs);
        } else {
            array = createJsonArrayFromObject((JSONObject) globalDataConfigs);
        }

        return array;
    }
 
Example #21
Source Project: sonar-quality-gates-plugin   Author: jenkinsci   File: GlobalConfigurationServiceTest.java    License: MIT License 5 votes vote down vote up
@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 #22
Source Project: pipeline-utility-steps-plugin   Author: jenkinsci   File: ReadJSONStepExecution.java    License: MIT License 5 votes vote down vote up
@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 #23
Source Project: pipeline-utility-steps-plugin   Author: jenkinsci   File: WriteJSONStepTest.java    License: MIT License 5 votes vote down vote up
@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 #24
Source Project: zap-extensions   Author: zaproxy   File: WebSocketAPI.java    License: Apache License 2.0 5 votes vote down vote up
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 #25
Source Project: zap-extensions   Author: zaproxy   File: AjaxSpiderAPI.java    License: Apache License 2.0 5 votes vote down vote up
@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 #26
Source Project: zap-extensions   Author: zaproxy   File: HttpPanelJsonView.java    License: Apache License 2.0 5 votes vote down vote up
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 #27
Source Project: phabricator-jenkins-plugin   Author: uber   File: UberallsClient.java    License: MIT License 5 votes vote down vote up
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 #28
Source Project: BotLibre   Author: BotLibre   File: Wikidata.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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 #29
Source Project: BotLibre   Author: BotLibre   File: Google.java    License: Eclipse Public License 1.0 5 votes vote down vote up
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 #30
Source Project: APICloud-Studio   Author: apicloudcom   File: Feature.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String ConvertXMLtoJSON(String xml)  {  
	XMLSerializer xmlSerializer = new XMLSerializer();  
	JSON json =null;
	  
       json = xmlSerializer.read(xml);  
	return json.toString(1);  
}