net.minidev.json.JSONValue Java Examples

The following examples show how to use net.minidev.json.JSONValue. 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: Iso8601MessageParser.java    From secor with Apache License 2.0 6 votes vote down vote up
@Override
public long extractTimestampMillis(final Message message) {
    JSONObject jsonObject = (JSONObject) JSONValue.parse(message.getPayload());
    Object fieldValue = jsonObject != null ? getJsonFieldValue(jsonObject) : null;

    if (m_timestampRequired && fieldValue == null) {
        throw new RuntimeException("Missing timestamp field for message: " + message);
    }

    if (fieldValue != null) {
        try {
            Date dateFormat = DatatypeConverter.parseDateTime(fieldValue.toString()).getTime();
            return dateFormat.getTime();
        } catch (IllegalArgumentException ex) {
            if (m_timestampRequired){
                throw new RuntimeException("Bad timestamp field for message: " + message);
            }
        }
    }

    return 0;
}
 
Example #2
Source File: DateMessageParser.java    From secor with Apache License 2.0 6 votes vote down vote up
@Override
public String[] extractPartitions(Message message) {
    JSONObject jsonObject = (JSONObject) JSONValue.parse(message.getPayload());
    String result[] = { defaultDate };

    if (jsonObject != null) {
        Object fieldValue = getJsonFieldValue(jsonObject);
        if (fieldValue != null && inputPattern != null) {
            try {
                Date dateFormat = inputFormatter.parse(fieldValue.toString());
                result[0] = mDtPrefix + outputFormatter.format(dateFormat);
            } catch (Exception e) {
                LOG.warn("Impossible to convert date = {} with the input pattern = {}. Using date default = {}",
                         fieldValue.toString(), inputPattern.toString(), result[0]);
            }
        }
    }

    return result;
}
 
Example #3
Source File: TestUpdater.java    From json-smart-v2 with Apache License 2.0 6 votes vote down vote up
public void testUpdateExistingBeans() throws Exception {
	T123 t123 = new T123();
	T1 t1 = new T1(); 
	T2 t2 = new T2(); 
	T3 t3 = new T3(); 
	t123.t1 = t1;
	t123.t2 = t2;
	t123.t3 = t3;
	
	String s = "{\"t2\":{\"name\":\"valueT2\"},\"t3\":{\"name\":\"valueT3\"},}";
	T123 res = JSONValue.parse(s, t123);
	assertEquals(res, t123);
	assertEquals(res.t2, t2);
	assertEquals(res.t2.name, "valueT2");
	assertEquals(res.t3.name, "valueT3");
}
 
Example #4
Source File: MCDownloadOnlineVersionList.java    From mclauncher-api with MIT License 6 votes vote down vote up
@Override
public void startDownload() throws Exception {
    // at first, we download the complete version list
    String jsonString = HttpUtils.httpGet(JSONVERSION_LIST_URL);
    JSONObject versionInformation = (JSONObject) JSONValue.parse(jsonString);
    JSONArray versions = (JSONArray) versionInformation.get("versions");

    versionsToUrlMap = new HashMap<>();
    // and then, for each version...
    for (Object object : versions) {
        JSONObject versionObject = (JSONObject) object;
        String id = versionObject.get("id").toString();
        versionsToUrlMap.put(id, versionObject.get("url").toString());
        notifyObservers(id);
    }
}
 
Example #5
Source File: CompessorMapper.java    From json-smart-v2 with Apache License 2.0 6 votes vote down vote up
private void writeValue(Object value) throws IOException {
		if (value instanceof String) {
			compression.writeString(out, (String) value);
//
//			if (!compression.mustProtectValue((String) value))
//				out.append((String) value);
//			else {
//				out.append('"');
//				JSONValue.escape((String) value, out, compression);
//				out.append('"');
//			}
			// needSep = true;
		} else {
			if (isCompressor(value)) {
				close(value);
				// needSep = true;
			} else {
				JSONValue.writeJSONString(value, out, compression);
				// needSep = true;
			}
		}
	}
 
Example #6
Source File: MCDResourcesInstaller.java    From mclauncher-api with MIT License 6 votes vote down vote up
/**
 * Installs resources for given version
 * @param version Version to install resources for
 * @param progress ProgressMonitor
 * @throws Exception Connection and I/O errors
 */
