javax.json.JsonWriterFactory Java Examples

The following examples show how to use javax.json.JsonWriterFactory. 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: DefaultServices.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
public static Object lookup(final String type) {
    if (type.equals(JsonBuilderFactory.class.getName())) {
        return ComponentManager.instance().getJsonpBuilderFactory();
    }
    if (type.equals(JsonReaderFactory.class.getName())) {
        return ComponentManager.instance().getJsonpReaderFactory();
    }
    if (type.equals(JsonGeneratorFactory.class.getName())) {
        return ComponentManager.instance().getJsonpGeneratorFactory();
    }
    if (type.equals(JsonParserFactory.class.getName())) {
        return ComponentManager.instance().getJsonpParserFactory();
    }
    if (type.equals(JsonWriterFactory.class.getName())) {
        return ComponentManager.instance().getJsonpWriterFactory();
    }
    if (type.equals(RecordBuilderFactory.class.getName())) {
        final Function<String, RecordBuilderFactory> provider =
                ComponentManager.instance().getRecordBuilderFactoryProvider();
        return provider.apply(null);
    }
    throw new IllegalArgumentException(type + " can't be a global service, didn't you pass a null plugin?");
}
 
Example #2
Source File: JsonUtil.java    From geoportal-server-harvester with Apache License 2.0 6 votes vote down vote up
/**
 * Create a JSON string.
 * @param structure the structure JsonAoject or JsonArray
 * @param pretty for pretty print
 * @return the JSON string
 */
public static String toJson(JsonStructure structure, boolean pretty) {
  JsonWriter writer  = null;
  StringWriter result = new StringWriter();
  try {
    Map<String, Object> props = new HashMap<String,Object>();
    if (pretty) props.put(JsonGenerator.PRETTY_PRINTING,true);
    JsonWriterFactory factory = Json.createWriterFactory(props);
    writer = factory.createWriter(result);
    writer.write(structure); 
  } finally {
    try {
      if (writer != null) writer.close();
    } catch (Throwable t) {
      t.printStackTrace(System.err);
    }
  }
  return result.toString().trim();
}
 
Example #3
Source File: SystemInputJsonWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Writes the given system test definition the form of a JSON document.
 */
public void write( SystemInputDef systemInput)
  {
  JsonWriterFactory writerFactory = Json.createWriterFactory( MapBuilder.of( PRETTY_PRINTING, true).build());
  JsonWriter jsonWriter = writerFactory.createWriter( getWriter());

  jsonWriter.write( SystemInputJson.toJson( systemInput));
  }
 
Example #4
Source File: TestXmlSchema2JsonSchema.java    From iaf with Apache License 2.0 5 votes vote down vote up
private String jsonPrettyPrint(String json) {
	StringWriter sw = new StringWriter();
	JsonReader jr = Json.createReader(new StringReader(json));
	JsonObject jobj = jr.readObject();

	Map<String, Object> properties = new HashMap<>(1);
	properties.put(JsonGenerator.PRETTY_PRINTING, true);

	JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
	try (JsonWriter jsonWriter = writerFactory.createWriter(sw)) {
		jsonWriter.writeObject(jobj);
	}

	return sw.toString().trim();
}
 
Example #5
Source File: ApiListenerServlet.java    From iaf with Apache License 2.0 5 votes vote down vote up
public void returnJson(HttpServletResponse response, int status, JsonObject json) throws IOException {
	response.setStatus(status);
	Map<String, Boolean> config = new HashMap<>();
	config.put(JsonGenerator.PRETTY_PRINTING, true);
	JsonWriterFactory factory = Json.createWriterFactory(config);
	try (JsonWriter jsonWriter = factory.createWriter(response.getOutputStream(), Charset.forName("UTF-8"))) {
		jsonWriter.write(json);
	}
}
 
Example #6
Source File: Util.java    From jcypher with Apache License 2.0 5 votes vote down vote up
/**
 * write a JsonObject formatted in a pretty way into a String
 * @param jsonObject
 * @return a String containing the JSON
 */
public static String writePretty(JsonObject jsonObject) {
	JsonWriterFactory factory = createPrettyWriterFactory();
	StringWriter sw = new StringWriter();
	JsonWriter writer = factory.createWriter(sw);
	writer.writeObject(jsonObject);
	String ret = sw.toString();
	writer.close();
	return ret;
}
 
