Java Code Examples for com.fasterxml.jackson.databind.type.TypeFactory

The following examples show how to use com.fasterxml.jackson.databind.type.TypeFactory. These examples are extracted from open source projects. 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 Project: camunda-bpm-elasticsearch   Source File: JsonHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> readJsonFromClasspathAsMap(String fileName) {
  InputStream inputStream = null;

  try {
    inputStream = IoUtil.getResourceAsStream(fileName);
    if (inputStream == null) {
      throw new RuntimeException("File '" + fileName + "' not found!");
    }

    MapType type = TypeFactory.defaultInstance().constructMapType(HashMap.class, String.class, Object.class);
    HashMap<String, Object> mapping = objectMapper.readValue(inputStream, type);

    return mapping;
  } catch (IOException e) {
    throw new RuntimeException("Unable to load json [" + fileName + "] from classpath", e);
  } finally {
    IoUtil.closeSilently(inputStream);
  }
}
 
Example 2
private void success_invocation() throws InterruptedException, ExecutionException {
  new Expectations(invocation) {
    {
      invocation.getTransportContext();
      result = transportContext;

      operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION);
      result = restOperationMeta;

      invocation.findResponseType(anyInt);
      result = TypeFactory.defaultInstance().constructType(String.class);
    }
  };

  codecFilter.onFilter(invocation, nextNode).get();
}
 
Example 3
Source Project: spring-cloud-function   Source File: JacksonMapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T fromJson(Object json, Type type) {
	T convertedValue = null;
	JavaType constructType = TypeFactory.defaultInstance().constructType(type);

	try {
		if (json instanceof String) {
			convertedValue = this.mapper.readValue((String) json, constructType);
		}
		else if (json instanceof byte[]) {
			convertedValue = this.mapper.readValue((byte[]) json, constructType);
		}
		else if (json instanceof Reader) {
			convertedValue = this.mapper.readValue((Reader) json, constructType);
		}
	}
	catch (Exception e) {
		logger.warn("Failed to convert. Possible bug as the conversion probably shouldn't have been attampted here", e);
	}
	return convertedValue;
}
 
Example 4
@Override
public ParamValueProcessor create(Parameter parameter, Type genericParamType) {
  Model model = ((BodyParameter) parameter).getSchema();
  JavaType swaggerType = null;
  if (model instanceof ModelImpl) {
    swaggerType = ConverterMgr.findJavaType(((ModelImpl) model).getType(), ((ModelImpl) model).getFormat());
  }
  boolean isString = swaggerType != null && swaggerType.getRawClass().equals(String.class);

  JavaType targetType =
      genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType);
  boolean rawJson = SwaggerUtils.isRawJsonType(parameter);
  if (rawJson) {
    return new RawJsonBodyProcessor(targetType, (String) parameter.getVendorExtensions()
        .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired());
  }

  return new BodyProcessor(targetType, (String) parameter.getVendorExtensions()
      .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired());
}
 
Example 5
Source Project: components   Source File: JdbcComponentTestIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getJdbcDefinition() throws java.io.IOException {
    // when
    Response response = given()
            .accept(APPLICATION_JSON_UTF8_VALUE).get(getVersionPrefix() + "/definitions/DATA_STORE");
    response.then()
            .statusCode(200).log().ifError();

    // then
    List<DefinitionDTO> definitions = mapper
            .readerFor(TypeFactory.defaultInstance().constructCollectionType(List.class, DefinitionDTO.class))
            .readValue(response.asInputStream());

    DefinitionDTO jdbcDef = null;

    for (DefinitionDTO definition : definitions) {
        if (DATA_STORE_DEFINITION_NAME.equals(definition.getName())) {
            jdbcDef = definition;
            break;
        }
    }
    assertNotNull(jdbcDef);
}
 
Example 6
Source Project: riptide   Source File: StreamConverterTest.java    License: MIT License 6 votes vote down vote up
@Test
void shouldSupportReadGeneric() {
    final ObjectMapper mapper = mock(ObjectMapper.class);
    final TypeFactory factory = new ObjectMapper().getTypeFactory();
    when(mapper.getTypeFactory()).thenReturn(factory);
    when(mapper.canDeserialize(any())).thenReturn(true);
    final StreamConverter<Object> unit = streamConverter(mapper, singletonList(APPLICATION_X_JSON_STREAM));

    assertFalse(unit.canRead(Object.class, getClass(), APPLICATION_X_JSON_STREAM));
    assertFalse(unit.canRead(Streams.streamOf(Object.class).getType(), getClass(), APPLICATION_XML));

    assertTrue(unit.canRead(Streams.streamOf(List.class).getType(), getClass(), APPLICATION_X_JSON_STREAM));
    assertTrue(unit.canRead(Streams.streamOf(List[].class).getType(), getClass(), APPLICATION_X_JSON_STREAM));
    assertTrue(unit.canRead(Streams.streamOf(AccountBody.class).getType(), getClass(), null));
    assertTrue(unit.canRead(Streams.streamOf(AccountBody[].class).getType(), getClass(), null));

    when(mapper.canDeserialize(factory.constructType(AccountBody.class))).thenReturn(false);
    assertFalse(unit.canRead(Streams.streamOf(AccountBody.class).getType(), getClass(), APPLICATION_X_JSON_STREAM));
}
 