void installAssetsForVersion(MCDownloadVersion version, IProgressMonitor progress) throws Exception {
    // let's see which asset index is needed by this version
    Artifact index = version.getAssetIndex();
    String indexName = version.getAssetsIndexName();
    MCLauncherAPI.log.fine("Installing asset index ".concat(indexName));
    File indexDest = new File(indexesDir, indexName + ".json");
    // download this asset index
    if (!indexDest.exists() || indexDest.length() == 0)
        FileUtils.downloadFileWithProgress(index.getUrl(), indexDest, progress);
    // parse it from JSON
    FileReader fileReader = new FileReader(indexDest);
    JSONObject jsonAssets = (JSONObject) JSONValue.parse(fileReader);
    fileReader.close();
    AssetIndex assets = AssetIndex.fromJson(indexName, jsonAssets);
    // and download individual assets inside it
    downloadAssetList(assets, progress);
    MCLauncherAPI.log.fine("Finished installing asset index ".concat(indexName));
}
 
Example #7
Source File: TestMisc.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testBool() throws Exception {
	String s = "{\"key1\":\"v1\", \"key2\":{}, \"key3\":[]}";
	JSONObject o = (JSONObject) JSONValue.parseWithException(s);

	assertEquals(o.get("key1"), "v1");
	assertEquals(((JSONObject) o.get("key2")).size(), 0);
	assertEquals(((JSONArray) o.get("key3")).size(), 0);
}
 
Example #8
Source File: ArrayWriter.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public <E> void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException {
	compression.arrayStart(out);
	boolean needSep = false;
	for (Object o : ((Object[]) value)) {
		if (needSep)
			compression.objectNext(out);
		else
			needSep = true;
		JSONValue.writeJSONString(o, out, compression);
	}
	compression.arrayStop(out);
}
 
Example #9
Source File: TestMisc.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testEmptyStrict() throws Exception {
	String s = "{\"key1\":\"v1\", \"key2\":{}, \"key3\":[]}";
	JSONObject o = (JSONObject) JSONValue.parseStrict(s);

	assertEquals(o.get("key1"), "v1");
	assertEquals(((JSONObject) o.get("key2")).size(), 0);
	assertEquals(((JSONArray) o.get("key3")).size(), 0);
}
 
Example #10
Source File: YDLoginService.java    From mclauncher-api with MIT License 5 votes vote down vote up
private YDLoginResponse doCheckedLoginPost(String url, IJSONSerializable req) throws YDServiceAuthenticationException {
      String jsonString = doLoginPost(url, req);

JSONObject jsonObject = (JSONObject)JSONValue.parse(jsonString);
      YDLoginResponse response = new YDLoginResponse(jsonObject);
      
      if(response.getError() != null) {
          MCLauncherAPI.log.fine("Login response error. JSON STRING: '".concat(jsonString).concat("'"));
	throw new YDServiceAuthenticationException("Authentication Failed: " + response.getMessage(),
			new LoginException("Error ".concat(response.getError()).concat(" : ").concat(response.getMessage())));

      }
      return response;
  }
 
Example #11
Source File: CompessorMapper.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
private void startKey(String key) throws IOException {
	addComma();
	// if (key == null)
	// return;
	if (isArray())
		return;
	if (!compression.mustProtectKey(key))
		out.append(key);
	else {
		out.append('"');
		JSONValue.escape(key, out, compression);
		out.append('"');
	}
	out.append(':');
}
 
Example #12
Source File: TestFieldRename.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testRemap() throws Exception {
	String text = "{'new':'foo','default':'bar'}";
	JSONValue.remapField(TRen.class, "default", "default_");
	JSONValue.remapField(TRen.class, "new", "new_");

	TRen t = JSONValue.parse(text, TRen.class);
	assertEquals(t.new_, "foo");
	assertEquals(t.default_, "bar");
	String dest = JSONValue.toJSONString(t);
	assertTrue(dest.contains("\"default\""));

}
 
