net.sf.json.JSONSerializer Java Examples

The following examples show how to use net.sf.json.JSONSerializer. 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: ipst   Author: itesla   File: OnlineDbMVStoreUtils.java    License: Mozilla Public License 2.0 6 votes vote down vote up
public static LimitViolation jsonToLimitViolation(String json, Network network) {
    JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(json);
    Map<String, String> limitViolation = (Map<String, String>) JSONObject.toBean(jsonObj, Map.class);
    float limitReduction = 1f;
    if (limitViolation.containsKey("LimitReduction")) {
        limitReduction = Float.parseFloat(limitViolation.get("LimitReduction"));
    }
    LimitViolationType limitType = LimitViolationType.valueOf(limitViolation.get("LimitType"));
    Branch.Side side = limitType == LimitViolationType.CURRENT ? Branch.Side.ONE : null;
    if (limitViolation.containsKey("Side")) {
        side =  Branch.Side.valueOf(limitViolation.get("Side"));
    }
    return new LimitViolation(limitViolation.get("Subject"),
            limitType,
            limitViolation.get("LimitName"),
            Integer.MAX_VALUE,
            Float.parseFloat(limitViolation.get("Limit")),
            limitReduction,
            Float.parseFloat(limitViolation.get("Value")),
            side);
}
 
Example #3
Source Project: gogs-webhook-plugin   Author: jenkinsci   File: GogsConfigHandler.java    License: MIT License 6 votes vote down vote up
/**
 * Creates a web hook in Gogs with the passed json configuration string
 *
 * @param jsonCommand A json buffer with the creation command of the web hook
 * @param projectName the project (owned by the user) where the webHook should be created
 * @throws IOException something went wrong
 */
int createWebHook(String jsonCommand, String projectName) throws IOException {

    String gogsHooksConfigUrl = getGogsServer_apiUrl()
            + "repos/" + this.gogsServer_user
            + "/" + projectName + "/hooks";

    Executor executor = getExecutor();
    Request request = Request.Post(gogsHooksConfigUrl);

    if (gogsAccessToken != null) {
        request.addHeader("Authorization", "token " + gogsAccessToken);
    }

    String result = executor
            .execute(request.bodyString(jsonCommand, ContentType.APPLICATION_JSON))
            .returnContent().asString();
    JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( result );
    return jsonObject.getInt("id");
}
 
Example #4
Source Project: jenkins-parallels   Author: Parallels   File: ParallelsDesktopConnectorSlaveComputer.java    License: MIT License 6 votes vote down vote up
public boolean checkVmExists(String vmId)
{
	try
	{
		RunVmCallable command = new RunVmCallable("list", "-i", "--json");
		String callResult = forceGetChannel().call(command);
		JSONArray vms = (JSONArray)JSONSerializer.toJSON(callResult);
		for (int i = 0; i < vms.size(); i++)
		{
			JSONObject vmInfo = vms.getJSONObject(i);
			if (vmId.equals(vmInfo.getString("ID")) || vmId.equals(vmInfo.getString("Name")))
				return true;
		}
		return true;
	}
	catch (Exception ex)
	{
		LOGGER.log(Level.SEVERE, ex.toString());
	}
	return false;
}
 
Example #5
Source Project: jenkins-parallels   Author: Parallels   File: ParallelsDesktopConnectorSlaveComputer.java    License: MIT License 6 votes vote down vote up
private String getVmIPAddress(String vmId) throws Exception
{
	int TIMEOUT = 60;
	for (int i = 0; i < TIMEOUT; ++i)
	{
		RunVmCallable command = new RunVmCallable("list", "-f", "--json", vmId);
		String callResult = forceGetChannel().call(command);
		LOGGER.log(Level.SEVERE, " - (" + i + "/" + TIMEOUT + ") calling for IP");
		LOGGER.log(Level.SEVERE, callResult);
		JSONArray vms = (JSONArray)JSONSerializer.toJSON(callResult);
		JSONObject vmInfo = vms.getJSONObject(0);
		String ip = vmInfo.getString("ip_configured");
		if (!ip.equals("-"))
			return ip;
		Thread.sleep(1000);
	}
	throw new Exception("Failed to get IP for VM '" + vmId + "'");
}
 
Example #6
Source Project: BotLibre   Author: BotLibre   File: LoginBean.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public void confirmBCPayment(String json) {
	try {
		JSONObject object = (JSONObject)JSONSerializer.toJSON(json);
		String id = object.getJSONObject("order").getString("custom");
		this.payment = AdminDatabase.instance().findUserPayment(Long.valueOf(id));
		this.payment.setStatus(UserPaymentStatus.Complete);
		this.payment.setType(UserPaymentType.BitCoin);
		this.payment.setBitCoinJSON(json);
		this.user = AdminDatabase.instance().updatePayment(this.payment);
		this.user.setType(this.payment.getUserType());
		this.user.setUpgradeDate(new Date());
		this.user = AdminDatabase.instance().updateUser(this.user, null, true, null);
		this.payment = null;
	} catch (Exception exception) {
		error(exception);
	}
}
 
