javax.json.spi.JsonProvider Java Examples

The following examples show how to use javax.json.spi.JsonProvider. 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: ConfigurableBus.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
private ConfiguredJsonbJaxrsProvider(final String encoding,
                                     final boolean nulls,
                                     final boolean iJson,
                                     final boolean pretty,
                                     final String binaryStrategy,
                                     final String namingStrategy,
                                     final String orderStrategy,
                                     final JsonProvider provider) {
    // ATTENTION this is only a workaround for MEECROWAVE-49 and shall get removed after Johnzon has a fix for it!
    // We add byte[] to the ignored types.
    super(singletonList("[B"));
    ofNullable(encoding).ifPresent(this::setEncoding);
    ofNullable(namingStrategy).ifPresent(this::setPropertyNamingStrategy);
    ofNullable(orderStrategy).ifPresent(this::setPropertyOrderStrategy);
    ofNullable(binaryStrategy).ifPresent(this::setBinaryDataStrategy);
    setNullValues(nulls);
    setIJson(iJson);
    setPretty(pretty);
    this.jsonb = JsonbBuilder.newBuilder()
            .withProvider(provider)
            .withConfig(config)
            .build();
}
 
Example #2
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void booleanRoundTrip(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final Record record = recordBuilderFactory.newRecordBuilder().withBoolean("value", true).build();
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final JsonObject json = JsonObject.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, JsonObject.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        assertTrue(json.getBoolean("value"));
        final Record toRecord = converter
                .toRecord(new RecordConverters.MappingMetaRegistry(), json, () -> jsonb,
                        () -> recordBuilderFactory);
        assertTrue(toRecord.getBoolean("value"));
    }
}
 
Example #3
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void intRoundTrip(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final Record record = recordBuilderFactory.newRecordBuilder().withInt("value", 2).build();
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final IntStruct struct = IntStruct.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, IntStruct.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        final Record toRecord = converter
                .toRecord(new RecordConverters.MappingMetaRegistry(), struct, () -> jsonb,
                        () -> recordBuilderFactory);
        assertEquals(Schema.Type.INT, toRecord.getSchema().getEntries().iterator().next().getType());
        assertEquals(2, toRecord.getInt("value"));
    }
}
 
Example #4
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void booleanRoundTripPojo(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final Record record = recordBuilderFactory.newRecordBuilder().withBoolean("value", true).build();
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final BoolStruct struct = BoolStruct.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, BoolStruct.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        final Record toRecord = converter
                .toRecord(new RecordConverters.MappingMetaRegistry(), struct, () -> jsonb,
                        () -> recordBuilderFactory);
        assertEquals(Schema.Type.BOOLEAN, toRecord.getSchema().getEntries().iterator().next().getType());
        assertTrue(toRecord.getBoolean("value"));
    }
}
 
Example #5
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void stringRoundTrip(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final Record record = recordBuilderFactory.newRecordBuilder().withString("value", "yes").build();
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final JsonObject json = JsonObject.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, JsonObject.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        assertEquals("yes", json.getString("value"));
        final Record toRecord = converter
                .toRecord(new RecordConverters.MappingMetaRegistry(), json, () -> jsonb,
                        () -> recordBuilderFactory);
        assertEquals("yes", toRecord.getString("value"));
    }
}
 
Example #6
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void notRowStructIntRoundTrip(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter, final Jsonb jsonb)
        throws Exception {
    final Record record = recordBuilderFactory.newRecordBuilder().withInt("myInt", 2).build();
    // run the round trip
    final IntWrapper wrapper = IntWrapper.class
            .cast(converter
                    .toType(new RecordConverters.MappingMetaRegistry(), record, IntWrapper.class,
                            () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb, () -> recordBuilderFactory));
    assertEquals(2, wrapper.myInt);
    final Record toRecord = converter
            .toRecord(new RecordConverters.MappingMetaRegistry(), wrapper, () -> jsonb, () -> recordBuilderFactory);
    assertEquals(Schema.Type.INT, toRecord.getSchema().getEntries().iterator().next().getType());
    assertEquals(2, toRecord.getInt("myInt"));
}
 