Example 7
private <T> RedisCacheConfiguration determineConfiguration(
        Type type) {
    CacheProperties.Redis redisProperties = this.cacheProperties.getRedis();
    RedisCacheConfiguration config = RedisCacheConfiguration
            .defaultCacheConfig();
    Jackson2JsonRedisSerializer<T> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(TypeFactory.defaultInstance().constructType(type));
    jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
    config = config.serializeValuesWith(RedisSerializationContext.SerializationPair
            .fromSerializer(jackson2JsonRedisSerializer));
    if (redisProperties.getTimeToLive() != null) {
        config = config.entryTtl(redisProperties.getTimeToLive());
    }
    if (redisProperties.getKeyPrefix() != null) {
        config = config.prefixKeysWith(redisProperties.getKeyPrefix());
    }
    if (!redisProperties.isCacheNullValues()) {
        config = config.disableCachingNullValues();
    }
    if (!redisProperties.isUseKeyPrefix()) {
        config = config.disableKeyPrefix();
    }
    return config;
}
 
Example 8
public PojoConsumerOperationMeta(PojoConsumerMeta pojoConsumerMeta, OperationMeta operationMeta,
    SwaggerConsumerOperation swaggerConsumerOperation,
    Swagger intfSwagger, Operation intfOperation) {
  this.pojoConsumerMeta = pojoConsumerMeta;
  this.operationMeta = operationMeta;
  this.swaggerConsumerOperation = swaggerConsumerOperation;

  Type intfResponseType = ParamUtils
      .getGenericParameterType(swaggerConsumerOperation.getConsumerClass(),
          swaggerConsumerOperation.getConsumerMethod().getDeclaringClass(),
          swaggerConsumerOperation.getConsumerMethod().getGenericReturnType());

  if (intfResponseType instanceof Class && Part.class.isAssignableFrom((Class<?>) intfResponseType)) {
    responseType = TypeFactory.defaultInstance().constructType(Part.class);
    return;
  }

  intfResponseType = findResponseTypeProcessor(intfResponseType).extractResponseType(intfResponseType);
  if (intfResponseType != null) {
    responseType = TypeFactory.defaultInstance().constructType(intfResponseType);
  }
}
 
Example 9
@SuppressWarnings("unchecked")
@Test
public void testGetValueSet() throws Exception {
  new Expectations() {
    {
      request.getParameterValues("name");
      result = new String[] {"value"};
    }
  };

  ParamValueProcessor processor = createProcessor("name",
      TypeFactory.defaultInstance().constructCollectionType(Set.class, String.class), null,
      true);
  Object value = processor.getValue(request);
  Assert.assertThat((Set<String>) value, Matchers.contains("value"));
}
 
Example 10
public void testRootNameAccess() throws Exception
{
    final TypeFactory tf = MAPPER.getTypeFactory();
    AnnotationIntrospector ai = new JaxbAnnotationIntrospector();
    // If no @XmlRootElement, should get null (unless pkg has etc)
    assertNull(ai.findRootName(MAPPER.serializationConfig(),
            AnnotatedClassResolver.resolve(MAPPER.serializationConfig(),
            tf.constructType(SimpleBean.class), null)));
    // With @XmlRootElement, but no name, empty String
    PropertyName rootName = ai.findRootName(MAPPER.serializationConfig(),
            AnnotatedClassResolver.resolve(MAPPER.serializationConfig(),
            tf.constructType(NamespaceBean.class), null));
    assertNotNull(rootName);
    assertEquals("", rootName.getSimpleName());
    assertEquals("urn:class", rootName.getNamespace());

    // and otherwise explicit name
    rootName = ai.findRootName(MAPPER.serializationConfig(),
            AnnotatedClassResolver.resolve(MAPPER.serializationConfig(),
            tf.constructType(RootNameBean.class), null));
    assertNotNull(rootName);
    assertEquals("test", rootName.getSimpleName());
    assertNull(rootName.getNamespace());
}
 