Example #7
Source Project: BotLibre   Author: BotLibre   File: Telegram.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Call a generic Telegram web API.
 */
public Vertex postJSON(String url, Vertex paramsObject, Network network) {
	log("POST JSON:", Level.INFO, url);
	try {
		Map<String, String> params = getBot().awareness().getSense(Http.class).convertToMap(paramsObject);
		String json = Utils.httpPOST("https://api.telegram.org/bot" + this.token + "/" + url, params);
		log("JSON", Level.FINE, json);
		JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim());
		if (root == null) {
			return null;
		}
		Vertex object = getBot().awareness().getSense(Http.class).convertElement(root, network);
		return object;
	} catch (Exception exception) {
		this.errors++;
		log(exception);
	}
	return null;
}
 
Example #8
Source Project: BotLibre   Author: BotLibre   File: Slack.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public void processSlackEvent(String json) {
	JSONObject root = (JSONObject)JSONSerializer.toJSON(json);
	JSONObject event = root.getJSONObject("event");
	String token = root.getString("token");
	
	if(event.getString("type").equals("message")) {
		String user = event.getString("user");
		String channel = event.getString("channel");
		String text = event.getString("text");
		
		String reply = this.processMessage(null, user, channel, text, token);
		
		if (reply == null || reply.isEmpty()) {
			return;
		}
		
		String data = "token=" + this.appToken;
		data += "&channel=" + channel;
		data += "&text=" + "@" + user + " " + reply;
		
		this.callSlackWebAPI("chat.postMessage", data);
	}
}
 
Example #9
Source Project: BotLibre   Author: BotLibre   File: Skype.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Retrieves access token for bot
 */
protected void getAccessToken() throws Exception {
	String url = "https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token";

	String type = "application/x-www-form-urlencoded";
	String data = "grant_type=client_credentials&client_id=" + appId + "&client_secret=" + appPassword + "&scope=https%3A%2F%2Fapi.botframework.com%2F.default";
	String json = Utils.httpPOST(url, type, data);
	
	JSONObject root = (JSONObject)JSONSerializer.toJSON(json);
	
	if(root.optString("token_type").equals("Bearer")) {
		int tokenExpiresIn = root.optInt("expires_in");
		String accessToken = root.optString("access_token");
		
		setToken(accessToken);
		this.tokenExpiry = new Date(System.currentTimeMillis() + (tokenExpiresIn * 1000));
		
		log("Skype access token retrieved.", Level.INFO);
	} else {
		log("Skype get access token failed:", Level.INFO);
	}
	
	saveProperties();
}
 
Example #10
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 #11
Source Project: BotLibre   Author: BotLibre   File: Http.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Return the count of the JSON result array.
 */
public int countJSON(String url, String attribute, Network network) {
	log("COUNT JSON", Level.INFO, url, attribute);
	try {
		String json = Utils.httpGET(url);
		log("JSON", Level.FINE, json);
		JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim());
		if (root == null) {
			return 0;
		}
		Object value = root.get(attribute);
		if (value == null) {
			return 0;
		}
		if (value instanceof JSONArray) {
			return ((JSONArray)value).size();
		}
		return 1;
	} catch (Exception exception) {
		log(exception);
		return 0;
	}
}
 
Example #12
Source Project: BotLibre   Author: BotLibre   File: Http.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * POST the JSON object and return the JSON data from the URL.
 */
public Vertex postJSON(String url, Vertex jsonObject, Map<String, String> headers, Network network) {
	log("POST JSON", Level.INFO, url);
	try {
		String data = convertToJSON(jsonObject);
		log("POST JSON", Level.FINE, data);
		String json = Utils.httpPOST(url, "application/json", data, headers);
		log("JSON", Level.FINE, json);
		JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim());
		if (root == null) {
			return null;
		}
		Vertex object = convertElement(root, network);
		return object;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}
 
Example #13
Source Project: BotLibre   Author: BotLibre   File: Http.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * PUT the JSON object and return the JSON data from the URL.
 */
public Vertex putJSON(String url, Vertex jsonObject, Network network) {
	log("PUT JSON", Level.INFO, url);
	try {
		String data = convertToJSON(jsonObject);
		log("PUT JSON", Level.FINE, data);
		String json = Utils.httpPUT(url, "application/json", data);
		log("JSON", Level.FINE, json);
		JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim());
		if (root == null) {
			return null;
		}
		Vertex object = convertElement(root, network);
		return object;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}
 