Example #7
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void convertListObject(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final Record record = converter
                .toRecord(new RecordConverters.MappingMetaRegistry(),
                        Json
                                .createObjectBuilder()
                                .add("list",
                                        Json
                                                .createArrayBuilder()
                                                .add(Json.createObjectBuilder().add("name", "a").build())
                                                .add(Json.createObjectBuilder().add("name", "b").build())
                                                .build())
                                .build(),
                        () -> jsonb, () -> new RecordBuilderFactoryImpl("test"));
        final Collection<Record> list = record.getArray(Record.class, "list");
        assertEquals(asList("a", "b"), list.stream().map(it -> it.getString("name")).collect(toList()));
    }
}
 
Example #8
Source File: RecordImpl.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Override // for debug purposes, don't use it for anything else
public String toString() {
    try (final Jsonb jsonb = JsonbBuilder
            .create(new JsonbConfig()
                    .withFormatting(true)
                    .withPropertyOrderStrategy(PropertyOrderStrategy.LEXICOGRAPHICAL)
                    .setProperty("johnzon.cdi.activated", false))) {
        return new RecordConverters()
                .toType(new RecordConverters.MappingMetaRegistry(), this, JsonObject.class,
                        () -> Json.createBuilderFactory(emptyMap()), JsonProvider::provider, () -> jsonb,
                        () -> new RecordBuilderFactoryImpl("tostring"))
                .toString();
    } catch (final Exception e) {
        return super.toString();
    }
}
 
Example #9
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void bigDecimalsInArray(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final BigDecimal pos1 = new BigDecimal("48.8480275637");
    final BigDecimal pos2 = new BigDecimal("2.25369456784");
    final List<BigDecimal> expected = asList(pos1, pos2);
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final JsonObject json = jsonBuilderFactory
                .createObjectBuilder()
                .add("points", jsonBuilderFactory.createArrayBuilder().add(pos1).add(pos2).build())
                .build();
        final Record record =
                converter.toRecord(new MappingMetaRegistry(), json, () -> jsonb, () -> recordBuilderFactory);
        assertEquals(expected, record.getArray(BigDecimal.class, "points"));
    }
}
 
Example #10
Source File: StringBackend.java    From jaxrs-analyzer with Apache License 2.0 6 votes vote down vote up
private String format(final String json) {
    final JsonProvider provider = JsonProvider.provider();
    final StringWriter out = new StringWriter();
    try (final JsonReader reader = provider.createReader(new StringReader(json));
         final JsonWriter jsonWriter = provider.createWriterFactory(singletonMap(JsonGenerator.PRETTY_PRINTING, true))
                 .createWriter(out)) {

        // jsonWriter.write(reader.readValue()); // bug in RI, can switch to johnzon
        final JsonStructure read = reader.read();
        if (read.getValueType() == JsonValue.ValueType.OBJECT) {
            jsonWriter.writeObject(JsonObject.class.cast(read));
        } else if (read.getValueType() == JsonValue.ValueType.ARRAY) {
            jsonWriter.writeArray(JsonArray.class.cast(read));
        } else { // no reformatting
            return json;
        }
        return out.toString().trim();
    }
}
 
Example #11
Source File: Json.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
private static JsonProvider getProvider()
{
  Thread thread = Thread.currentThread();
  ClassLoader loader = thread.getContextClassLoader();
  
  synchronized (_providerMap) {
    SoftReference<JsonProvider> providerRef = _providerMap.get(loader);
  
    JsonProvider provider = null;
  
    if (providerRef != null) {
      provider = providerRef.get();
    }
  
    if (provider == null) {
      provider = createProvider();
      
      _providerMap.put(loader, new SoftReference<>(provider));
    }
    
    return provider;
  }
}
 
Example #12
Source File: JsonpReader.java    From incubator-batchee with Apache License 2.0 6 votes vote down vote up
@Override
public void open(final Serializable checkpoint) throws Exception {
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    final JsonProvider provider = this.provider == null ? JsonProvider.provider() : JsonProvider.class.cast(loader.loadClass(this.provider));
    parser = provider.createParser(new FileInputStream(file));
    reader = new JsonPartialReader(provider, parser);

    if (skipRoot == null || "true".equalsIgnoreCase(skipRoot)) {
        final JsonParser.Event event = parser.next();
        if (event == JsonParser.Event.START_ARRAY) {
            end = JsonParser.Event.END_ARRAY;
        } else {
            end = JsonParser.Event.END_OBJECT;
        }
    }
    super.open(checkpoint);
}
 