Example #13
Source File: PathRemoverTest.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
@Parameterized.Parameters
public static Collection<Object[]> params() {
	return Arrays.asList(new Object[][]{
			{null,                                                             "key",                    null                                             }, // null json
			{"{}",                                                             "key",                    "{}"                                             }, // empty json
			{"{\"first\": null}",                                              null,                     "{\"first\": null}"                              }, // null key
			{"{\"first\": null}",                                              "",                       "{\"first\": null}"                              }, // empty string key
			{"{\"first\": null}",                                              new String[]{},           "{\"first\": null}"                              }, // empty string array key
			{"{\"first\": null}",                                              new JSONArray(),          "{\"first\": null}"                              }, // empty json array key
			{"{\"first\": null}",                                              new ArrayList<String>(0), "{\"first\": null}"                              }, // empty list key
			{"{\"first\": null}",                                              "first",                  "{}"                                             }, // remove root key
			{"{\"first.f1\": null}",                                           "first.f1",               "{}"                                             }, // key with dot
			{"{\"first.f1\": \"withDot\", \"first\":{\"f1\": null}}",          "first.f1",               "{\"first\":{}}"                                 }, //9 key with dot ambiguity
			{"{\"first\":{\"f2\":{\"f3\":{\"id\":\"id1\"}}}}",                 "first.f2.f3.id",         "{\"first\":{\"f2\":{\"f3\":{}}}}"               }, // nested object remove single leaf
			{"{\"first\":{\"f2\":{\"f3\":{\"id\":\"id1\"}}}}",                 "notfound",               "{\"first\":{\"f2\":{\"f3\":{\"id\":\"id1\"}}}}" }, // nested object key does not exist
			{"{\"first\":{\"f2\":{\"f3\":{\"id\":\"id1\",\"name\":\"me\"}}}}", "first.f2.f3.id",         "{\"first\":{\"f2\":{\"f3\":{\"name\":\"me\"}}}}"}, // nested object remove first leaf
			{"{\"first\":{\"f2\":{\"f3\":{\"id\":\"id1\",\"name\":\"me\"}}}}", "first.f2.f3.name",       "{\"first\":{\"f2\":{\"f3\":{\"id\":\"id1\"}}}}" }, //13 nested object remove last leaf
			{"{\"first\":{\"f2\":{\"f3\":{\"id\":\"id1\",\"name\":\"me\"}}}}", "first.f2.f3",            "{\"first\":{\"f2\":{}}}"                        }, // nested object remove intermediate node
			{"{\"first\":{\"f2\":{\"f3\":{\"id\":\"id1\",\"name\":\"me\"}}}}", "first",                  "{}"                                             }, // nested object remove root
			{"{\"first\":{\"f2\":[[1,{\"id\":\"id1\"},3],4]}}",                "first.f2.id",            "{\"first\":{\"f2\":[[1,{},3],4]}}"              }, // double nested array remove leaf
			{"{\"first\":{\"f2\":[[1,{\"id\":\"id1\"},3],4]}}",                "first.f2",               "{\"first\":{}}"                                 }, // double nested array remove array
			{"{\"first\":[[1,{\"id\":\"id1\"},3],4]}",                         "first",                  "{}"                                             }, // double nested array remove root

			//arrays
			{"{\"k0\":{\"k1\":[1,{\"k2\":\"v2\"},3,4]}}",                    "k0.k1",                    "{\"k0\":{}}"                                    }, // value is array
			{"{\"k0\":{\"k1\":[1,{\"k2\":\"v2\"},3,4]}}",                    "k0.k1.k2",                 "{\"k0\":{\"k1\":[1,{},3,4]}}"                   }, // full path into array object
			{"{\"k0\":{\"k1\":[1,{\"k2\":\"v2\"},3,4]}}",                    "k0.k1.3" ,                 "{\"k0\":{\"k1\":[1,{\"k2\":\"v2\"},3,4]}}"      }, // full path into array primitive
			{"{\"k0\":{\"k1\":[1,{\"k2\":\"v2\"},{\"k2\":\"v2\"},3,4]}}",    "k0.k1.k2",                 "{\"k0\":{\"k1\":[1,{},{},3,4]}}"                }, // full path into array with identical items

			// composite json remove all roots
			{"{\"first\": {\"f2\":{\"id\":\"id1\"}}, \"second\": [{\"k1\":{\"id\":\"id1\"}}, 4, 5, 6, {\"id\": 123}], \"third\": 789, \"id\": null}",
					(JSONArray) JSONValue.parse("[\"first\",\"second\",\"third\",\"id\"]"),
					"{}" },
			// composite json remove all leaves
			{"{\"first\": {\"f2\":{\"id\":\"id1\"}}, \"second\": [{\"k1\":{\"id\":\"id1\"}}, 4, 5, 6, {\"id\": 123}], \"third\": 789, \"id\": null}",
					(List<String>) Arrays.asList("first.f2.id", "second.k1.id", "second.id", "third", "id"),
					"{\"first\": {\"f2\":{}}, \"second\": [{\"k1\":{}}, 4, 5, 6, {}]}" },

	});
}
 
