org.json.simple.JSONObject Java Examples

The following examples show how to use org.json.simple.JSONObject. 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: Metrics.java    From TAB with Apache License 2.0 6 votes vote down vote up
@Override
protected JSONObject getChartData() throws Exception {
	JSONObject data = new JSONObject();
	JSONObject values = new JSONObject();
	Map<String, int[]> map = callable.call();
	if (map == null || map.isEmpty()) {
		return null;
	}
	boolean allSkipped = true;
	for (Map.Entry<String, int[]> entry : map.entrySet()) {
		if (entry.getValue().length == 0) {
			continue;
		}
		allSkipped = false;
		JSONArray categoryValues = new JSONArray();
		for (int categoryValue : entry.getValue()) {
			categoryValues.add(categoryValue);
		}
		values.put(entry.getKey(), categoryValues);
	}
	if (allSkipped) {
		return null;
	}
	data.put("values", values);
	return data;
}
 
Example #2
Source File: UnitUserCellCRUDTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * セルレベルPROPPATCHをオーナーが違うユニットローカルユニットユーザトークンで実行不可なことを確認.
 * @throws TokenParseException トークンパースエラー
 */
@Test
public final void セルレベルPROPPATCHをオーナーが違うユニットローカルユニットユーザトークンで実行不可なことを確認() throws TokenParseException {
    // アカウントにユニット昇格権限付与
    DavResourceUtils.setProppatch(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME,
            "cell/proppatch-uluut.txt", HttpStatus.SC_MULTI_STATUS);

    // パスワード認証でのユニット昇格
    TResponse res = Http.request("authnUnit/password-uluut.txt")
            .with("remoteCell", Setup.TEST_CELL1)
            .with("username", "account1")
            .with("password", "password1")
            .returns()
            .statusCode(HttpStatus.SC_OK);

    JSONObject json = res.bodyAsJson();
    String uluutString = (String) json.get(OAuth2Helper.Key.ACCESS_TOKEN);

    // アカウントにユニット昇格権限付与
    DavResourceUtils.setProppatch(Setup.TEST_CELL2, uluutString,
            "cell/proppatch-uluut.txt", HttpStatus.SC_FORBIDDEN);
}
 
Example #3
Source File: BasicBroParserTest.java    From metron with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Test
public void testDnsBroMessage() throws ParseException {
	Map rawMessageMap = (Map) jsonParser.parse(dnsBroMessage);
	JSONObject rawJson = (JSONObject) rawMessageMap.get(rawMessageMap.keySet().iterator().next());

	JSONObject broJson = broParser.parse(dnsBroMessage.getBytes(StandardCharsets.UTF_8)).get(0);
	String expectedBroTimestamp = "1402308259.609";
	assertEquals(broJson.get("bro_timestamp"), expectedBroTimestamp);
	String expectedTimestamp = "1402308259609";
	assertEquals(broJson.get("timestamp").toString(), expectedTimestamp);
	assertEquals(broJson.get("ip_src_addr").toString(), rawJson.get("id.orig_h").toString());
	assertEquals(broJson.get("ip_dst_addr").toString(), rawJson.get("id.resp_h").toString());
	assertEquals(broJson.get("ip_src_port").toString(), rawJson.get("id.orig_p").toString());
	assertEquals(broJson.get("ip_dst_port").toString(), rawJson.get("id.resp_p").toString());
	assertTrue(broJson.get("original_string").toString().startsWith(rawMessageMap.keySet().iterator().next().toString().toUpperCase()));

	assertEquals(broJson.get("qtype").toString(), rawJson.get("qtype").toString());
	assertEquals(broJson.get("trans_id").toString(), rawJson.get("trans_id").toString());

	assertTrue(broJson.get("original_string").toString().startsWith("DNS"));
}
 