Example #13
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void bigDecimalsInArrays(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final BigDecimal pos1 = new BigDecimal("48.8480275637");
    final BigDecimal pos2 = new BigDecimal("2.25369456784");
    final BigDecimal pos3 = new BigDecimal(25);
    final List<BigDecimal> expected = asList(pos1, pos2, pos1, pos2, pos2, pos1, pos3);
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final JsonObject json =
                jsonBuilderFactory
                        .createObjectBuilder()
                        .add("coordinates", jsonBuilderFactory
                                .createArrayBuilder()
                                .add(jsonBuilderFactory.createArrayBuilder().add(pos1).add(pos2).build())
                                .add(jsonBuilderFactory.createArrayBuilder().add(pos1).add(pos2).build())
                                .add(jsonBuilderFactory.createArrayBuilder().add(pos2).add(pos1).add(pos3).build())
                                .build())
                        .build();
        final Record record =
                converter.toRecord(new MappingMetaRegistry(), json, () -> jsonb, () -> recordBuilderFactory);
        assertEquals(expected,
                record
                        .getArray(ArrayList.class, "coordinates")
                        .stream()
                        .flatMap(a -> a.stream())
                        .flatMap(bd -> Stream.of(bd))
                        .collect(toList()));
    }
}
 
Example #14
Source File: PluralRecordExtension.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
        throws ParameterResolutionException {
    final Class<?> type = parameterContext.getParameter().getType();
    Boolean result = Jsonb.class == type || RecordConverters.class == type || JsonProvider.class == type
            || JsonBuilderFactory.class == type || RecordBuilderFactory.class == type;
    return result;
}
 
Example #15
Source File: PluralRecordExtension.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
        throws ParameterResolutionException {
    final Class<?> type = parameterContext.getParameter().getType();
    if (type == Jsonb.class) {
        return extensionContext
                .getStore(GLOBAL_NAMESPACE)
                .getOrComputeIfAbsent(Jsonb.class, k -> getJsonb(createPojoJsonb()));
    }
    if (type == RecordConverters.class) {
        return extensionContext
                .getStore(GLOBAL_NAMESPACE)
                .getOrComputeIfAbsent(RecordConverters.class, k -> converter);
    }
    if (type == JsonProvider.class) {
        return extensionContext
                .getStore(GLOBAL_NAMESPACE)
                .getOrComputeIfAbsent(JsonProvider.class, k -> jsonProvider);
    }
    if (type == JsonBuilderFactory.class) {
        return extensionContext
                .getStore(GLOBAL_NAMESPACE)
                .getOrComputeIfAbsent(JsonBuilderFactory.class, k -> jsonBuilderFactory);
    }
    if (type == RecordBuilderFactory.class) {
        return extensionContext
                .getStore(GLOBAL_NAMESPACE)
                .getOrComputeIfAbsent(RecordBuilderFactory.class, k -> recordBuilderFactory);
    }
    throw new ParameterResolutionException(
            String.format("Parameter for class %s not managed.", type.getCanonicalName()));
}
 
Example #16
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void bytesRoundTrip(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final byte[] bytes = new byte[] { 1, 2, 3 };
    final Record record = recordBuilderFactory.newRecordBuilder().withBytes("value", bytes).build();
    try (final Jsonb jsonb =
            JsonbBuilder.create(new JsonbConfig().withBinaryDataStrategy(BinaryDataStrategy.BASE_64))) {
        final JsonObject json = JsonObject.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, JsonObject.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        assertEquals(Base64.getEncoder().encodeToString(bytes), json.getString("value"));
        final Record toRecord = converter
                .toRecord(new RecordConverters.MappingMetaRegistry(), json, () -> jsonb,
                        () -> recordBuilderFactory);
        assertArrayEquals(bytes, toRecord.getBytes("value"));

        // now studio generator kind of convertion
        final BytesStruct struct = jsonb.fromJson(json.toString(), BytesStruct.class);
        assertArrayEquals(bytes, struct.value);
        final String jsonFromStruct = jsonb.toJson(struct);
        assertEquals("{\"value\":\"AQID\"}", jsonFromStruct);
        final Record structToRecordFromJson = converter
                .toRecord(new RecordConverters.MappingMetaRegistry(), json, () -> jsonb,
                        () -> recordBuilderFactory);
        assertArrayEquals(bytes, structToRecordFromJson.getBytes("value"));
    }
}
 
