net.minidev.json.parser.JSONParser Java Examples

The following examples show how to use net.minidev.json.parser.JSONParser. 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: PyLint.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
int initialize() {
    JSONParser parser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);

    try {
        JSONArray elements = (JSONArray) parser.parse(PyLint.class.getResourceAsStream("pylint-descriptions.json"));
        for (Object element : elements) {
            JSONObject object = (JSONObject) element;
            String description = object.getAsString("description");
            descriptionByName.put(object.getAsString("name"), description);
            descriptionById.put(object.getAsString("code"), description);
        }
    }
    catch (ParseException | UnsupportedEncodingException ignored) {
        // ignore all exceptions
    }

    return descriptionByName.size();
}
 
Example #2
Source File: XsuaaServicesParser.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
@Nullable
private static JSONObject parseCredentials(String vcapServices) throws IOException {
	if (vcapServices == null || vcapServices.isEmpty()) {
		logger.warn("VCAP_SERVICES could not be load.");
		return null;
	}
	try {
		JSONObject vcapServicesJSON = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(vcapServices);
		JSONObject xsuaaBinding = searchXsuaaBinding(vcapServicesJSON);

		if (Objects.nonNull(xsuaaBinding) && xsuaaBinding.containsKey(CREDENTIALS)) {
			return (JSONObject) xsuaaBinding.get(CREDENTIALS);
		}
	} catch (ParseException ex) {
		throw new IOException("Error while parsing XSUAA credentials from VCAP_SERVICES: {}.", ex);
	}
	return null;
}
 
Example #3
Source File: TokenUtil.java    From microservice-with-jwt-and-microprofile with Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to generate a JWT string from a JSON resource file that is signed by the privateKey-pkcs1.pem
 * test resource key, possibly with invalid fields.
 *
 * @param jsonResName   - name of test resources file
 * @param invalidClaims - the set of claims that should be added with invalid values to test failure modes
 * @param timeClaims    - used to return the exp, iat, auth_time claims
 * @return the JWT string
 * @throws Exception on parse failure
 */
public static String generateTokenString(String jsonResName, Set<InvalidClaims> invalidClaims, Map<String, Long> timeClaims) throws Exception {
    if (invalidClaims == null) {
        invalidClaims = Collections.emptySet();
    }
    final InputStream contentIS = TokenUtil.class.getResourceAsStream(jsonResName);
    byte[] tmp = new byte[4096];
    int length = contentIS.read(tmp);
    byte[] content = new byte[length];
    System.arraycopy(tmp, 0, content, 0, length);

    JSONParser parser = new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE);
    JSONObject jwtContent = (JSONObject) parser.parse(content);

    return generateTokenString(jwtContent, invalidClaims, timeClaims);
}
 
Example #4
Source File: ListTopologiesRequest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
protected List<String> parseResourceNames(BasicResponse response) throws Exception {
  List<String> result = new ArrayList<>();
  JSONObject json = (JSONObject) new JSONParser(0).parse(response.getBytes());
  if (json != null) {
    JSONObject topologies = (JSONObject) json.get("topologies");
    if (topologies != null) {
      JSONArray items = (JSONArray) topologies.get("topology");
      if (items != null) {
        for (Object item1 : items) {
          JSONObject item = (JSONObject) item1;
          String name = (String) item.get("name");
          if (name != null) {
            result.add(name);
          }
        }
      }
    }
  }
  return result;
}
 
Example #5
Source File: PicaReaderTest.java    From metadata-qa-marc with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
private Map<String, List<PicaTagDefinition>> readSchema(JSONParser parser, String fileName) throws IOException, URISyntaxException, ParseException {
  Map<String, List<PicaTagDefinition>> map = new HashMap<>();

  Path tagsFile = FileUtils.getPath(fileName);
  Object obj = parser.parse(new FileReader(tagsFile.toString()));
  JSONObject jsonObject = (JSONObject) obj;
  JSONObject fields = (JSONObject) jsonObject.get("fields");
  for (String name : fields.keySet()) {
    JSONObject field = (JSONObject) fields.get(name);
    // System.err.println(field);
    PicaTagDefinition tag = new PicaTagDefinition(
      (String) field.get("pica3"),
      name,
      (boolean) field.get("repeatable"),
      false,
      (String) field.get("label")
    );
    addTag(map, tag);
  }

  return map;
}
 
Example #6
Source File: Verify.java    From dew with Apache License 2.0 6 votes vote down vote up
/**
 * Verify resource descriptors.
 *
 * @param message      the message
 * @param expectedText the expected text
 * @param actualText   the actual text
 * @throws IOException    the io exception
 * @throws ParseException the parse exception
 */
default void verifyResourceDescriptors(String message, String expectedText, String actualText) throws IOException, ParseException {
    JsonTextMessageValidator validator = new JsonTextMessageValidator();
    validator.setStrict(false);

    TestContext context = new TestContext();
    context.getValidationMatcherRegistry()
            .getValidationMatcherLibraries()
            .add(new ValidationMatcherConfig().getValidationMatcherLibrary());

    validator.validateJson(message,
            (JSONObject) new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE).parse(toJson(actualText)),
            (JSONObject) new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE).parse(toJson(expectedText)),
            new JsonMessageValidationContext(),
            context,
            JsonPath.parse(actualText));
}
 