Example #7
Source File: ApiStart2.java    From logbook-kai with MIT License 5 votes vote down vote up
/**
 * store
 * 
 * @param obj api_data
 */
private void store(JsonObject root) {
    if (AppConfig.get().isStoreApiStart2()) {
        try {
            String dir = AppConfig.get().getStoreApiStart2Dir();
            if (dir == null || "".equals(dir))
                return;

            Path dirPath = Paths.get(dir);
            Path parent = dirPath.getParent();
            if (parent != null && !Files.exists(parent)) {
                Files.createDirectories(parent);
            }

            JsonWriterFactory factory = Json
                    .createWriterFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true));
            for (Entry<String, JsonValue> entry : root.entrySet()) {
                String key = entry.getKey();
                JsonValue val = entry.getValue();
                JsonObject obj = Json.createObjectBuilder().add(key, val).build();

                Path outPath = dirPath.resolve(key + ".json");

                try (OutputStream out = Files.newOutputStream(outPath)) {
                    try (JsonWriter writer = factory.createWriter(out)) {
                        writer.write(obj);
                    }
                }
            }
        } catch (Exception e) {
            LoggerHolder.get().warn("api_start2の保存に失敗しました", e);
        }
    }
}
 
Example #8
Source File: RequestTestDefWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Writes the given request cases in the form of a JSON document.
 */
public void write( RequestTestDef requestTestDef)
  {
  JsonWriterFactory writerFactory = Json.createWriterFactory( MapBuilder.of( PRETTY_PRINTING, true).build());
  JsonWriter jsonWriter = writerFactory.createWriter( getWriter());

  jsonWriter.write( RequestCaseJson.toJson( requestTestDef));
  }
 
Example #9
Source File: MocoTestConfigWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Writes the given request cases in the form of a JSON document.
 */
public void write( MocoTestConfig mocoTestConfig)
  {
  JsonWriterFactory writerFactory = Json.createWriterFactory( MapBuilder.of( PRETTY_PRINTING, true).build());
  JsonWriter jsonWriter = writerFactory.createWriter( getWriter());

  jsonWriter.write( MocoTestConfigJson.toJson( mocoTestConfig));
  }
 
Example #10
Source File: MocoServerConfigWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Writes the given system test definition the form of a JSON document.
 */
public void write( RequestTestDef requestCases)
  {
  JsonWriterFactory writerFactory = Json.createWriterFactory( MapBuilder.of( PRETTY_PRINTING, true).build());
  JsonWriter jsonWriter = writerFactory.createWriter( getWriter());

  try
    {
    jsonWriter.write( expectedConfigs( requestCases));
    }
  catch( Exception e)
    {
    throw new RequestCaseException( String.format( "Can't write Moco server configuration for %s", requestCases), e);
    }
  }
 
Example #11
Source File: SystemTestJsonWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Writes the given system test definition the form of a JSON document.
 */
public void write( SystemTestDef systemTest)
  {
  JsonWriterFactory writerFactory = Json.createWriterFactory( MapBuilder.of( PRETTY_PRINTING, true).build());
  JsonWriter jsonWriter = writerFactory.createWriter( getWriter());

  jsonWriter.write( SystemTestJson.toJson( systemTest));
  }
 
Example #12
Source File: ProjectJsonWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Writes the given project definition the form of a JSON document.
 */
public void write( Project project)
  {
  JsonWriterFactory writerFactory = Json.createWriterFactory( MapBuilder.of( PRETTY_PRINTING, true).build());
  JsonWriter jsonWriter = writerFactory.createWriter( getWriter());

  jsonWriter.write( ProjectJson.toJson( project));
  }
 
Example #13
Source File: PrintUtil.java    From microprofile-graphql with Apache License 2.0 5 votes vote down vote up
private static String prettyJson(JsonObject jsonObject) {
    if(jsonObject!=null){
        StringWriter sw = new StringWriter();
        Map<String, Object> properties = new HashMap<>(1);
        properties.put(JsonGenerator.PRETTY_PRINTING, true);

        JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
        try (JsonWriter jsonWriter = writerFactory.createWriter(sw)) {
            jsonWriter.writeObject(jsonObject);
        }
        return sw.toString();
    }
    return null;
}
 