Example #4
Source File: ResponseUtil.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
public static Object getMessagesFromResponse(String responseStr, String node) {
    Object msgObject = null;
    if (responseStr == null || responseStr.equalsIgnoreCase(""))
        return msgObject;
    try {
        JSONObject responseObj = (JSONObject) JSONValue
                .parseWithException(responseStr);
        if (responseObj != null) {
            JSONObject dataObj = (JSONObject) responseObj
                    .get(ConstantsForTest.DATA);
            if (dataObj != null) {
                msgObject = dataObj.get(node);
            }
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return msgObject;
}
 
Example #5
Source File: UrlEndpoints.java    From SB_Elsinore_Server with MIT License 6 votes vote down vote up
@UrlEndpoint(url = "/toggleaux", help = "Toggle the aux pin for a PID",
parameters = {@Parameter(name = "toggle", value = "The name of the PID to toggle the pin for")})
public Response toggleAux() {
    JSONObject usage = new JSONObject();
    if (parameters.containsKey("toggle")) {
        String pidname = parameters.get("toggle");
        PID tempPID = LaunchControl.findPID(pidname);
        if (tempPID != null) {
            tempPID.toggleAux();
            return new NanoHTTPD.Response(Status.OK, MIME_HTML,
                    "Updated Aux for " + pidname);
        } else {
            BrewServer.LOG.warning("Invalid PID: " + pidname + " provided.");
            usage.put("Error", "Invalid name supplied: " + pidname);
        }
    }

    usage.put("toggle",
            "The name of the PID to toggle the aux output for");
    return new Response(usage.toJSONString());
}
 
Example #6
Source File: JSONCleaner.java    From opensoc-streaming with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes", "unused" })
public static void main(String args[])
{
	String jsonText = "{\"first_1\": 123, \"second\": [4, 5, 6], \"third\": 789}";
	JSONCleaner cleaner = new JSONCleaner();
	try {
		//cleaner.Clean(jsonText);
		Map obj=new HashMap();
		  obj.put("name","foo");
		  obj.put("num",new Integer(100));
		  obj.put("balance",new Double(1000.21));
		  obj.put("is_vip",new Boolean(true));
		  obj.put("nickname",null);
		Map obj1 = new HashMap();
		obj1.put("sourcefile", obj);
		
		JSONObject json = new JSONObject(obj1);
		System.out.println(json);
		  
		  
		  
		  System.out.print(jsonText);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #7
Source File: DigitalSTROMJSONImpl.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String loginApplication(String loginToken) {
    if (loginToken != null && !loginToken.trim().equals("")) {
        String response = null;

        response = transport.execute(JSONRequestConstants.JSON_SYSTEM_LOGIN_APPLICATION + loginToken);

        JSONObject responseObj = handler.toJSONObject(response);

        if (handler.checkResponse(responseObj)) {
            JSONObject obj = handler.getResultJSONObject(responseObj);

            String tokenStr = null;

            if (obj != null && obj.get(JSONApiResponseKeysEnum.SYSTEM_LOGIN.getKey()) != null) {
                tokenStr = obj.get(JSONApiResponseKeysEnum.SYSTEM_LOGIN.getKey()).toString();

            }

            if (tokenStr != null) {
                return tokenStr;
            }
        }
    }
    return null;
}
 
Example #8
Source File: UserDataUtils.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * ユーザーデータに更新を実行し、レスポンスコードをチェックする.
 * @param token トークン
 * @param code 期待するレスポンスコード
 * @return レスポンス
 */
@SuppressWarnings("unchecked")
public static TResponse update(String token, int code) {
    JSONObject body = new JSONObject();
    body.put("__id", "auth_test");
    body.put("prop", "prop");
    TResponse res = Http.request("box/odatacol/update.txt")
            .with("cell", "testcell1")
            .with("box", "box1")
            .with("collection", "setodata")
            .with("entityType", "Price")
            .with("id", "auth_test")
            .with("accept", MediaType.APPLICATION_JSON)
            .with("contentType", MediaType.APPLICATION_JSON)
            .with("token", token)
            .with("ifMatch", "*")
            .with("body", body.toJSONString())
            .returns()
            .statusCode(code)
            .debug();
    return res;
}
 
Example #9
Source File: Metrics.java    From SonarPet with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected JSONObject getChartData() {
    JSONObject data = new JSONObject();
    JSONObject values = new JSONObject();
    HashMap<String, Integer> map = getValues(new HashMap<String, Integer>());
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    boolean allSkipped = true;
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        if (entry.getValue() == 0) {
            continue; // Skip this invalid
        }
        allSkipped = false;
        values.put(entry.getKey(), entry.getValue());
    }
    if (allSkipped) {
        // Null = skip the chart
        return null;
    }
    data.put("values", values);
    return data;
}
 
Example #10
Source File: Metrics.java    From IridiumSkyblock with GNU General Public License v2.0 6 votes vote down vote up
private JSONObject getRequestJsonObject() {
    JSONObject chart = new JSONObject();
    chart.put("chartId", chartId);
    try {
        JSONObject data = getChartData();
        if (data == null) {
            // If the data is null we don't send the chart.
            return null;
        }
        chart.put("data", data);
    } catch (Throwable t) {
        if (logFailedRequests) {
            Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
        }
        return null;
    }
    return chart;
}
 
Example #11
Source File: CommonUtilsTest.java    From fiware-cygnus with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * [CommonUtils.getTimeInstant] -------- When getting a time instant, it is properly obtained when
 * passing a valid SQL timestamp with microseconds.
 */
@Test
public void testGetTimeInstantSQLTimestampWithMicroseconds() {
    System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
            + "-------- When getting a time instant, it is properly obtained when passing a valid "
            + "SQL timestamp with microseconds");
    JSONObject metadataJson = new JSONObject();
    metadataJson.put("name", "TimeInstant");
    metadataJson.put("type", "SQL timestamp");
    metadataJson.put("value", "2017-01-01 00:00:01.123456");
    JSONArray metadatasJson = new JSONArray();
    metadatasJson.add(metadataJson);
    String metadatasStr = metadatasJson.toJSONString();
    Long timeInstant = CommonUtils.getTimeInstant(metadatasStr);

    try {
        assertTrue(timeInstant != null);
        System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
                + "-  OK  - Time instant obtained for '" + metadatasJson.toJSONString() + "' is '"
                + timeInstant + "'");
    } catch (AssertionError e) {
        System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
                + "- FAIL - Time instant obtained is 'null'");
        throw e;
    } // try catch
}
 