Example #14
Source Project: BotLibre   Author: BotLibre   File: Http.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Post the JSON object and return the JSON data from the URL.
 */
public Vertex postJSONAuth(String url, String user, String password, Vertex jsonObject, Network network) {
	log("POST JSON Auth", Level.INFO, url);
	try {
		String data = convertToJSON(jsonObject);
		log("POST JSON", Level.FINE, data);
		String json = Utils.httpAuthPOST(url, user, password, "application/json", data);
		log("JSON", Level.FINE, json);
		JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim());
		if (root == null) {
			return null;
		}
		Vertex object = convertElement(root, network);
		return object;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}
 
Example #15
Source Project: BotLibre   Author: BotLibre   File: Http.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Post the JSON object and return the JSON data from the URL.
 */
public Vertex postJSONAuth(String url, String user, String password, String agent, Vertex jsonObject, Network network) {
	log("POST JSON Auth", Level.INFO, url);
	try {
		String data = convertToJSON(jsonObject);
		log("POST JSON", Level.FINE, data);
		String json = Utils.httpAuthPOST(url, user, password, agent, "application/json", data);
		log("JSON", Level.FINE, json);
		JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim());
		if (root == null) {
			return null;
		}
		Vertex object = convertElement(root, network);
		return object;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}
 
Example #16
Source Project: BotLibre   Author: BotLibre   File: Http.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * GET the JSON data from the URL.
 */
public Vertex requestJSONAuth(String url, String user, String password, Network network) {
	log("GET JSON Auth", Level.INFO, url);
	try {
		String json = Utils.httpAuthGET(url, user, password);
		log("JSON", Level.FINE, json);
		JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim());
		if (root == null) {
			return null;
		}
		Vertex object = convertElement(root, network);
		return object;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}
 
Example #17
Source Project: BotLibre   Author: BotLibre   File: Http.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * GET the JSON data from the URL.
 */
public Vertex requestJSONAuth(String url, String user, String password, String agent, Network network) {
	log("GET JSON Auth", Level.INFO, url);
	try {
		String json = Utils.httpAuthGET(url, user, password, agent);
		log("JSON", Level.FINE, json);
		JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim());
		if (root == null) {
			return null;
		}
		Vertex object = convertElement(root, network);
		return object;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}
 
Example #18
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 #19
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 #20
Source Project: gerrit-events   Author: sonyxperiadev   File: GerritJsonEventFactory.java    License: MIT License 6 votes vote down vote up
/**
 * Tries to parse the provided string into a JSONObject and returns it if it is interesting and usable.
 * If it is interesting is determined by:
 * <ol>
 *  <li>The object contains a String field named type</li>
 *  <li>The String returns a non null GerritEventType from
 *      {@link GerritEventType#findByTypeValue(java.lang.String) }</li>
 *  <li>The property {@link GerritEventType#isInteresting() } == true</li>
 * </ol>
 * It is usable if the type's {@link GerritEventType#getEventRepresentative() } is not null.
 * @param jsonString the string to parse.
 * @return an interesting and usable JSONObject, or null if it is not.
 */
public static JSONObject getJsonObjectIfInterestingAndUsable(String jsonString) {
    logger.trace("finding event for jsonString: {}", jsonString);
    if (jsonString == null || jsonString.length() <= 0) {
        return null;
    }
    try {
        JSONObject jsonObject = (JSONObject)JSONSerializer.toJSON(jsonString);
        logger.debug("Parsed a JSONObject");
        if (isInterestingAndUsable(jsonObject)) {
            return jsonObject;
        }
    } catch (Exception ex) {
        logger.warn("Unanticipated error when examining JSON String", ex);
    }
    return null;
}
 
Example #21
Source Project: gerrit-events   Author: sonyxperiadev   File: GerritQueryHandler.java    License: MIT License 6 votes vote down vote up
/**
 * Runs the query and returns the result as a list of Java JSONObjects.
 * @param queryString the query.
 * @param getPatchSets getPatchSets if all patch-sets of the projects found should be included in the result.
 *                      Meaning if --patch-sets should be appended to the command call.
 * @param getCurrentPatchSet if the current patch-set for the projects found should be included in the result.
 *                          Meaning if --current-patch-set should be appended to the command call.
 * @param getFiles if the files of the patch sets should be included in the result.
 *                          Meaning if --files should be appended to the command call.
 * @param getCommitMessage if full commit message should be included in the result.
 *                          Meaning if --commit-message should be appended to the command call.
 * @param getComments if patchset comments should be included in the results.
 *                          Meaning if --comments should be appended to the command call.
 *
 * @return the query result as a List of JSONObjects.
 * @throws GerritQueryException if Gerrit reports an error with the query.
 * @throws SshException if there is an error in the SSH Connection.
 * @throws IOException for some other IO problem.
 */