Example #14
Source File: MCDownloadOnlineVersionList.java    From mclauncher-api with MIT License 5 votes vote down vote up
@Override
public IVersion retrieveVersionInfo(String id) throws Exception{
    if (null == versionsToUrlMap) {
        startDownload();
    }

    String fullVersionJSONString = HttpUtils.httpGet(versionsToUrlMap.get(id));
    JSONObject fullVersionObject = (JSONObject) JSONValue.parse(fullVersionJSONString);
    // ,create a MCDownloadVersion based on it
    MCDownloadVersion version = MCDownloadVersion.fromJson(fullVersionObject);
    return version;
}
 
Example #15
Source File: CatalogRestUtils.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates a JSON string for the Difference statements in the specified RDF format. Key "additions" has value of the
 * Difference's addition statements and key "deletions" has value of the Difference's deletion statements.
 *
 * @param difference   The Difference to convert into a JSONObject.
 * @param format       A String representing the RDF format to return the statements in.
 * @param transformer  The {@link SesameTransformer} to use.
 * @param bNodeService The {@link BNodeService} to use.
 * @return A JSONObject with a key for the Difference's addition statements and a key for the Difference's deletion
 * statements.
 */
public static String getDifferenceJsonString(Difference difference, String format, SesameTransformer transformer,
                                             BNodeService bNodeService) {
    String additions = modelToSkolemizedString(difference.getAdditions(), format, transformer, bNodeService);
    String deletions = modelToSkolemizedString(difference.getDeletions(), format, transformer, bNodeService);


    return "{ \"additions\": "
            + (format.toLowerCase().contains("json") ? additions : "\"" + JSONValue.escape(additions) + "\"")
            + ", \"deletions\": "
            + (format.toLowerCase().contains("json") ? deletions : "\"" + JSONValue.escape(deletions) + "\"")
            + " }";

}
 
Example #16
Source File: KeysPrintActionTest.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws ParseException {
	KeysPrintAction p = new KeysPrintAction();
	JSONTraverser t = new JSONTraverser(p);
	
	String data ="{" +
			"'k0':{" +
			"'k01':{" +
				"'k011':'v2'" +
			"}" +
		"}," +
		"'k1':{" +
			"'k11':{" +
				"'k111':'v5'" +
			"}," +
			"'k12':{" +
				"'k121':'v5'" +
			"}" +
		"}," +
		"'k3':{" +
			"'k31':{" +
				"'k311':'v5'" +
			"}" +
		"}" +
	"}";
	JSONObject jo = (JSONObject) JSONValue.parseWithException(data.replace("'", "\""));
	t.traverse(jo);
}
 
Example #17
Source File: TestUtf8.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testString() throws Exception {
	for (String nonLatinText : nonLatinTexts) {
		String s = "{\"key\":\"" + nonLatinText + "\"}";
		JSONObject obj = (JSONObject) JSONValue.parse(s);
		String v = (String) obj.get("key"); // result is incorrect
		assertEquals(v, nonLatinText);
	}
}
 
Example #18
Source File: TestNumberPrecision.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testMaxBig() {
	BigInteger v = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE);
	String s = "[" + v + "]";
	JSONArray array = (JSONArray) JSONValue.parse(s);
	Object r = array.get(0);
	assertEquals(v, r);
}
 
Example #19
Source File: TestNumberPrecision.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testMaxLong() {		
	Long v = Long.MAX_VALUE;
	String s = "[" + v + "]";
	JSONArray array = (JSONArray) JSONValue.parse(s);
	Object r = array.get(0);
	assertEquals(v, r);
}
 
Example #20
Source File: TestZeroLead.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void test0Float() throws Exception {
	String s = "[00.0]";
	// strict
	MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_LEADING_0);
	// PERMISIVE
	JSONValue.parseWithException(s);
}
 
Example #21
Source File: TestInvalidNumber.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testF4() {
	String test = "51ee88";
	JSONObject o = new JSONObject();
	o.put("a", test);
	String comp = JSONValue.toJSONString(o, JSONStyle.MAX_COMPRESS);
	assertEquals("{a:51ee88}", comp);
	
	o = JSONValue.parse(comp, JSONObject.class);
	assertEquals(o.get("a"), test);
}
 