Example #17
Source File: Json.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
private static JsonProvider createProvider()
{
  for (JsonProvider provider : ServiceLoader.load(JsonProvider.class)) {
    return provider;
  }
  
  throw new UnsupportedOperationException("Cannot find JsonProvider");
}
 
Example #18
Source File: ConfigurationLoader.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
private JsonProvider loadJsonpProvider() {
    try { // prefer johnzon to support comments
        return JsonProvider.class.cast(Thread.currentThread().getContextClassLoader()
                .loadClass("org.apache.johnzon.core.JsonProviderImpl")
                .getConstructor().newInstance());
    } catch (final InvocationTargetException | NoClassDefFoundError | InstantiationException | ClassNotFoundException | NoSuchMethodException | IllegalAccessException err) {
        return JsonProvider.provider();
    }
}
 
Example #19
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void nullSupport(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final Record record = recordBuilderFactory.newRecordBuilder().withString("value", null).build();
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final JsonObject json = JsonObject.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, JsonObject.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        assertNull(json.getJsonString("value"));
    }
}
 
Example #20
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void pojo2Record(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter, final Jsonb jsonb)
        throws Exception {
    final Wrapper record = new Wrapper();
    record.value = "hey";
    final Record json = Record.class
            .cast(converter
                    .toType(new RecordConverters.MappingMetaRegistry(), record, Record.class,
                            () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb, () -> recordBuilderFactory));
    assertEquals("hey", json.getString("value"));
}
 
Example #21
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void studioTypes2(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final RowStruct rowStruct = new RowStruct();
    rowStruct.col1int = 10;
    rowStruct.col2string = "stringy";
    rowStruct.col3char = 'a';
    rowStruct.col4bool = Boolean.TRUE;
    rowStruct.col5byte = 100;
    rowStruct.col6short = Short.MAX_VALUE;
    rowStruct.col7long = 1971L;
    rowStruct.col8float = 19.71f;
    rowStruct.col9double = 19.234;
    rowStruct.col10bigdec = java.math.BigDecimal.TEN;
    rowStruct.col11date = new java.util.Date();
    try (final Jsonb jsonb = JsonbBuilder
            .create(new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.LEXICOGRAPHICAL))) {
        final Record record = Record.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), rowStruct, Record.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        final RowStruct deserialized = RowStruct.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, RowStruct.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        if (rowStruct.col10bigdec.doubleValue() == deserialized.col10bigdec.doubleValue()) {
            deserialized.col10bigdec = rowStruct.col10bigdec;
        }
        if (rowStruct.col11date.equals(deserialized.col11date)) {
            deserialized.col11date = rowStruct.col11date;
        }
        assertEquals(rowStruct, deserialized);
    }
}
 
Example #22
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void studioTypes(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final SimpleRowStruct record = new SimpleRowStruct();
    record.character = 'a';
    record.character2 = 'a';
    record.notLong = 100;
    record.notLong2 = 100;
    record.binary = 100;
    record.binary2 = 100;
    record.bd = BigDecimal.TEN;
    record.today = new Date(0);
    try (final Jsonb jsonb = JsonbBuilder
            .create(new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.LEXICOGRAPHICAL))) {
        final Record recordModel = Record.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, Record.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        assertEquals(
                "{\"bd\":10.0,\"binary\":100.0,\"binary2\":100.0," + "\"character\":\"a\",\"character2\":\"a\","
                        + "\"notLong\":100.0,\"notLong2\":100.0," + "\"today\":\"1970-01-01T00:00:00Z[UTC]\"}",
                recordModel.toString());
        final SimpleRowStruct deserialized = SimpleRowStruct.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), recordModel, SimpleRowStruct.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        if (record.bd.doubleValue() == deserialized.bd.doubleValue()) { // equals fails on this one
            deserialized.bd = record.bd;
        }
        assertEquals(record, deserialized);
    }
}
 