Example #7
Source File: ListResourcesRequest.java    From knox with Apache License 2.0 6 votes vote down vote up
protected List<String> parseResourceNames(BasicResponse response) throws Exception {
  List<String> result = new ArrayList<>();
  JSONObject json = (JSONObject) new JSONParser(0).parse(response.getBytes());
  if (json != null) {
    JSONArray items = (JSONArray) json.get("items");
    if (items != null) {
      for (Object item1 : items) {
        JSONObject item = (JSONObject) item1;
        String name = (String) item.get("name");
        if (name != null) {
          result.add(name.substring(0, name.lastIndexOf('.')));
        }
      }
    }
  }
  return result;
}
 
Example #8
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Parse input json as a mapTo class
 * 
 * mapTo can be a bean
 * 
 * @since 2.0
 */
public static <T> T parse(InputStream in, T toUpdate) {
	try {
		JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE);
		return p.parse(in, new UpdaterMapper<T>(defaultReader, toUpdate));
	} catch (Exception e) {
		return null;
	}
}
 
Example #9
Source File: TestSpecialChar.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testSpecial127() throws Exception {
	String s127 = String.format("%c", 127); 
	String s = String.format("[\"%c\"]", 127);
	MustThrows.testInvalidJson(s, JSONParser.MODE_STRICTEST, ParseException.ERROR_UNEXPECTED_CHAR);
	
	JSONArray o = (JSONArray) new JSONParser(JSONParser.MODE_RFC4627).parse(s);
	assertEquals(o.get(0), s127);		
}
 
Example #10
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Parse input json as a mapTo class
 * 
 * @since 2.0
 */
protected static <T> T parse(String in, JsonReaderI<T> mapper) {
	try {
		JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE);
		return p.parse(in, mapper);
	} catch (Exception e) {
		return null;
	}
}
 
Example #11
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Parse input json as a mapTo class
 * 
 * @since 2.0
 */
protected static <T> T parse(byte[] in, JsonReaderI<T> mapper) {
	try {
		JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE);
		return p.parse(in, mapper);
	} catch (Exception e) {
		return null;
	}
}
 
Example #12
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Parse input json as a mapTo class
 * 
 * mapTo can be a bean
 * 
 * @since 2.0
 */
public static <T> T parse(String in, T toUpdate) {
	try {
		JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE);
		return p.parse(in, new UpdaterMapper<T>(defaultReader, toUpdate));
	} catch (Exception e) {
		return null;
	}
}
 
Example #13
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Reformat Json input keeping element order
 * 
 * @since 1.0.6.2
 * 
 *        need to be rewrite in 2.0
 */
public static String compress(String input, JSONStyle style) {
	try {
		StringBuilder sb = new StringBuilder();
		new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(input, new CompessorMapper(defaultReader, sb, style));
		return sb.toString();
	} catch (Exception e) {
		return input;
	}
}
 
Example #14
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Parse input json as a mapTo class
 * 
 * mapTo can be a bean
 * 
 * @since 2.0
 */
public static <T> T parse(String in, Class<T> mapTo) {
	try {
		JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE);
		return p.parse(in, defaultReader.getMapper(mapTo));
	} catch (Exception e) {
		return null;
	}
}
 
Example #15
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Parse input json as a mapTo class
 * 
 * @since 2.0
 */
protected static <T> T parse(Reader in, JsonReaderI<T> mapper) {
	try {
		JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE);
		return p.parse(in, mapper);
	} catch (Exception e) {
		return null;
	}
}
 
Example #16
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Parse input json as a mapTo class
 * 
 * mapTo can be a bean
 * 
 * @since 2.0
 */
public static <T> T parse(Reader in, Class<T> mapTo) {
	try {
		JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE);
		return p.parse(in, defaultReader.getMapper(mapTo));
	} catch (Exception e) {
		return null;
	}
}
 
Example #17
Source File: RpcUtil.java    From snowblossom with Apache License 2.0 5 votes vote down vote up
public static JSONObject protoToJson(com.google.protobuf.Message m)
  throws Exception
{
  JsonFormat.Printer printer = JsonFormat.printer();
  String str = printer.print(m);

  JSONParser parser = new JSONParser(JSONParser.MODE_STRICTEST);
  return (JSONObject) parser.parse(str);

}
 
Example #18
Source File: JwtTokenGenerator.java    From microprofile1.4-samples with MIT License 5 votes vote down vote up
public static String generateJWTString(String jsonResource) throws Exception {
    byte[] byteBuffer = new byte[16384];
    currentThread().getContextClassLoader()
                   .getResource(jsonResource)
                   .openStream()
                   .read(byteBuffer);

    JSONParser parser = new JSONParser(DEFAULT_PERMISSIVE_MODE);
    JSONObject jwtJson = (JSONObject) parser.parse(byteBuffer);
    
    long currentTimeInSecs = (System.currentTimeMillis() / 1000);
    long expirationTime = currentTimeInSecs + 1000;
   
    jwtJson.put(Claims.iat.name(), currentTimeInSecs);
    jwtJson.put(Claims.auth_time.name(), currentTimeInSecs);
    jwtJson.put(Claims.exp.name(), expirationTime);
    
    SignedJWT signedJWT = new SignedJWT(new JWSHeader
                                        .Builder(RS256)
                                        .keyID("/privateKey.pem")
                                        .type(JWT)
                                        .build(), parse(jwtJson));
    
    signedJWT.sign(new RSASSASigner(readPrivateKey("privateKey.pem")));
    
    return signedJWT.serialize();
}
 