Example 11
@SuppressWarnings("unchecked")
@Test
public void testGetValueSet() throws Exception {
  new Expectations() {
    {
      request.getHeaders("h1");
      result = Collections.enumeration(Arrays.asList("h1v"));
    }
  };

  HeaderProcessor processor = createProcessor("h1",
      TypeFactory.defaultInstance().constructCollectionType(Set.class, String.class),
      null, true);
  Object value = processor.getValue(request);
  Assert.assertThat((Set<String>) value, Matchers.contains("h1v"));
}
 
Example 12
Source Project: registry   Source File: Schema.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public JavaType typeFromId(DatabindContext databindContext, String s) {
    Type fieldType = Schema.Type.valueOf(s);
    JavaType javaType;
    switch (fieldType) {
        case NESTED:
            javaType = TypeFactory.defaultInstance().constructType(NestedField.class);
            break;
        case ARRAY:
            javaType = TypeFactory.defaultInstance().constructType(ArrayField.class);
            break;
        default:
            javaType = TypeFactory.defaultInstance().constructType(Field.class);
    }
    return javaType;
}
 
Example 13
@SuppressWarnings("unchecked")
@Test
public void testGetValueList() throws Exception {
  new Expectations() {
    {
      request.getParameterValues("name");
      result = new String[] {"value"};
    }
  };

  ParamValueProcessor processor = createProcessor("name",
      TypeFactory.defaultInstance().constructCollectionType(List.class, String.class),
      null, true);
  Object value = processor.getValue(request);
  Assert.assertThat((List<String>) value, Matchers.contains("value"));
}
 
Example 14
Source Project: servicecomb-java-chassis   Source File: ConverterMgr.java    License: Apache License 2.0 6 votes vote down vote up
private static void initPropertyMap() {
  PROPERTY_MAP.put(BooleanProperty.class, TypeFactory.defaultInstance().constructType(Boolean.class));

  PROPERTY_MAP.put(FloatProperty.class, TypeFactory.defaultInstance().constructType(Float.class));
  PROPERTY_MAP.put(DoubleProperty.class, TypeFactory.defaultInstance().constructType(Double.class));
  PROPERTY_MAP.put(DecimalProperty.class, TypeFactory.defaultInstance().constructType(BigDecimal.class));

  PROPERTY_MAP.put(ByteProperty.class, TypeFactory.defaultInstance().constructType(Byte.class));
  PROPERTY_MAP.put(ShortProperty.class, TypeFactory.defaultInstance().constructType(Short.class));
  PROPERTY_MAP.put(IntegerProperty.class, TypeFactory.defaultInstance().constructType(Integer.class));
  PROPERTY_MAP.put(BaseIntegerProperty.class, TypeFactory.defaultInstance().constructType(Integer.class));
  PROPERTY_MAP.put(LongProperty.class, TypeFactory.defaultInstance().constructType(Long.class));

  // stringProperty include enum scenes, not always be string type
  // if convert by StringPropertyConverter, can support enum scenes
  PROPERTY_MAP.put(StringProperty.class, TypeFactory.defaultInstance().constructType(String.class));

  PROPERTY_MAP.put(DateProperty.class, TypeFactory.defaultInstance().constructType(LocalDate.class));
  PROPERTY_MAP.put(DateTimeProperty.class, TypeFactory.defaultInstance().constructType(Date.class));

  PROPERTY_MAP.put(ByteArrayProperty.class, TypeFactory.defaultInstance().constructType(byte[].class));

  PROPERTY_MAP.put(FileProperty.class, TypeFactory.defaultInstance().constructType(Part.class));
}
 
Example 15
Source Project: netty-rest   Source File: ModelConverters.java    License: Apache License 2.0 6 votes vote down vote up
private boolean shouldProcess(Type type) {
    final Class<?> cls = TypeFactory.defaultInstance().constructType(type).getRawClass();
    if (cls.isPrimitive()) {
        return false;
    }
    String className = cls.getName();
    for (String packageName : skippedPackages) {
        if (className.startsWith(packageName)) {
            return false;
        }
    }
    for (String classToSkip : skippedClasses) {
        if (className.equals(classToSkip)) {
            return false;
        }
    }
    return true;
}
 
Example 16
Source Project: conf4j   Source File: YamlConverter.java    License: MIT License 6 votes vote down vote up
@Override
public T fromString(Type type, String value, Map<String, String> attributes) {
    requireNonNull(type, "type cannot be null");

    if (value == null) {
        return null;
    }

    try {
        JavaType javaType = TypeFactory.defaultInstance().constructType(type);
        ObjectReader objectReader = objectMapper.readerFor(javaType);
        return objectReader.readValue(value);
    } catch (IOException e) {
        // should never happen
        throw new IllegalStateException(e);
    }
}
 