Example #14
Source File: GeneratorSetJsonWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Writes the given system test definition the form of a JSON document.
 */
public void write( IGeneratorSet generatorSet)
  {
  JsonWriterFactory writerFactory = Json.createWriterFactory( MapBuilder.of( PRETTY_PRINTING, true).build());
  JsonWriter jsonWriter = writerFactory.createWriter( getWriter());

  jsonWriter.write( GeneratorSetJson.toJson( generatorSet));
  }
 
Example #15
Source File: JsonpJsonObjectCoder.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
public static JsonpJsonObjectCoder of(final String plugin) {
    if (plugin == null) {
        final ComponentManager instance = ComponentManager.instance();
        return new JsonpJsonObjectCoder(instance.getJsonpReaderFactory(), instance.getJsonpWriterFactory());
    }
    final LightContainer container = ContainerFinder.Instance.get().find(plugin);
    return new JsonpJsonObjectCoder(container.findService(JsonReaderFactory.class),
            container.findService(JsonWriterFactory.class));
}
 
Example #16
Source File: SmallRyeHealthReporter.java    From smallrye-health with Apache License 2.0 5 votes vote down vote up
public void reportHealth(OutputStream out, SmallRyeHealth health) {
    if (health.isDown() && HealthLogging.log.isInfoEnabled()) {
        // Log reason, as not reported by container orchestrators, yet container may get killed.
        HealthLogging.log.healthDownStatus(health.getPayload().toString());
    }

    JsonWriterFactory factory = jsonProvider.createWriterFactory(JSON_CONFIG);
    JsonWriter writer = factory.createWriter(out);

    writer.writeObject(health.getPayload());
    writer.close();
}
 
Example #17
Source File: ExecutionTest.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private String getPrettyJson(JsonObject jsonObject) {

        JsonWriterFactory writerFactory = Json.createWriterFactory(JSON_PROPERTIES);

        try (StringWriter sw = new StringWriter();
                JsonWriter jsonWriter = writerFactory.createWriter(sw)) {
            jsonWriter.writeObject(jsonObject);
            return sw.toString();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

    }
 
Example #18
Source File: CdiExecutionTest.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private String getPrettyJson(JsonObject jsonObject) {

        JsonWriterFactory writerFactory = Json.createWriterFactory(JSON_PROPERTIES);

        try (StringWriter sw = new StringWriter();
                JsonWriter jsonWriter = writerFactory.createWriter(sw)) {
            jsonWriter.writeObject(jsonObject);
            return sw.toString();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

    }
 
Example #19
Source File: ResourceProcessor.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JsonReaderFactory jsonReaderFactory = Json.createReaderFactory(null);
    JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(null);
    JsonBuilderFactory jsonBuilderFactory = Json.createBuilderFactory(null);

    File dir = new File("src/main/resources/hl7/fhir/us/davinci-pdex-plan-net/package/");
    for (File file : dir.listFiles()) {
        String fileName = file.getName();
        if (!fileName.endsWith(".json") || file.isDirectory()) {
            continue;
        }
        JsonObject jsonObject = null;
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            JsonReader jsonReader = jsonReaderFactory.createReader(reader);
            jsonObject = jsonReader.readObject();

            JsonObjectBuilder jsonObjectBuilder = jsonBuilderFactory.createObjectBuilder(jsonObject);

            JsonObject text = jsonObject.getJsonObject("text");
            if (text != null) {
                JsonObjectBuilder textBuilder = jsonBuilderFactory.createObjectBuilder(text);
                String div = text.getString("div");
                div = div.replace("<p><pre>", "<pre>").replace("</pre></p>", "</pre>");
                textBuilder.add("div", div);
                jsonObjectBuilder.add("text", textBuilder);
            }

            if (!jsonObject.containsKey("version")) {
                System.out.println("file: " + file + " does not have a version");
                jsonObjectBuilder.add("version", "0.1.0");
            }

            jsonObject = jsonObjectBuilder.build();
        }
        try (FileWriter writer = new FileWriter(file)) {
            JsonWriter jsonWriter = jsonWriterFactory.createWriter(writer);
            jsonWriter.write(jsonObject);
        }
    }
}
 
