public void mergeProperties(final String properties) { if (StringUtils.isEmpty(properties)) { return; } if (StringUtils.isEmpty(getProperties())) { setProperties(properties); return; } final JsonReaderFactory fact = Json.createReaderFactory(null); final JsonReader r1 = fact.createReader(new StringReader(getProperties())); final JsonObjectBuilder jbf = Json.createObjectBuilder(r1.readObject()); final JsonReader r2 = fact.createReader(new StringReader(getProperties())); final JsonObject obj2 = r2.readObject(); for (Entry<String, JsonValue> jv : obj2.entrySet()) { jbf.add(jv.getKey(), jv.getValue()); } setProperties(jbf.build().toString()); }
public static Map<String, Object> toDictionary(String source) throws JsonParseException { if (source == null) { return null; } JsonObject jsonObject = null; try { JsonReaderFactory factory = Json.createReaderFactory(null); JsonReader jsonReader = factory.createReader(new StringReader(source)); jsonObject = jsonReader.readObject(); jsonReader.close(); } catch (Exception e) { throw new JsonParseException(e); } Map<String, Object> dictionary = new HashMap<String, Object>(); fill_dictionary(dictionary, jsonObject); return dictionary; }
private final List<Speaker> parseSpeaker(URL speakerResource) { try { final JsonReaderFactory factory = Json.createReaderFactory(null); final JsonReader reader = factory.createReader(speakerResource.openStream()); final JsonArray items = reader.readArray(); // parse session objects final List<Speaker> speaker = new LinkedList<>(); for (final JsonValue item : items) { final Speaker s = new Speaker((JsonObject) item); s.setId(String.valueOf(this.speakerId.incrementAndGet())); speaker.add(s); } return speaker; } catch (Exception e) { throw new RuntimeException("Failed to parse speaker.json"); } }
@Test public void testBson () throws IOException { BasicConfigurator.configure (); String f = "../tests/data/data1.bson"; File file = new File (f.replace ('/', File.separatorChar)); JsonPathProvider provider = new JsonPathProvider (); Configuration pathConfig = Configuration.defaultConfiguration ().jsonProvider (provider); JsonPath path = JsonPath.compile ("$..A"); JsonProvider p = new CookJsonProvider (); HashMap<String, Object> readConfig = new HashMap<String, Object> (); readConfig.put (CookJsonProvider.FORMAT, CookJsonProvider.FORMAT_BSON); readConfig.put (CookJsonProvider.ROOT_AS_ARRAY, Boolean.TRUE); JsonReaderFactory rf = p.createReaderFactory (readConfig); JsonReader reader = rf.createReader (new FileInputStream (file)); JsonStructure obj = reader.read (); reader.close (); JsonValue value = path.read (obj, pathConfig); Assert.assertEquals ("[1,3,5,7]", provider.toJson (value)); }
@Override public void execute() throws MojoExecutionException, MojoFailureException { final JsonReaderFactory readerFactory = Json.createReaderFactory(Collections.<String, Object>emptyMap()); if (source.isFile()) { generateFile(readerFactory, source); } else { final File[] children = source.listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { return name.endsWith(".json"); } }); if (children == null || children.length == 0) { throw new MojoExecutionException("No json file found in " + source); } for (final File child : children) { generateFile(readerFactory, child); } } if (attach && project != null) { project.addCompileSourceRoot(target.getAbsolutePath()); } }
@Test public void testGrowingString() throws Throwable { JsonReaderFactory factory = Json.createReaderFactory(null); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10000; i++) { sb.append('x'); String growingString = sb.toString(); String str = "[4, \"\", \"" + growingString + "\", \"\", \"" + growingString + "\", \"\", 400]"; try { JsonReader reader = factory.createReader(new StringReader(str)); JsonArray array = reader.readArray(); assertEquals(4, array.getInt(0)); assertEquals("", array.getString(1)); assertEquals(growingString, array.getString(2)); assertEquals("", array.getString(3)); assertEquals(growingString, array.getString(4)); assertEquals("", array.getString(5)); assertEquals(400, array.getInt(6)); reader.close(); } catch (Throwable t) { throw new Throwable("Failed for growingString with length: " + i, t); } } }
@Override protected TokenValidator createTokenValidator(Map<String, ?> filterConfig) throws UnavailableException { // Pass all of the filter's config to the ReaderFactory factory method. It'll ignore anything it doesn't // understand (per JSR 353). This way, clients can change the provider using the service locator and configure // the ReaderFactory using the filter's config. JsonReaderFactory jsonReaderFactory = JsonProvider.provider().createReaderFactory(filterConfig); WebKeysClient webKeysClient = HttpClientProvider.provider().createWebKeysClient(filterConfig); String audience = FilterHelper.getInitParamValue(InitParams.AUDIENCE, filterConfig); String issuer = FilterHelper.getInitParamValue(InitParams.ISSUER, filterConfig); return _jwtValidator = new JwtValidatorWithJwk(_minKidReloadTimeInSeconds, webKeysClient, audience, issuer, jsonReaderFactory); }
JwkManager(long minKidReloadTimeInSeconds, WebKeysClient webKeysClient, JsonReaderFactory jsonReaderFactory) { _jsonWebKeyByKID = new TimeBasedCache<>(Duration.ofSeconds(minKidReloadTimeInSeconds), this::reload); _webKeysClient = webKeysClient; _jsonReaderFactory = jsonReaderFactory; // invalidate the cache periodically to avoid stale state _executor.scheduleAtFixedRate(this::ensureCacheIsFresh, 5, 15, TimeUnit.MINUTES); }
JwtValidatorWithCert(String issuer, String audience, Map<String, RSAPublicKey> publicKeys, JsonReaderFactory jsonReaderFactory) { super(issuer, audience, jsonReaderFactory); _keys = publicKeys; }
JwtValidatorWithJwk(long minKidReloadTime, WebKeysClient webKeysClient, String audience, String issuer, JsonReaderFactory jsonReaderFactory) { super(issuer, audience, jsonReaderFactory); _jwkManager = new JwkManager(minKidReloadTime, webKeysClient, jsonReaderFactory); }
@Override protected TokenValidator createTokenValidator(Map<String, ?> initParams) throws UnavailableException { // Like in the OAuthJwtFilter, we'll reuse the config of this filter + the service locator to // get a JsonReaderFactory JsonReaderFactory jsonReaderFactory = JsonProvider.provider().createReaderFactory(initParams); IntrospectionClient introspectionClient = HttpClientProvider.provider() .createIntrospectionClient(initParams); return new OpaqueTokenValidator(introspectionClient, jsonReaderFactory); }
@Before public void parseJson() { JsonReaderFactory factory = Json.createReaderFactory(null); InputStream in = LibrariesTest.class.getResourceAsStream("libraries.json"); JsonReader reader = factory.createReader(in); apis = reader.readArray().toArray(new JsonObject[0]); }
@Test public void testJson () throws IOException { BasicConfigurator.configure (); String f = "../tests/data/data3.json"; File file = new File (f.replace ('/', File.separatorChar)); JsonPathProvider provider = new JsonPathProvider (); Configuration pathConfig = Configuration.defaultConfiguration ().jsonProvider (provider); JsonPath path = JsonPath.compile ("$..A"); JsonProvider p = new CookJsonProvider (); HashMap<String, Object> readConfig = new HashMap<String, Object> (); JsonReaderFactory rf = p.createReaderFactory (readConfig); JsonReader reader = rf.createReader (new FileInputStream (file)); JsonStructure obj = reader.read (); reader.close (); JsonValue value = path.read (obj, pathConfig); Assert.assertEquals ("[1,3,5,7]", provider.toJson (value)); }
@Test public void testGrowingStringWithDifferentBufferSizes() throws Throwable { for (int size = 20; size < 500; size++) { final int k = size; Map<String, Object> config = new HashMap<String, Object>() { { put("org.apache.johnzon.default-char-buffer", k); } }; JsonReaderFactory factory = Json.createReaderFactory(config); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100; i++) { sb.append('x'); String name = sb.toString(); String str = "[4, \"\", \"" + name + "\", \"\", \"" + name + "\", \"\", 400]"; try { JsonReader reader = factory.createReader(new StringReader(str)); JsonArray array = reader.readArray(); assertEquals(4, array.getInt(0)); assertEquals("", array.getString(1)); assertEquals(name, array.getString(2)); assertEquals("", array.getString(3)); assertEquals(name, array.getString(4)); assertEquals("", array.getString(5)); assertEquals(400, array.getInt(6)); reader.close(); } catch (Throwable t) { throw new Throwable("Failed for buffer size=" + size + " growingString with length: " + i, t); } } } }
@Override public void contextInitialized(final ServletContextEvent servletContextEvent) { final ClassLoader classLoader = servletContextEvent.getServletContext().getClassLoader(); final JsonReaderFactory reader = newReadFactory(); READER_FACTORY_BY_LOADER.put(classLoader, reader); servletContextEvent.getServletContext().setAttribute(READER_ATTRIBUTE, reader); final JsonWriterFactory writer = newWriterFactory(); WRITER_FACTORY_BY_LOADER.put(classLoader, writer); servletContextEvent.getServletContext().setAttribute(WRITER_ATTRIBUTE, reader); }
public static JsonReaderFactory readerLocate() { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = FactoryLocator.class.getClassLoader(); } final JsonReaderFactory factory = READER_FACTORY_BY_LOADER.get(loader); if (factory == null) { return newReadFactory(); } return factory; }
Mapper(final JsonReaderFactory readerFactory, final JsonGeneratorFactory generatorFactory, MapperConfig config, final Collection<Closeable> closeables) { this.readerFactory = readerFactory; this.generatorFactory = generatorFactory; this.config = config; this.mappings = new Mappings(config); this.readerHandler = ReaderHandler.create(readerFactory); this.closeables = closeables; this.charset = config.getEncoding(); }
OpaqueTokenValidator(IntrospectionClient introspectionClient, JsonReaderFactory jsonReaderFactory) { _introspectionClient = introspectionClient; _tokenCache = new ExpirationBasedCache<>(); _jsonReaderFactory = jsonReaderFactory; }
AbstractJwtValidator(String issuer, String audience, JsonReaderFactory jsonReaderFactory) { _issuer = issuer; _audience = audience; _jsonReaderFactory = jsonReaderFactory; }
static JsonReaderFactory createDefaultReaderFactory() { return JsonProvider.provider().createReaderFactory(Collections.emptyMap()); }
/** * Initializes the factory to be used for creating readers. */ private JsonReaderFactory initReaderFactory() { final Map<String, Object> config = new HashMap<>(); config.put(JOHNZON_SUPPORTS_COMMENTS_PROP, true); return Json.createReaderFactory(config); }
/** * Low level famulus to abstract out some of the HTTP handling common to all requests * * @param url The actual url to httpRequest * @param contentType The value string of the Content-Type header * @param body the body of the POST request * @return the returned JSON object * * @throws CouldNotCreateException * @throws IOException */ private JsonObject penginePost( URL url, String contentType, String body ) throws IOException { StringBuffer response; try { HttpURLConnection con = (HttpURLConnection) url.openConnection(); // above should get us an HttpsURLConnection if it's https://... //add request header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", "JavaPengine"); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); con.setRequestProperty("Content-type", contentType); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); try { wr.writeBytes(body); wr.flush(); } finally { wr.close(); } int responseCode = con.getResponseCode(); if(responseCode < 200 || responseCode > 299) { throw new IOException("bad response code (if 500, query was invalid? query threw Prolog exception?) " + Integer.toString(responseCode) + " " + url.toString() + " " + body); } BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; response = new StringBuffer(); try { while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } finally { in.close(); } JsonReaderFactory jrf = Json.createReaderFactory(null); JsonReader jr = jrf.createReader(new StringReader(response.toString())); JsonObject respObject = jr.readObject(); return respObject; } catch (IOException e) { state.destroy(); throw e; } }
@Override public JsonReaderFactory readerFactory() { return readerFactory; }
public static JsonReaderFactory createReaderFactory(Map<String, ?> config) { return provider.createReaderFactory(config); }
private void generate(final JsonReaderFactory readerFactory, final File source, final Writer writer, final String javaName) throws MojoExecutionException { JsonReader reader = null; try { reader = readerFactory.createReader(new FileReader(source)); final JsonStructure structure = reader.read(); if (JsonArray.class.isInstance(structure) || !JsonObject.class.isInstance(structure)) { // quite redundant for now but to avoid surprises in future throw new MojoExecutionException("This plugin doesn't support array generation, generate the model (generic) and handle arrays in your code"); } final JsonObject object = JsonObject.class.cast(structure); final Collection<String> imports = new TreeSet<String>(); // while we browse the example tree just store imports as well, avoids a 2 passes processing duplicating imports logic final StringWriter memBuffer = new StringWriter(); generateFieldsAndMethods(memBuffer, object, " ", imports); if (header != null) { writer.write(header); writer.write('\n'); } writer.write("package " + packageBase + ";\n\n"); if (!imports.isEmpty()) { for (final String imp : imports) { writer.write("import " + imp + ";\n"); } writer.write('\n'); } writer.write("public class " + javaName + " {\n"); writer.write(memBuffer.toString()); writer.write("}\n"); } catch (final IOException e) { throw new MojoExecutionException(e.getMessage(), e); } finally { if (reader != null) { reader.close(); } } }
public void setReaderFactory(final JsonReaderFactory readerFactory) { builder.setReaderFactory(readerFactory); }
public JsrMessageBodyReader(final JsonReaderFactory factory, final boolean closeStream) { this.factory = factory; this.closeStream = closeStream; }
@Override public JsonReaderFactory createReaderFactory(final Map<String, ?> stringMap) { return DELEGATE.createReaderFactory(stringMap); }
@Override public JsonReaderFactory createReaderFactory(final Map<String, ?> config) { return (config == null || config.isEmpty()) ? readerFactory : new JsonReaderFactoryImpl(config); }
private static JsonReaderFactory newReadFactory() { return Json.createReaderFactory(Collections.<String, Object>emptyMap()); }
public MapperBuilder setReaderFactory(final JsonReaderFactory readerFactory) { this.readerFactory = readerFactory; return this; }
public static ReaderHandler create(final JsonReaderFactory readerFactory) { if (readerFactory.getClass().getName().equals("org.apache.johnzon.core.JsonReaderFactoryImpl")) { return new ReaderHandler(true); } return new ReaderHandler(false); }
@Override public JsonReaderFactory getReaderFactory() { return readerFactory; }
@Override public JsonReaderFactory createReaderFactory( Map<String, ?> config ) { return defaultProvider.createReaderFactory(config); }
/** * Creates a reader factory for creating {@link JsonReader} objects. * The factory is configured with the specified map of provider specific * configuration properties. Provider implementations should ignore any * unsupported configuration properties specified in the map. * * @param config a map of provider specific properties to configure the * JSON readers. The map may be empty or null * @return a JSON reader factory */ public static JsonReaderFactory createReaderFactory(Map<String, ?> config) { return PROVIDER_INSTANCE.createReaderFactory(config); }
JsonReaderFactory readerFactory();