Example #19
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Parse Json input to a java Object keeping element order
 * 
 * @since 1.0.6.1
 */
public static Object parseKeepingOrder(Reader in) {
	try {
		return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, defaultReader.DEFAULT_ORDERED);
	} catch (Exception e) {
		return null;
	}
}
 
Example #20
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Parse Json input to a java Object keeping element order
 * 
 * @since 1.0.6.1
 */
public static Object parseKeepingOrder(String in) {
	try {
		return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, defaultReader.DEFAULT_ORDERED);
	} catch (Exception e) {
		return null;
	}
}
 
Example #21
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Parse input json as a mapTo class
 * 
 * mapTo can be a bean
 * 
 * @since 2.0
 */
public static <T> T parse(Reader in, T toUpdate) {
	try {
		JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE);
		return p.parse(in, new UpdaterMapper<T>(defaultReader, toUpdate));
	} catch (Exception e) {
		return null;
	}
}
 
Example #22
Source File: TestInts.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testBigInt() throws Exception {
	StringBuilder sb = new StringBuilder();
	for (int i = 0; i < 10; i++)
		sb.append(Integer.MAX_VALUE);
	String bigText = sb.toString();
	BigInteger big = new BigInteger(bigText, 10);
	String s = "{t:" + bigText + "}";
	JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
	assertEquals(o.get("t"), big);
}
 
Example #23
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Check RFC4627 Json Syntax from input Reader
 * 
 * @return if the input is valid
 */
public static boolean isValidJsonStrict(Reader in) throws IOException {
	try {
		new JSONParser(MODE_RFC4627).parse(in, FakeMapper.DEFAULT);
		return true;
	} catch (ParseException e) {
		return false;
	}
}
 
Example #24
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * check RFC4627 Json Syntax from input String
 * 
 * @return if the input is valid
 */
public static boolean isValidJsonStrict(String s) {
	try {
		new JSONParser(MODE_RFC4627).parse(s, FakeMapper.DEFAULT);
		return true;
	} catch (ParseException e) {
		return false;
	}
}
 
Example #25
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Check Json Syntax from input Reader
 * 
 * @return if the input is valid
 */
public static boolean isValidJson(Reader in) throws IOException {
	try {
		new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, FakeMapper.DEFAULT);
		return true;
	} catch (ParseException e) {
		return false;
	}
}
 
Example #26
Source File: JSONValue.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Check Json Syntax from input String
 * 
 * @return if the input is valid
 */
public static boolean isValidJson(String s) {
	try {
		new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(s, FakeMapper.DEFAULT);
		return true;
	} catch (ParseException e) {
		return false;
	}
}
 
Example #27
Source File: TestFloat.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testFloat() throws Exception {
	JSONParser p = new JSONParser(JSONParser.MODE_PERMISSIVE);
	for (String s : TRUE_NUMBERS) {
		String json = "{v:" + s + "}";
		Double val = Double.valueOf(s.trim());
		JSONObject obj = (JSONObject) p.parse(json);
		Object value = obj.get("v");
		assertEquals("Should be parse as double", val, value);
	}
}
 
Example #28
Source File: TestFloat.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testNonFloat() throws Exception {
	JSONParser p = new JSONParser(JSONParser.MODE_PERMISSIVE);
	for (String s : FALSE_NUMBERS) {
		String json = "{v:" + s + "}";
		JSONObject obj = (JSONObject) p.parse(json);
		assertEquals("Should be parse as string", s, obj.get("v"));

		String correct = "{\"v\":\"" + s + "\"}";
		assertEquals("Should be re serialized as", correct, obj.toJSONString());
	}
}
 
Example #29
Source File: TestStrict.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testSEscape() throws Exception {
	String text = "My\r\nTest";
	String text2 = "My\\r\\nTest";
	String s = "{t:'" + text2 + "'}";
	JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
	assertEquals(o.get("t"), text);
}
 
Example #30
Source File: JSONObjectConverter.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Un-serialize an object from a stream.
 * The stream must be close afterward
 *
 * @param r the stream to read
 * @return the resulting object
 * @throws JSONConverterException if the stream cannot be parsed
 */
default E fromJSON(Reader r) throws JSONConverterException {
    try {
        JSONParser p = new JSONParser(JSONParser.MODE_RFC4627);
        Object o = p.parse(r);
        if (!(o instanceof JSONObject)) {
            throw new JSONConverterException("Unable to parse a JSON object");
        }
        return fromJSON((JSONObject) o);
    } catch (ParseException ex) {
        throw new JSONConverterException(ex);
    }
}