Example #12
Source File: ServiceInfo.java    From sepia-assist-server with MIT License 6 votes vote down vote up
/**
 * Add a custom trigger sentence for a given language to the collection with predefined parameters, e.g. "Bring me home" with "location=home". 
 * If the service registers itself as a custom services this will be used.
 * @param sentence - a sample sentence
 * @param language - language code for this sentence
 * @param normParameters - predefined parameters for this sentence in normalized format (not extracted yet)
 */
public ServiceInfo addCustomTriggerSentenceWithNormalizedParameters(String sentence, String language, JSONObject normParameters){
	List<String> list = customTriggerSentences.get(language);
	if (list == null){
		list = new ArrayList<>();
		customTriggerSentences.put(language, list);
	}
	//tag parameters
	for (Object keyObj : normParameters.keySet()){
		String key = (String) keyObj;
		JSON.put(normParameters, key, Interview.INPUT_NORM + JSON.getString(normParameters, key));
	}
	//build sentence + cmdSummary
	sentence = sentence + ";;" + Converters.makeCommandSummary(this.intendedCommand, normParameters);
	list.add(sentence);
	return this;
}
 
Example #13
Source File: InternalEsClient.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * 非同期でドキュメントを検索. <br />
 * Queryの指定方法をMapで直接記述せずにQueryBuilderにするため、非推奨とする.
 * @param index インデックス名
 * @param routingId routingId
 * @param query クエリ情報
 * @return 非同期応答
 */
public ActionFuture<SearchResponse> asyncSearch(
        String index,
        String routingId,
        Map<String, Object> query) {
    SearchRequest req = new SearchRequest(index).searchType(SearchType.DEFAULT);
    if (query != null) {
        req.source(query);
    }
    if (routingFlag) {
        req = req.routing(routingId);
    }
    ActionFuture<SearchResponse> ret = esTransportClient.search(req);
    this.fireEvent(Event.afterRequest, index, null, null, JSONObject.toJSONString(query), "Search");
    return ret;
}
 
