Java Code Examples for net.minidev.json.JSONValue#parse()

The following examples show how to use net.minidev.json.JSONValue#parse() . 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: 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 2
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 3
Source File: TestInvalidNumber.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testF1() {
	String test = "51e88";
	JSONObject o = new JSONObject();
	o.put("a", test);
	String comp = JSONValue.toJSONString(o, JSONStyle.MAX_COMPRESS);
	assertEquals("{a:\"51e88\"}", comp);

	o = JSONValue.parse(comp, JSONObject.class);
	assertEquals(o.get("a"), test);
}
 
Example 4
Source File: YDLoginService.java    From mclauncher-api with MIT License 5 votes vote down vote up
public void loadFrom(File file) throws Exception {
    FileReader fileReader = new FileReader(file);
    JSONObject obj = (JSONObject) JSONValue.parse(fileReader);
    fileReader.close();
    clientToken = UUID.fromString(obj.get("clientToken").toString());
    MCLauncherAPI.log.fine("Loaded client token: " + clientToken.toString());
}
 
Example 5
Source File: TestInvalidNumber.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testF2() {
	String test = "51e+88";
	JSONObject o = new JSONObject();
	o.put("a", test);
	String comp = JSONValue.toJSONString(o, JSONStyle.MAX_COMPRESS);
	assertEquals("{a:\"51e+88\"}", comp);

	o = JSONValue.parse(comp, JSONObject.class);
	assertEquals(o.get("a"), test);
}
 
Example 6
Source File: TestNumberPrecision.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testMinLong() {
	Long v = Long.MIN_VALUE;
	String s = "[" + v + "]";
	JSONArray array = (JSONArray) JSONValue.parse(s);
	Object r = array.get(0);
	assertEquals(v, r);
}
 
Example 7
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 8
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 9
Source File: ServerPinger.java    From mclauncher-api with MIT License 5 votes vote down vote up
public ServerPingResult call() throws Exception {
    ServerPingResult result = null;
    // open a connection
    InetSocketAddress addr = InetSocketAddress.createUnresolved(server.getIP(), server.getPort());
    Socket socket = SocketFactory.getDefault().createSocket();
    socket.connect(addr);
    // get streams
    InputStream is = socket.getInputStream();
    DataInputStream dis = new DataInputStream(is);
    OutputStream os = socket.getOutputStream();


    // send data
    os.write(pingPacketFactory.createPingPacket(server));
    // wait for data
    while (is.available() == 0) {
        Thread.sleep(20l);
    }


    // receive data
    byte zero = dis.readByte();
    if (zero != 0) {
        return new ServerPingResult(new RuntimeException("Outdated protocol!"));
    }
    String jsonString = dis.readUTF();
    result = new ServerPingResult(new JSONPingedServerInfo47((JSONObject)JSONValue.parse(jsonString), server.getIP(), server.getName(), server.getPort()));
    socket.close();
    return null;
}
 
Example 10
Source File: TestCompressorFlags.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void test4Web() throws Exception {
	String NProtectValue = "{\"k\":\"http:\\/\\/url\"}";
	
	JSONObject obj = (JSONObject) JSONValue.parse(NProtectValue);

	String r = obj.toJSONString(JSONStyle.MAX_COMPRESS);
	assertEquals("{k:\"http://url\"}", r);
	
	r = obj.toJSONString(JSONStyle.LT_COMPRESS);
	assertEquals("{\"k\":\"http://url\"}", r);

	r = obj.toJSONString(JSONStyle.NO_COMPRESS);
	assertEquals("{\"k\":\"http:\\/\\/url\"}", r);
}
 
Example 11
Source File: TestUtf8.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testBytes() throws Exception {
	for (String nonLatinText : nonLatinTexts) {
		String s = "{\"key\":\"" + nonLatinText + "\"}";
		byte[] bs = s.getBytes("utf8");
		JSONObject obj = (JSONObject) JSONValue.parse(bs);
		String v = (String) obj.get("key"); // result is incorrect
		assertEquals(v, nonLatinText);
	}
}
 
Example 12
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 13
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 14
Source File: EncryptionUtils.java    From Protocol with Apache License 2.0 5 votes vote down vote up
/**
 * Verify the validity of the login chain data from the {@link com.nukkitx.protocol.bedrock.packet.LoginPacket}
 *
 * @param chain array of JWS objects
 * @return chain validity
 * @throws JOSEException            invalid JWS algorithm used
 * @throws ParseException           invalid JWS object
 * @throws InvalidKeySpecException  invalid EC key provided
 * @throws NoSuchAlgorithmException runtime does not support EC spec
 */