Example #23
Source File: JsonLoader.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private static JsonProvider loadProvider() {
   return AccessController.doPrivileged(new PrivilegedAction<JsonProvider>() {
      @Override
      public JsonProvider run() {
         ClassLoader originalLoader = Thread.currentThread().getContextClassLoader();
         try {
            Thread.currentThread().setContextClassLoader(JsonLoader.class.getClassLoader());
            return JsonProvider.provider();
         } finally {
            Thread.currentThread().setContextClassLoader(originalLoader);
         }
      }
   });

}
 
Example #24
Source File: RecordConverters.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
public Object toType(final MappingMetaRegistry registry, final Object data, final Class<?> parameterType,
        final Supplier<JsonBuilderFactory> factorySupplier, final Supplier<JsonProvider> providerSupplier,
        final Supplier<Jsonb> jsonbProvider, final Supplier<RecordBuilderFactory> recordBuilderProvider) {
    if (parameterType.isInstance(data)) {
        return data;
    }

    final JsonObject inputAsJson;
    if (JsonObject.class.isInstance(data)) {
        if (JsonObject.class == parameterType) {
            return data;
        }
        inputAsJson = JsonObject.class.cast(data);
    } else if (Record.class.isInstance(data)) {
        final Record record = Record.class.cast(data);
        if (!JsonObject.class.isAssignableFrom(parameterType)) {
            final MappingMeta mappingMeta = registry.find(parameterType, recordBuilderProvider);
            if (mappingMeta.isLinearMapping()) {
                return mappingMeta.newInstance(record);
            }
        }
        final JsonObject asJson = toJson(factorySupplier, providerSupplier, record);
        if (JsonObject.class == parameterType) {
            return asJson;
        }
        inputAsJson = asJson;
    } else {
        if (parameterType == Record.class) {
            return toRecord(registry, data, jsonbProvider, recordBuilderProvider);
        }
        final Jsonb jsonb = jsonbProvider.get();
        inputAsJson = jsonb.fromJson(jsonb.toJson(data), JsonObject.class);
    }
    return jsonbProvider.get().fromJson(new JsonValueReader<>(inputAsJson), parameterType);
}
 
Example #25
Source File: ProcessorImpl.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private JsonProvider jsonProvider() {
    if (jsonProvider == null) {
        synchronized (this) {
            if (jsonProvider == null) {
                jsonProvider = ContainerFinder.Instance.get().find(plugin()).findService(JsonProvider.class);
            }
        }
    }
    return jsonProvider;
}
 
Example #26
Source File: JsonReporter.java    From revapi with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(@Nonnull AnalysisContext analysisContext) {
    super.initialize(analysisContext);
    boolean prettyPrint = analysisContext.getConfiguration().get("indent").asBoolean(false);

    Map<String, Object> config = prettyPrint
            ? singletonMap(JsonGenerator.PRETTY_PRINTING, null)
            : emptyMap();

    jsonFactory = JsonProvider.provider().createGeneratorFactory(config);

    this.reports = new TreeSet<>(getReportsByElementOrderComparator());
}
 
Example #27
Source File: JsonSchemaModulesGenerator.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void generate(JsonStructureWriter<T, C> writer) {
	final JsonProvider provider = JsonProvider.provider();
	final JsonBuilderFactory builderFactory = provider.createBuilderFactory(null);
	for (final Module<T, C> module : this.modules.getModules()) {
		if (!module.isEmpty()) {
			for (JsonSchema jsonSchema : module.getJsonSchemas()) {
				final JsonSchemaModuleCompiler<T, C> moduleCompiler = new JsonSchemaModuleCompiler<T, C>(
						builderFactory, modules, module, jsonSchema);
				final JsonSchemaBuilder moduleSchema = moduleCompiler.compile();
				final JsonObject moduleSchemaJsonObject = moduleSchema.build(builderFactory);
				writer.writeJsonStructure(module, moduleSchemaJsonObject, jsonSchema.getFileName());
			}
		}
	}
}
 