Example #14
Source File: PropertyUtils.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * Propertyを更新する.
 * @param token トークン
 * @param cell セル名
 * @param box ボックス名
 * @param collection コレクション名
 * @param srcPropertyName 更新前Property名
 * @param srcEntityTypeName 更新前EntityType名
 * @param propertyName リクエストに指定するProperty名
 * @param entityTypeName リクエストに指定するEntityType名
 * @param type PropertyのType項目
 * @param nullable PropertyのNullable項目
 * @param defaultValue PropertyのDefaultValue項目
 * @param collectionKind PropertyのcollectionKind項目
 * @param isKey PropertyのisKey項目
 * @param uniqueKey PropertyのUniqueKey項目
 * @return レスポンス
 */
@SuppressWarnings("unchecked")
public static DcResponse update(
        String token, String cell, String box,
        String collection, String srcPropertyName,
        String srcEntityTypeName, String propertyName,
        String entityTypeName, String type, Boolean nullable, Object defaultValue,
        String collectionKind, Boolean isKey, String uniqueKey) {

    // リクエストボディの組み立て
    JSONObject body = new JSONObject();
    body.put("Name", propertyName);
    body.put("_EntityType.Name", entityTypeName);
    body.put("Type", type);
    body.put("Nullable", nullable);
    body.put("DefaultValue", defaultValue);
    body.put("CollectionKind", collectionKind);
    body.put("IsKey", isKey);
    body.put("UniqueKey", uniqueKey);

    return update(token, cell, box, collection, srcPropertyName, srcEntityTypeName, body);

}
 
Example #15
Source File: Syslog3164ParserTest.java    From metron with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadMultiLineWithErrors() throws Exception {
  Syslog3164Parser parser = new Syslog3164Parser();
  Map<String, Object> config = new HashMap<>();
  parser.configure(config);
  StringBuilder builder = new StringBuilder();
  builder
          .append("HEREWEGO!!!!\n")
          .append(SYSLOG_LINE_ALL)
          .append("\n")
          .append(SYSLOG_LINE_MISSING)
          .append("\n")
          .append("BOOM!\n")
          .append(SYSLOG_LINE_ALL)
          .append("\nOHMY!");
  Optional<MessageParserResult<JSONObject>> output = parser.parseOptionalResult(builder.toString().getBytes(
      StandardCharsets.UTF_8));
  assertTrue(output.isPresent());
  assertEquals(3,output.get().getMessages().size());
  assertEquals(3,output.get().getMessageThrowables().size());
}
 
Example #16
Source File: MojangUtil.java    From VoxelGamesLibv2 with MIT License 6 votes vote down vote up
/**
 * Tries to fetch the current display name for the user
 *
 * @param id the id of the user to check
 * @return the current display name of that user
 * @throws IOException           if something goes wrong
 * @throws VoxelGameLibException if the user has no display name
 */
@Nonnull
public static String getDisplayName(@Nonnull UUID id) throws IOException, VoxelGameLibException {
    URL url = new URL(NAME_HISTORY_URL.replace("%1", id.toString().replace("-", "")));
    System.out.println(url.toString());
    Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(url.openStream())));
    if (scanner.hasNext()) {
        String json = scanner.nextLine();
        try {
            JSONArray jsonArray = (JSONArray) new JSONParser().parse(json);
            if (json.length() > 0) {
                return (String) ((JSONObject) jsonArray.get(0)).get("name");
            }
        } catch (ParseException ignore) {
        }
    }

    throw new VoxelGameLibException("User has no name! " + id);
}
 
Example #17
Source File: Redis.java    From AntiVPN with MIT License 6 votes vote down vote up
public void loadMCLeaksValues(Set<RawMCLeaksResult> values, boolean truncate) throws StorageException {
    try (Jedis redis = pool.getResource()) {
        if (truncate) {
            deleteNamespace(redis, prefix + "mcleaks_values:");
        }
        long max = 0;
        for (RawMCLeaksResult r : values) {
            max = Math.max(max, r.getID());
            JSONObject obj = new JSONObject();
            obj.put("playerID", r.getLongPlayerID());
            obj.put("result", r.getValue());
            obj.put("created", r.getCreated());

            redis.set(prefix + "mcleaks_values:" + r.getID(), obj.toJSONString());

            obj.remove("playerID");
            obj.put("id", r.getID());
            redis.rpush(prefix + "mcleaks_values:player:" + r.getLongPlayerID(), obj.toJSONString());
        }
        redis.set(prefix + "mcleaks_values:idx", String.valueOf(max));
    } catch (JedisException ex) {
        throw new StorageException(isAutomaticallyRecoverable(ex), ex);
    }
}
 