public static boolean verifyChain(JSONArray chain) throws JOSEException, ParseException, InvalidKeySpecException, NoSuchAlgorithmException {
    ECPublicKey lastKey = null;
    boolean validChain = false;
    for (Object node : chain) {
        Preconditions.checkArgument(node instanceof String, "Chain node is not a string");
        JWSObject jwt = JWSObject.parse((String) node);

        if (lastKey == null) {
            validChain = verifyJwt(jwt, MOJANG_PUBLIC_KEY);
        } else {
            validChain = verifyJwt(jwt, lastKey);
        }

        if (!validChain) {
            break;
        }

        Object payload = JSONValue.parse(jwt.getPayload().toString());
        Preconditions.checkArgument(payload instanceof JSONObject, "Payload is not a object");

        Object identityPublicKey = ((JSONObject) payload).get("identityPublicKey");
        Preconditions.checkArgument(identityPublicKey instanceof String, "identityPublicKey node is missing in chain");
        lastKey = generateKey((String) identityPublicKey);
    }
    return validChain;
}
 
Example 15
Source File: TestMapPublic.java    From json-smart-v2 with Apache License 2.0 4 votes vote down vote up
public void testObjInts() throws Exception {
	String s = "{\"vint\":[1,2,3]}";
	T1 r = JSONValue.parse(s, T1.class);
	assertEquals(3, r.vint[2]);
}
 
Example 16
Source File: TestMapPublic2.java    From json-smart-v2 with Apache License 2.0 4 votes vote down vote up
public void testMapPublicInterface() throws Exception {
	T5 r = JSONValue.parse(s, T5.class);
	assertEquals(1, r.data.size());
}
 
Example 17
Source File: TestMapPrimArrays.java    From json-smart-v2 with Apache License 2.0 4 votes vote down vote up
public void testInts() throws Exception {
	String s = "[1,2,3]";
	int[] r = JSONValue.parse(s, int[].class);
	assertEquals(3, r[2]);
}
 
Example 18
Source File: GoogleGeocodeService.java    From c4sg-services with MIT License 4 votes vote down vote up
@Override
public Map<String, BigDecimal> getGeoCode(String state, String country) throws Exception {
	
	Map<String,BigDecimal> geocode = new HashMap<String,BigDecimal>();
	
	// validate input
	if(country != null && !country.isEmpty()) {
		StringBuilder address = new StringBuilder();
		if (state != null && !state.isEmpty()) {
			address.append(state);
			address.append(",");
		}
		String countryCode = CountryCodeConverterUtil.convertToIso2(country);
		address.append(countryCode);
		
		try {
			URL url = getRequestUrl(address.toString());
			String response = getResponse(url);
			if(response != null) {
				Object obj = JSONValue.parse(response);
				
				if(obj instanceof JSONObject) {
					JSONObject jsonObject = (JSONObject) obj;
					JSONArray array = (JSONArray) jsonObject.get("results");					
					JSONObject element = (JSONObject) array.get(0);
					JSONObject geometry = (JSONObject) element.get("geometry");
					JSONObject location = (JSONObject) geometry.get("location");
					Double lng = (Double) location.get("lng");
					Double lat = (Double) location.get("lat");
					geocode.put("lng", new BigDecimal(lng));
					geocode.put("lat", new BigDecimal(lat));
				}
				return geocode;				
			} else {
				throw new Exception("Fail to convert to geocode");
			}
		}
		catch(Exception ex) {
			throw new Exception(ex.getMessage());
			
		}
		
	}
	
	return geocode;
}
 
Example 19
Source File: TestMapPrimArrays.java    From json-smart-v2 with Apache License 2.0 4 votes vote down vote up
public void testLongs() throws Exception {
	String s = "[1,2,3]";
	long[] r = JSONValue.parse(s, long[].class);
	assertEquals(3, r[2]);
}
 
Example 20
Source File: TestMapBeans.java    From json-smart-v2 with Apache License 2.0 4 votes vote down vote up
public void testObjInts() throws Exception {
	String s = "{\"vint\":[1,2,3]}";
	T1 r = JSONValue.parse(s, T1.class);
	assertEquals(3, r.vint[2]);
}