Example 17
Source Project: data-highway   Source File: PayloadTypeFactory.java    License: Apache License 2.0 5 votes vote down vote up
static PayloadTypeFactory fromClass(Class<?> payloadClass) {
  return new PayloadTypeFactory() {
    private static final long serialVersionUID = 1L;

    @Override
    public JavaType construct(TypeFactory typeFactory) {
      return typeFactory.constructType(payloadClass);
    }
  };
}
 
Example 18
@Test
public void shouldValidateNothingForPrimitiveClass() {
  // given
  JavaType type = TypeFactory.defaultInstance().constructType(int.class);
  validator = createValidatorMock(true);

  // when
  format.getMapper().validateType(type, validator);

  // then
  Mockito.verifyZeroInteractions(validator);
}
 
Example 19
public static FieldDocumentationVisitorWrapper create(JavadocReader javadocReader,
        ConstraintReader constraintReader, DeserializationConfig deserializationConfig,
        TypeRegistry typeRegistry, TypeFactory typeFactory, SnippetTranslationResolver translationResolver,
        JsonProperty.Access skipAccessor) {
    FieldDocumentationVisitorContext context = new FieldDocumentationVisitorContext(
            javadocReader, constraintReader, deserializationConfig, translationResolver);
    return new FieldDocumentationVisitorWrapper(context, "", null, typeRegistry, typeFactory, skipAccessor);
}
 
Example 20
@Test
public void shouldFailForMapClass() {
  // given
  JavaType type = TypeFactory.defaultInstance().constructFromCanonical("java.util.HashMap<java.lang.String, java.lang.Integer>");
  validator = createValidatorMock(false);

  // then
  thrown.expect(SpinRuntimeException.class);
  thrown.expectMessage("[java.util.HashMap, java.lang.String, java.lang.Integer]");

  // when
  format.getMapper().validateType(type, validator);
}
 
Example 21
@Test
public void shouldFailForArrayClass() {
  // given
  JavaType type = TypeFactory.defaultInstance().constructType(Integer[].class);
  setValidatorMockResult(false);

  // then
  thrown.expect(IllegalArgumentException.class);
  thrown.expectMessage("[java.lang.Integer]");

  // when
  variablesResourceSpy.validateType(type);
}
 
Example 22
@Override
public JavaType convert(Swagger swagger, Object def) {
  Map<String, Object> vendorExtensions = findVendorExtensions(def);
  String canonical = SwaggerUtils.getClassName(vendorExtensions);
  if (StringUtils.isEmpty(canonical)) {
    return doConvert(swagger, def);
  }

  try {
    return TypeFactory.defaultInstance().constructFromCanonical(canonical);
  } catch (Throwable e) {
    // type not exist
    return OBJECT_JAVA_TYPE;
  }
}
 
Example 23
Source Project: kogito-runtimes   Source File: ForEachStateSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(ForEachState forEachState,
                      JsonGenerator gen,
                      SerializerProvider provider) throws IOException {

    // set defaults for foreach state
    forEachState.setType(DefaultState.Type.FOREACH);

    // serialize after setting default bean values...
    BeanSerializerFactory.instance.createSerializer(provider,
            TypeFactory.defaultInstance().constructType(ForEachState.class)).serialize(forEachState,
            gen,
            provider);
}
 
Example 24
Source Project: rest-schemagen   Source File: PaginatedResponseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDeserialize() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final TypeFactory typeFactory = mapper.getTypeFactory();

    final String content = "{\"members\": [{\"value\": \"foo\", \"_schema\":{\"links\": []}}, {\"value\": \"bar\", \"_schema\":{\"links\": []}}], \"offset\": 100, \"limit\": 10, \"total\": 2000, \"_schema\":{\"links\":[]}}";

    final JavaType nameWithSchemaType = typeFactory.constructParametricType(PaginatedResponse.class, Payload.class);
    final PaginatedResponse<Payload> listResponse = mapper.readValue(content, nameWithSchemaType);

    assertThat(listResponse.getMembers()).extracting(ObjectWithSchema::getObject).extracting(p -> p.value).containsExactly("foo", "bar");
    assertThat(listResponse.getLimit()).isEqualTo(10);
    assertThat(listResponse.getOffset()).isEqualTo(100);
    assertThat(listResponse.getTotal()).isEqualTo(2000);
}
 
Example 25
@Test
public void shouldValidateNothingForPrimitiveClass() {
  // given
  JavaType type = TypeFactory.defaultInstance().constructType(int.class);
  setValidatorMockResult(true);

  // when
  variablesResourceSpy.validateType(type);

  // then
  Mockito.verifyZeroInteractions(validator);
}
 