Example #20
Source File: ConfigurableBus.java    From openwebbeans-meecrowave with Apache License 2.0 4 votes vote down vote up
@Override
public JsonWriterFactory createWriterFactory(final Map<String, ?> config) {
    return writerFactory;
}
 
Example #21
Source File: ConfigurableBus.java    From openwebbeans-meecrowave with Apache License 2.0 4 votes vote down vote up
private DelegateJsonProvider(final JsonProvider provider, final JsonReaderFactory readerFactory, final JsonWriterFactory writerFactory) {
    this.provider = provider;
    this.readerFactory = readerFactory;
    this.writerFactory = writerFactory;
}
 
Example #22
Source File: BeamIOTransformerTest.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
private void scenario(final Scenario runnable) {
    final AtomicReference<ContainerFinder> containerFinder;
    try {
        final Field finder = ContainerFinder.Instance.class.getDeclaredField("FINDER");
        if (!finder.isAccessible()) {
            finder.setAccessible(true);
        }
        containerFinder = (AtomicReference<ContainerFinder>) finder.get(null);
        final ContainerFinder oldContainerFinder = containerFinder.get();
        try {
            final Thread thread = Thread.currentThread();
            final ClassLoader originalLoader = thread.getContextClassLoader();
            final String prefix = BeamIOTransformerTest.class.getName() + "$";
            final Predicate<String> parentPredicate = it -> SetValidator.class.getName().equals(it)
                    || !(it.startsWith(prefix) || it.startsWith(JdbcSource.class.getName()))
                    || Pojo.class.getName().equals(it);
            try (final ConfigurableClassLoader loader = new ConfigurableClassLoader("test",
                    new URL[] { jarLocation(BeamIOTransformerTest.class).toURI().toURL() }, originalLoader,
                    parentPredicate, parentPredicate.negate(), new String[0], new String[0])) {
                // thread.setContextClassLoader(loader); // don't set it, this is what we test!
                final BeamIOTransformer transformer = new BeamIOTransformer();
                loader.registerTransformer(transformer);
                containerFinder.set(plugin -> new LightContainer() {

                    private final JavaProxyEnricherFactory factory = new JavaProxyEnricherFactory();

                    @Override
                    public ClassLoader classloader() {
                        return loader;
                    }

                    @Override
                    public <T> T findService(final Class<T> key) {
                        if (key == JsonReaderFactory.class) {
                            return key
                                    .cast(factory
                                            .asSerializable(loader, "test", JsonReaderFactory.class.getName(),
                                                    Json.createReaderFactory(emptyMap())));
                        }
                        if (key == JsonWriterFactory.class) {
                            return key
                                    .cast(factory
                                            .asSerializable(loader, "test", JsonWriterFactory.class.getName(),
                                                    Json.createWriterFactory(emptyMap())));
                        }
                        return null;
                    }
                });
                runnable.execute(transformer, loader);
            } catch (final Exception e) {
                doFail(e);
            } finally {
                thread.setContextClassLoader(originalLoader);
            }
        } finally {
            containerFinder.set(oldContainerFinder);
        }
    } catch (final Exception t) {
        doFail(t);
    }
}
 