Example #18
Source File: WorldIO.java    From TerraLegion with MIT License 6 votes vote down vote up
public static Player loadPlayer() {
	try {
		FileHandle handle = Gdx.files.external("player.save");
		if (!handle.exists()) {
			// not saved player yet
			return null;
		}

		String JSONString = handle.readString();

		JSONObject playerInfo = (JSONObject) new JSONParser().parse(JSONString);

		JSONObject playerPosition = (JSONObject) playerInfo.get("playerPosition");
		Player player = new Player(Float.parseFloat(playerPosition.get("x").toString()), Float.parseFloat(playerPosition.get("y").toString()));

		JSONObject jsonInventory = (JSONObject) playerInfo.get("playerInventory");

		Inventory inventory = JSONConverter.getInventoryFromJSON(jsonInventory);

		player.setInventory(inventory);
		return player;
	} catch(ParseException ex) {
		ex.printStackTrace();
	}
	return null;
}
 
Example #19
Source File: CloudHarmonyCrawler.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
private void crawlComputeOfferings() {
    /* iaas section */
    String computeQuery = "https://cloudharmony.com/api/services?"
            + "api-key=" + API_KEY + "&"
            + "serviceTypes=compute";

    JSONObject resp = (JSONObject) query(computeQuery);

    if(resp == null) {
        return;
    }

    JSONArray computes = (JSONArray) resp.get("ids");

    Iterator<String> it = computes.iterator();
    while (it.hasNext()) {
        try {
            String serviceId = it.next();
            CloudHarmonyService chService = getService(serviceId, CloudTypes.IAAS);
            if (chService != null)
                generateOfferings(chService);
        } catch(Exception ex) {
            log.warn(ex.getMessage());
        }
    }
}
 
Example #20
Source File: PaasifyCrawler.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @return an array of offerings successfully translated into SeaClouds offering format
 */
private void getOfferings() {

    File offeringsDirectory = new File(paasifyRepositoryDirecory + "/profiles");

    for (File offerFile : offeringsDirectory.listFiles()) {
        try {
            if (offerFile.isFile() && isJSON(offerFile)) {
                FileReader fr = new FileReader(offerFile);
                JSONObject obj =(JSONObject) jsonParser.parse(fr);
                Offering offering = getOfferingFromJSON(obj);
                fr.close();

                if (offering != null)
                    addOffering(offering);
            }
        } catch (IOException ioe) {
            log.error("IOException");
            log.error(ioe.getMessage());
        } catch (ParseException pe) {
            log.error("ParseException");
            log.error(pe.getMessage());
        }
    }
}
 
Example #21
Source File: OAuthMediator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method returns the OAuthEndpointSecurity Properties from the API Manager Configuration
 * @return JSONObject OAuthEndpointSecurity properties
 */
public JSONObject getOAuthEndpointSecurityProperties() {
    APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance()
            .getAPIManagerConfigurationService().getAPIManagerConfiguration();
    String tokenRefreshInterval = configuration.getFirstProperty(APIConstants
            .OAuthConstants.OAUTH_TOKEN_REFRESH_INTERVAL);

    JSONObject configProperties = new JSONObject();

    if (StringUtils.isNotEmpty(tokenRefreshInterval)) {
        configProperties.put(APIConstants.OAuthConstants.TOKEN_REFRESH_INTERVAL, tokenRefreshInterval);
        return configProperties;
    }
    return null;
}
 
Example #22
Source File: UserDataListTopSkipTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * $skipに0を指定してUserDataの一覧をした場合に200となること.
 */