Example #28
Source File: JsonBuilderUtilsTest.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void addsProperty() {
	final JsonProvider provider = JsonProvider.provider();
	final JsonBuilderFactory builderFactory = provider
			.createBuilderFactory(null);
	final JsonObjectBuilder builder = builderFactory.createObjectBuilder();
	JsonBuilderUtils.add(builderFactory, builder, "null", null);
	JsonBuilderUtils.add(builderFactory, builder, "true", true);
	JsonBuilderUtils.add(builderFactory, builder, "string", "string");
	JsonBuilderUtils.add(builderFactory, builder, "char", 'c');
	JsonBuilderUtils.add(builderFactory, builder, "bigInteger",
			BigInteger.TEN);
	JsonBuilderUtils.add(builderFactory, builder, "bigDecimal",
			BigDecimal.valueOf(1111, 2));
	JsonBuilderUtils.add(builderFactory, builder, "float", 22f);
	JsonBuilderUtils.add(builderFactory, builder, "double", 22d);
	JsonBuilderUtils.add(builderFactory, builder, "byte", (byte) 33);
	JsonBuilderUtils.add(builderFactory, builder, "int", (int) 44);
	JsonBuilderUtils.add(builderFactory, builder, "short", (int) 55);
	JsonBuilderUtils.add(builderFactory, builder, "list",
			Arrays.<Object> asList("a", 0xbc, "d"));
	JsonBuilderUtils.add(builderFactory, builder, "array", new Object[] {
			1, "2", 3, false });

	JsonBuilderUtils.add(builderFactory, builder, "map",
			Collections.singletonMap("foo", "bar"));
	// provider.createWriter(System.out).write(builder.build());
}
 
Example #29
Source File: Main.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@ProcessElement
public void processElement(final ProcessContext context) {
    // not the best conversion impl but this is really to simplify the asserts, not for "prod"
    final JsonObject asJson = JsonObject.class.cast(new RecordConverters().toType(
            new RecordConverters.MappingMetaRegistry(), context.element(), JsonObject.class,
            () -> Json.createBuilderFactory(emptyMap()), JsonProvider::provider, JsonbBuilder::create,
            () -> new AvroRecordBuilderFactoryProvider().apply("serialization-over-cluster")));
    context.output(asJson.values().iterator().next().asJsonArray().getJsonObject(0).toString());
}
 
Example #30
Source File: JsonBuilderUtilsTest.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void addsItem() {
	final JsonProvider provider = JsonProvider.provider();
	final JsonBuilderFactory builderFactory = provider
			.createBuilderFactory(null);
	final JsonArrayBuilder builder = builderFactory.createArrayBuilder();
	JsonBuilderUtils.add(builderFactory, builder, null);
	JsonBuilderUtils.add(builderFactory, builder, true);
	JsonBuilderUtils.add(builderFactory, builder, "string");
	JsonBuilderUtils.add(builderFactory, builder, 'c');
	JsonBuilderUtils.add(builderFactory, builder, BigInteger.TEN);
	JsonBuilderUtils.add(builderFactory, builder,
			BigDecimal.valueOf(1111, 2));
	JsonBuilderUtils.add(builderFactory, builder, 22f);
	JsonBuilderUtils.add(builderFactory, builder, 22d);
	JsonBuilderUtils.add(builderFactory, builder, (byte) 33);
	JsonBuilderUtils.add(builderFactory, builder, (int) 44);
	JsonBuilderUtils.add(builderFactory, builder, (int) 55);
	JsonBuilderUtils.add(builderFactory, builder,
			Arrays.<Object> asList("a", 0xbc, "d"));
	JsonBuilderUtils.add(builderFactory, builder, new Object[] { 1, "2", 3,
			false });

	JsonBuilderUtils.add(builderFactory, builder,
			Collections.singletonMap("foo", "bar"));
	// provider.createWriter(System.out).write(builder.build());
}