Example 26
Source Project: n2o-framework   Source File: TestDataProviderEngine.java    License: Apache License 2.0 5 votes vote down vote up
private List<DataSet> loadJson(InputStream is, PrimaryKeyType primaryKeyType, String primaryKeyFieldId) throws IOException {
    TypeFactory typeFactory = objectMapper.getTypeFactory();
    CollectionType collectionType = typeFactory.constructCollectionType(
            List.class, DataSet.class);
    List<DataSet> dataList = objectMapper.readValue(is, collectionType);
    for (DataSet data : dataList) {
        if (data.containsKey(primaryKeyFieldId) && integer.equals(primaryKeyType))
            data.put(primaryKeyFieldId, ((Number) data.get(primaryKeyFieldId)).longValue());
    }
    return dataList;
}
 
Example 27
Source Project: n2o-framework   Source File: TestDataProviderEngineTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateOnFile() throws IOException {
    TestDataProviderEngine engine = new TestDataProviderEngine();
    engine.setResourceLoader(new DefaultResourceLoader());
    engine.setPathOnDisk(testFolder.getRoot() + "/");

    N2oTestDataProvider provider = new N2oTestDataProvider();
    provider.setFile(testFile.getName());

    //Добавление новых данных
    provider.setOperation(create);

    Map<String, Object> inParamsForCreate = new LinkedHashMap<>();
    inParamsForCreate.put("id", 9L);
    inParamsForCreate.put("name", "test9");
    inParamsForCreate.put("type", "9");

    engine.invoke(provider, inParamsForCreate);

    //Проверка, что после create, json файл содержит ожидаемые данные
    ObjectMapper objectMapper = new ObjectMapper();
    TypeFactory typeFactory = objectMapper.getTypeFactory();
    CollectionType collectionType = typeFactory.constructCollectionType(
            List.class, HashMap.class);
    List<Map> result = objectMapper.readValue(testFile, collectionType);

    assertThat(result.size(), is(2));
    assertThat(result.get(0).get("id"), is(9));
    assertThat(result.get(0).get("name"), is("test9"));
    assertThat(result.get(0).get("type"), is("9"));
    assertThat(result.get(1).get("id"), is(1));
    assertThat(result.get(1).get("name"), is("test1"));
    assertThat(result.get(1).get("type"), is("1"));
}
 
Example 28
@Test
public void setType() {
  JavaType type = TypeFactory.defaultInstance().constructCollectionType(List.class, String.class);
  resolver.setType(type, vendorExtensions);

  Assert.assertEquals("java.util.List<java.lang.String>", vendorExtensions.get(SwaggerConst.EXT_JAVA_CLASS));
}
 
Example 29
Source Project: JuniperBot   Source File: JacksonUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static List mapJsonToObjectList(String json, Class clazz) {
    List list;
    TypeFactory t = TypeFactory.defaultInstance();
    try {
        list = OBJECT_MAPPER.readValue(json, t.constructCollectionType(ArrayList.class, clazz));
    } catch (IOException e) {
        throw new IllegalArgumentException("The given string value: "
                + json + " cannot be transformed to List of " + clazz.getName());
    }

    return list;
}
 
Example 30
Source Project: n2o-framework   Source File: TestDataProviderEngineTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateOnEmptyFile() throws IOException {
    TestDataProviderEngine engine = new TestDataProviderEngine();
    engine.setResourceLoader(new DefaultResourceLoader());
    engine.setPathOnDisk(testFolder.getRoot() + "/");

    N2oTestDataProvider provider = new N2oTestDataProvider();
    provider.setFile(emptyFile.getName());

    //Добавление новых данных в пустой файл
    provider.setOperation(create);

    Map<String, Object> inParamsForCreate = new LinkedHashMap<>();
    inParamsForCreate.put("name", "test10");
    inParamsForCreate.put("type", "10");

    engine.invoke(provider, inParamsForCreate);

    //Проверка, что после create, json файл содержит ожидаемые данные
    ObjectMapper objectMapper = new ObjectMapper();
    TypeFactory typeFactory = objectMapper.getTypeFactory();
    CollectionType collectionType = typeFactory.constructCollectionType(
            List.class, HashMap.class);
    List<Map> result = objectMapper.readValue(emptyFile, collectionType);

    assertThat(result.size(), is(1));
    assertThat(result.get(0).get("id"), is(1));
    assertThat(result.get(0).get("name"), is("test10"));
    assertThat(result.get(0).get("type"), is("10"));
}