@SuppressWarnings("unchecked")
@Test
public final void $skipに0を指定してUserDataの一覧をした場合に200となること() {
    // リクエストボディを設定
    String userDataId = "userdata001";
    JSONObject body = new JSONObject();
    body.put("__id", userDataId);

    // リクエスト実行
    try {
        // ユーザデータ作成
        TResponse respons = createUserData(body, HttpStatus.SC_CREATED);

        Map<String, String> etagList = new HashMap<String, String>();
        etagList.put("userdata001", respons.getHeader(HttpHeaders.ETAG));

        // ユーザデータの一覧取得
        TResponse response = Http.request("box/odatacol/list.txt")
                .with("cell", cellName)
                .with("box", boxName)
                .with("collection", colName)
                .with("entityType", entityTypeName)
                .with("query", "?\\$skip=0")
                .with("accept", MediaType.APPLICATION_JSON)
                .with("token", DcCoreConfig.getMasterToken())
                .returns()
                .statusCode(HttpStatus.SC_OK)
                .debug();

        JSONArray results = (JSONArray) ((JSONObject) response.bodyAsJson().get("d")).get("results");
        assertEquals(1, results.size());
    } finally {
        // ユーザデータ削除
        deleteUserData(userDataId);
    }
}
 
Example #23
Source File: FractionOfTotalField.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
@Override
public JSONObject jsonValueForSubject(Subject subject, Boolean timeStamp) throws IncomputableFieldException {
    ValueWithTimestamp valueWithTimestamp = getValue(subject);
    JSONObject obj = new JSONObject();
    if (null != timeStamp && !timeStamp) {
        obj.put(null != this.label ? this.label : "value", valueWithTimestamp.value);
        return withinJsonStructure(obj);
    }
    obj.put("timestamp", valueWithTimestamp.timestamp.format(TimedValueId.DATE_TIME_FORMATTER));
    obj.put("value", valueWithTimestamp.value);
    return withinJsonStructure(obj);
}
 
Example #24
Source File: MetronError.java    From metron with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
private void addStacktrace(JSONObject errorMessage) {
  if (throwable != null) {
    String stackTrace = ExceptionUtils.getStackTrace(throwable);
    String exception = throwable.toString();
    errorMessage.put(ErrorFields.EXCEPTION.getName(), exception);
    errorMessage.put(ErrorFields.STACK.getName(), stackTrace);
  }
}
 
Example #25
Source File: StatusRecorder.java    From SB_Elsinore_Server with MIT License 5 votes vote down vote up
/**
 * Compare two generic objects.
 *
 * @param previousValue First object to check
 * @param currentValue Second object to check
 * @return True if the objects are different, false if the same.
 */
protected final boolean compare(final Object previousValue,
        final Object currentValue) {
    if (previousValue == null && currentValue == null) {
        return true;
    }

    if (previousValue == null || currentValue == null) {
        return false;
    }

    if (previousValue instanceof JSONObject
            && currentValue instanceof JSONObject) {
        if (isDifferent((JSONObject) previousValue,
                (JSONObject) currentValue)) {
            return true;
        }
    } else if (previousValue instanceof JSONArray
            && currentValue instanceof JSONArray) {
        if (isDifferent((JSONArray) previousValue,
                (JSONArray) currentValue)) {
            return true;
        }
    } else {
        if (!previousValue.equals(currentValue)) {
            return true;
        }
    }

    return false;
}
 
Example #26
Source File: MetricsProvider.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
public static PageMetrics getMetrics(Har<?, ?> har, int i, String harName,
        PerformanceReport.Report r) {
    PageMetrics metrics;
    switch (getProvider()) {
        default:
            metrics = new PageSpeed(((JSONObject) har.log().pages.get(0)).
                    get("title").toString() + " " + harName,
                    r.savedHars.get(harName).get(i), H_PS_EXE);
            break;
    }
    return metrics;
}
 
Example #27
Source File: UserDataBatchWithNPTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * $batchでNavPro経由でのGETができないこと.
 */