public List<JSONObject> queryJava(String queryString, boolean getPatchSets, boolean getCurrentPatchSet,
                                  boolean getFiles, boolean getCommitMessage, boolean getComments)
        throws SshException, IOException, GerritQueryException {

    final List<JSONObject> list = new LinkedList<JSONObject>();

    runQuery(queryString, getPatchSets, getCurrentPatchSet, getFiles, getCommitMessage, getComments,
            new LineVisitor() {
                @Override
                public void visit(String line) throws GerritQueryException {
                    JSONObject json = (JSONObject)JSONSerializer.toJSON(line.trim());
                    if (json.has("type") && "error".equalsIgnoreCase(json.getString("type"))) {
                        throw new GerritQueryException(json.getString("message"));
                    }
                    list.add(json);
                }
            });
    return list;
}
 
Example #22
Source Project: oodt   Author: apache   File: MetadataResource.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Path(PRODUCT_TYPE+"/elements")
@Produces("text/plain")
public String getElementsForProductType(
  @FormParam("policy") String policy,
  @FormParam("id") String id,
  @FormParam("direct") boolean direct) {
  XMLValidationLayer vLayer = getValidationLayer(policy);
  XMLRepositoryManager xmlRepo = getRepo(policy);
  try {
    ProductType type = xmlRepo.getProductTypeById(id);
    ArrayList<String> elementIds = new ArrayList<String>();
    for(Element el : vLayer.getElements(type, direct)) {
      elementIds.add(el.getElementId());
    }
    return JSONSerializer.toJSON(elementIds).toString();
  } catch (Exception e) {
    LOG.log(Level.SEVERE, e.getMessage());
  }
  return null;
}
 
Example #23
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 #24
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 #25
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 #26
Source Project: jmeter-bzm-plugins   Author: Blazemeter   File: SessionTest.java    License: Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testFlow() throws Exception {
    StatusNotifierCallbackTest.StatusNotifierCallbackImpl notifier = new StatusNotifierCallbackTest.StatusNotifierCallbackImpl();
    BlazeMeterHttpUtilsEmul emul = new BlazeMeterHttpUtilsEmul(notifier, "test_address", "test_data_address", new BlazeMeterReport());

    JSONObject data = new JSONObject();
    data.put("data", "Hello, World!");

    Session session = new Session(emul, "sessionId", "sessionName", "userId", "testId", "testSignature");

    emul.addEmul(JSONSerializer.toJSON("{\"result\":{\"session\":{\"statusCode\":15}}}", new JsonConfig()));
    session.sendData(data);
    assertEquals(1, emul.getRequests().size());
    assertEquals("{\"data\":\"Hello, World!\"}", emul.getRequests().get(0));
    emul.clean();

    emul.addEmul(new JSONObject());
    session.stop();
    assertEquals(1, emul.getRequests().size());
    assertEquals("", emul.getRequests().get(0));
    emul.clean();

    emul.addEmul(new JSONObject());
    session.stopAnonymous();
    assertEquals(1, emul.getRequests().size());
    assertEquals("{\"signature\":\"testSignature\",\"testId\":\"testId\",\"sessionId\":\"sessionId\"}", emul.getRequests().get(0));
    emul.clean();
}
 
Example #27
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 #28
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 #29
Source Project: sonar-quality-gates-plugin   Author: jenkinsci   File: GlobalConfigurationServiceTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testGetGlobalConfigsArrayWhenObject() {
    jsonArray = new JSONArray();
    doReturn(jsonArray).when(spyGlobalConfigurationService).createJsonArrayFromObject(JSONObject.fromObject(globalDataConfigs));
    String objectString = "{\"name\":\"Sonar\",\"url\":\"http://localhost:9000\",\"account\":\"admin\",\"password\":\"admin\"}";
    globalDataConfigs = JSONSerializer.toJSON(objectString);
    jsonArray.add(globalDataConfigs);
    assertEquals(jsonArray, spyGlobalConfigurationService.getGlobalConfigsArray(globalDataConfigs));
}
 
Example #30
Source Project: sonar-quality-gates-plugin   Author: jenkinsci   File: GlobalConfigurationServiceTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testGetGlobalConfigsArrayWhenArray() {
    String arrayString = "[{\"name\":\"Sonar1\",\"url\":\"http://localhost:9000\",\"account\":\"admin\",\"password\":\"admin\"},{\"name\":\"Sonar2\",\"url\":\"http://localhost:9000\",\"account\":\"admin\",\"password\":\"admin\"}]";
    globalDataConfigs = JSONSerializer.toJSON(arrayString);
    jsonArray = JSONArray.class.cast(globalDataConfigs);
    assertEquals(jsonArray, globalConfigurationService.getGlobalConfigsArray(globalDataConfigs));
}