Example #22
Source File: TestNumberPrecision.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testMinBig() {
	BigInteger v = BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE);
	String s = "[" + v + "]";
	JSONArray array = (JSONArray) JSONValue.parse(s);
	Object r = array.get(0);
	assertEquals(v, r);
}
 
Example #23
Source File: TestBigValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * test BigInteger serialization
 */
public void testBigInteger() {
	HashMap<String, Object> map = new HashMap<String, Object>();
	BigInteger bigInt = new BigInteger(bigStr);
	map.put("big", bigInt);
	String test = JSONValue.toJSONString(map);
	String result = "{\"big\":" + bigStr + "}";
	assertEquals(result, test);
	JSONObject obj =  (JSONObject)JSONValue.parse(test);
	assertEquals(bigInt, obj.get("big"));
	assertEquals(bigInt.getClass(), obj.get("big").getClass());
}
 
Example #24
Source File: PathLocatorTest.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws ParseException
{
	JSONObject objectToSearch = jsonToSearch != null ? (JSONObject) JSONValue.parseWithException(jsonToSearch) : null;
	PathLocator locator = switchKeyToRemove();
	List<String> found = locator.locate(objectToSearch);
	assertEquals(Arrays.asList(expectedFound), found);
}
 
Example #25
Source File: PathReplicatorTest.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void test2() throws Exception {
	JSONObject objectSource = jsonSource != null ? (JSONObject) JSONValue.parseWithException(jsonSource) : null;
	PathReplicator copier = switchKeyToCopy2();
	JSONObject copied = copier.replicate(objectSource);
	JSONObject expectedObj = expected != null ? (JSONObject) JSONValue.parseWithException((String) expected) : null;
	assertEquals(expectedObj, copied);
}
 
Example #26
Source File: TestMapPublic.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testObjMixtePrim() throws Exception {
	T3 r = JSONValue.parse(MultiTyepJson, T3.class);
	assertEquals("B", r.name);
	assertEquals(Short.valueOf((short) 120), r.age);
	assertEquals(Integer.valueOf(12000), r.cost);
	assertEquals(Byte.valueOf((byte) 3), r.flag);
	assertEquals(Boolean.TRUE, r.valid);
	assertEquals(1.2F, r.f);
	assertEquals(1.5, r.d);
	assertEquals(Long.valueOf(12345678912345L), r.l);
}
 
Example #27
Source File: TestCustomMappingInstant.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void test_dummy() throws IOException {
	@SuppressWarnings("unused")
	ParseException e = null;
	
	JSONValue.toJSONString(true, JSONStyle.MAX_COMPRESS);
	//Assert.assertEquals(true, true);
}
 
Example #28
Source File: TestUpdater.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testUpdate1() throws Exception {
	T3 t3 = new T3();
	t3.age = 20;
	t3.f = 1.4f;
	t3.l = 120000L;

	String s = "{\"name\":\"text\"}";
	T3 t3_1 = JSONValue.parse(s, t3);
	assertEquals(t3, t3_1);
	assertEquals("text", t3.name);
	assertEquals((Long) 120000L, t3.l);
}
 
Example #29
Source File: TestMapPublic.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testObjMixte() throws Exception {
	T2 r = JSONValue.parse(MultiTyepJson, T2.class);
	assertEquals("B", r.name);
	assertEquals(120, r.age);
	assertEquals(12000, r.cost);
	assertEquals(3, r.flag);
	assertEquals(true, r.valid);
	assertEquals(1.2F, r.f);
	assertEquals(1.5, r.d);
	assertEquals(12345678912345L, r.l);
}
 
Example #30
Source File: YDProfileIO.java    From mclauncher-api with MIT License 5 votes vote down vote up
@Override
public IProfile[] read() throws Exception {
    FileReader fileReader = new FileReader(dest);
    JSONObject root = (JSONObject) JSONValue.parse(fileReader);
    fileReader.close();

    JSONObject authDatabase = (JSONObject) root.get("authenticationDatabase");
    IProfile[] result = new IProfile[authDatabase.size()];
    int i = 0;
    for (String key : authDatabase.keySet()) {
        result[i] = new YDAuthProfile((JSONObject) authDatabase.get(key));
        ++i;
    }
    return result;
}