@Test
@SuppressWarnings("unchecked")
public final void $batchでNavPro経由でのGETができないこと() {
    try {
        JSONObject srcBody = new JSONObject();
        srcBody.put("__id", "srcKey");
        srcBody.put("Name", "key0001");
        super.createUserData(srcBody, HttpStatus.SC_CREATED, cellName, boxName, colName, "Sales");
        String body = START_BOUNDARY
                + retrieveListBody("Sales('srcKey')/_Product")
                + START_BOUNDARY + retrievePostBody("Sales('srcKey')/_Product('id0001')", "id0001")
                + START_BOUNDARY + retrieveGetBody("Sales('srcKey')/_Product('id0001')")
                + START_BOUNDARY + retrievePutBody("Sales('srcKey')/_Product('id0001')")
                + START_BOUNDARY + retrieveDeleteBody("Sales('srcKey')/_Product('id0001')")
                + END_BOUNDARY;
        TResponse response = Http.request("box/odatacol/batch.txt")
                .with("cell", cellName)
                .with("box", boxName)
                .with("collection", colName)
                .with("boundary", BOUNDARY)
                .with("token", DcCoreConfig.getMasterToken())
                .with("body", body)
                .returns()
                .debug()
                .statusCode(HttpStatus.SC_ACCEPTED);

        // レスポンスボディのチェック
        String expectedBody = START_BOUNDARY
                + retrieveQueryOperationResErrorBody(HttpStatus.SC_NOT_IMPLEMENTED)
                + START_BOUNDARY + retrieveChangeSetResErrorBody(HttpStatus.SC_BAD_REQUEST)
                + START_BOUNDARY + retrieveQueryOperationResErrorBody(HttpStatus.SC_BAD_REQUEST)
                + START_BOUNDARY + retrieveChangeSetResErrorBody(HttpStatus.SC_BAD_REQUEST)
                + START_BOUNDARY + retrieveChangeSetResErrorBody(HttpStatus.SC_BAD_REQUEST)
                + END_BOUNDARY;
        checkBatchResponseBody(response, expectedBody);
    } finally {
        deleteUserData(cellName, boxName, colName, "Sales", "srcKey", DcCoreConfig.getMasterToken(), -1);
    }
}
 
Example #28
Source File: LevelLoader.java    From ud406 with MIT License 5 votes vote down vote up
private static void loadPlatforms(JSONArray array, Level level) {

        Array<Platform> platformArray = new Array<Platform>();

        for (Object object : array) {
            final JSONObject platformObject = (JSONObject) object;

            final float x = safeGetFloat(platformObject, Constants.LEVEL_X_KEY);
            final float y = safeGetFloat(platformObject, Constants.LEVEL_Y_KEY);
            final float width = ((Number) platformObject.get(Constants.LEVEL_WIDTH_KEY)).floatValue();
            final float height = ((Number) platformObject.get(Constants.LEVEL_HEIGHT_KEY)).floatValue();

            Gdx.app.log(TAG,
                    "Loaded a platform at x = " + x + " y = " + (y + height) + " w = " + width + " h = " + height);

            final Platform platform = new Platform(x, y + height, width, height);
            platformArray.add(platform);

            final String identifier = (String) platformObject.get(Constants.LEVEL_IDENTIFIER_KEY);
            if (identifier != null && identifier.equals(Constants.LEVEL_ENEMY_TAG)) {
                Gdx.app.log(TAG, "Loaded an enemy on that platform");
                final Enemy enemy = new Enemy(platform);
                level.getEnemies().add(enemy);
            }
        }

        platformArray.sort(new Comparator<Platform>() {
            @Override
            public int compare(Platform o1, Platform o2) {
                if (o1.top < o2.top) {
                    return 1;
                } else if (o1.top > o2.top) {
                    return -1;
                }
                return 0;
            }
        });

        level.getPlatforms().addAll(platformArray);
    }
 
Example #29
Source File: Account.java    From Software-Architecture-with-Spring-5.0 with MIT License 5 votes vote down vote up
public Account(EventMetadata accountCreatedEvent) {
    JSONObject jsonObject = accountCreatedEvent.getEventData();
    this.accountId = jsonObject.get("account_id").toString();
    this.customerId = jsonObject.get("customer_id").toString();
    this.balance = Integer.valueOf(jsonObject.get("balance").toString());
    this.type = jsonObject.get("account_type").toString();
}
 
Example #30
Source File: CIFHbaseAdapter.java    From metron with Apache License 2.0 5 votes vote down vote up
@Override
public JSONObject enrich(CacheKey k) {
	String metadata = k.coerceValue(String.class);
	JSONObject output = new JSONObject();
	LOGGER.debug("=======Looking Up For: {}", metadata);
	output.putAll(getCIFObject(metadata));

	return output;
}