Example #23
Source File: DefaultServiceProvider.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
private Object doLookup(final String id, final ClassLoader loader,
        final Supplier<List<InputStream>> localConfigLookup, final Function<String, Path> resolver,
        final Class<?> api, final AtomicReference<Map<Class<?>, Object>> services) {
    if (JsonProvider.class == api) {
        return new PreComputedJsonpProvider(id, jsonpProvider, jsonpParserFactory, jsonpWriterFactory,
                jsonpBuilderFactory, jsonpGeneratorFactory, jsonpReaderFactory);
    }
    if (JsonBuilderFactory.class == api) {
        return javaProxyEnricherFactory
                .asSerializable(loader, id, JsonBuilderFactory.class.getName(), jsonpBuilderFactory);
    }
    if (JsonParserFactory.class == api) {
        return javaProxyEnricherFactory
                .asSerializable(loader, id, JsonParserFactory.class.getName(), jsonpParserFactory);
    }
    if (JsonReaderFactory.class == api) {
        return javaProxyEnricherFactory
                .asSerializable(loader, id, JsonReaderFactory.class.getName(), jsonpReaderFactory);
    }
    if (JsonWriterFactory.class == api) {
        return javaProxyEnricherFactory
                .asSerializable(loader, id, JsonWriterFactory.class.getName(), jsonpWriterFactory);
    }
    if (JsonGeneratorFactory.class == api) {
        return javaProxyEnricherFactory
                .asSerializable(loader, id, JsonGeneratorFactory.class.getName(), jsonpGeneratorFactory);
    }
    if (Jsonb.class == api) {
        final JsonbBuilder jsonbBuilder = createPojoJsonbBuilder(id,
                Lazy
                        .lazy(() -> Jsonb.class
                                .cast(doLookup(id, loader, localConfigLookup, resolver, Jsonb.class, services))));
        return new GenericOrPojoJsonb(id, jsonbProvider
                .create()
                .withProvider(jsonpProvider) // reuses the same memory buffering
                .withConfig(jsonbConfig)
                .build(), jsonbBuilder.build());
    }
    if (LocalConfiguration.class == api) {
        final List<LocalConfiguration> containerConfigurations = new ArrayList<>(localConfigurations);
        if (!Boolean.getBoolean("talend.component.configuration." + id + ".ignoreLocalConfiguration")) {
            final Stream<InputStream> localConfigs = localConfigLookup.get().stream();
            final Properties aggregatedLocalConfigs = aggregateConfigurations(localConfigs);
            if (!aggregatedLocalConfigs.isEmpty()) {
                containerConfigurations.add(new PropertiesConfiguration(aggregatedLocalConfigs));
            }
        }
        return new LocalConfigurationService(containerConfigurations, id);
    }
    if (RecordBuilderFactory.class == api) {
        return recordBuilderFactoryProvider.apply(id);
    }
    if (ProxyGenerator.class == api) {
        return proxyGenerator;
    }
    if (LocalCache.class == api) {
        final LocalCacheService service =
                new LocalCacheService(id, System::currentTimeMillis, this.executorService);
        Injector.class.cast(services.get().get(Injector.class)).inject(service);
        return service;
    }
    if (Injector.class == api) {
        return new InjectorImpl(id, reflections, proxyGenerator, services.get());
    }
    if (HttpClientFactory.class == api) {
        return new HttpClientFactoryImpl(id, reflections, Jsonb.class.cast(services.get().get(Jsonb.class)),
                services.get());
    }
    if (Resolver.class == api) {
        return new ResolverImpl(id, resolver);
    }
    if (ObjectFactory.class == api) {
        return new ObjectFactoryImpl(id, propertyEditorRegistry);
    }
    if (RecordPointerFactory.class == api) {
        return new RecordPointerFactoryImpl(id);
    }
    if (ContainerInfo.class == api) {
        return new ContainerInfo(id);
    }
    if (RecordService.class == api) {
        return new RecordServiceImpl(id, recordBuilderFactoryProvider.apply(id), () -> jsonpBuilderFactory,
                () -> jsonpProvider,
                Lazy
                        .lazy(() -> Jsonb.class
                                .cast(doLookup(id, loader, localConfigLookup, resolver, Jsonb.class, services))));
    }
    return null;
}
 
Example #24
Source File: PreComputedJsonpProvider.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
@Override
public JsonWriterFactory createWriterFactory(final Map<String, ?> config) {
    return writerFactory;
}
 
Example #25
Source File: JavaxJsonFactories.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@Override
public JsonWriterFactory writerFactory()
{
    return writerFactory;
}
 
Example #26
Source File: JsonLoader.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public static JsonWriterFactory createWriterFactory(Map<String, ?> config) {
   return provider.createWriterFactory(config);
}
 
Example #27
Source File: Util.java    From jcypher with Apache License 2.0 4 votes vote down vote up
private static JsonWriterFactory createPrettyWriterFactory() {
	HashMap<String, Object> prettyConfigMap = new HashMap<String, Object>();
	prettyConfigMap.put(JsonGenerator.PRETTY_PRINTING, Boolean.TRUE);
	JsonWriterFactory prettyWriterFactory = Json.createWriterFactory(prettyConfigMap);
	return prettyWriterFactory;
}
 
Example #28
Source File: JavaxJsonFactories.java    From attic-polygene-java with Apache License 2.0 votes vote down vote up
JsonWriterFactory writerFactory();