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

The following examples show how to use com.fasterxml.jackson.databind.type.TypeFactory. 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: TestDataProviderEngine.java    From n2o-framework with Apache License 2.0 7 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 #2
Source File: ModelConverters.java    From netty-rest with 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 #3
Source File: Schema.java    From registry with 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 #4
Source File: TestFormProcessor.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: ConverterMgr.java    From servicecomb-java-chassis with 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 #6
Source File: JsonHelper.java    From camunda-bpm-elasticsearch with 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 #7
Source File: TestHeaderProcessor.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: TestJaxbAnnotationIntrospector.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: YamlConverter.java    From conf4j with 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 #10
Source File: RestServerCodecFilterTest.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: TestFormProcessor.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@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 #12
Source File: PojoConsumerOperationMeta.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
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 #13
Source File: RedisGenericCacheManager.java    From faster-framework-project with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: StreamConverterTest.java    From riptide with 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 #15
Source File: JdbcComponentTestIT.java    From components with 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 #16
Source File: JacksonMapper.java    From spring-cloud-function with 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 #17
Source File: BodyProcessorCreator.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@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 #18
Source File: FormProcessorCreator.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public ParamValueProcessor create(Parameter parameter, Type genericParamType) {
  JavaType targetType =
      genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType);

  if (isPart(parameter)) {
    return new PartProcessor((FormParameter) parameter, genericParamType);
  }
  return new FormProcessor((FormParameter) parameter, targetType);
}
 
Example #19
Source File: JobParametersDeserializer.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Object deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
    if(jobsManager == null) {
        throw new IllegalStateException("This deserializer need a jobsManager instance, see 'JobParametersDeserializer.setJobsManager'");
    }
    final JsonStreamContext jsc = p.getParsingContext();
    String paramName = null;
    JsonStreamContext parent = jsc;
    while(parent != null) {
        paramName = parent.getCurrentName();
        if(paramName != null) {
            break;
        }
        parent = parent.getParent();
    }
    if(parent == null) {
        throw new NullPointerException("Something wrong: we can not find our parent object, " +
          "may be you use this deserializer on custom object?");
    }
    JobParameters.Builder r = (JobParameters.Builder) parent.getParent().getCurrentValue();
    String jobType = r.getType();
    JobDescription desc = jobsManager.getDescription(jobType);
    JobParameterDescription param = desc.getParameters().get(paramName);
    TypeFactory typeFactory = ctx.getTypeFactory();
    JavaType type;
    if(param == null) {
        type = typeFactory.constructType(Object.class);
    } else {
        type = typeFactory.constructType(param.getType());
    }
    JsonDeserializer<Object> deser = ctx.findNonContextualValueDeserializer(type);
    try {
        return deser.deserialize(p, ctx);
    } catch (Exception e) {
        throw new RuntimeException("Can not deserialize '" + jobType + "." + paramName + "' job parameter ", e );
    }
}
 
Example #20
Source File: ExecutionRestServiceInteractionTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidationOnPutSingleLocalSerializableVariableFromJson() throws Exception {
  boolean previousIsValidationEnabled = processEngine.getProcessEngineConfiguration().isDeserializationTypeValidationEnabled();
  DeserializationTypeValidator previousValidator = processEngine.getProcessEngineConfiguration().getDeserializationTypeValidator();

  DeserializationTypeValidator validatorMock = mock(DeserializationTypeValidator.class);
  when(validatorMock.validate(anyString())).thenReturn(true);
  when(processEngine.getProcessEngineConfiguration().isDeserializationTypeValidationEnabled()).thenReturn(true);
  when(processEngine.getProcessEngineConfiguration().getDeserializationTypeValidator()).thenReturn(validatorMock);

  try {
    ObjectMapper mapper = new ObjectMapper();
    String jsonBytes = mapper.writeValueAsString("test");
    String typeName = TypeFactory.defaultInstance().constructType(String.class).toCanonical();

    String variableKey = "aVariableKey";

    given()
      .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey)
      .multiPart("data", jsonBytes, MediaType.APPLICATION_JSON)
      .multiPart("type", typeName, MediaType.TEXT_PLAIN)
    .expect()
      .statusCode(Status.NO_CONTENT.getStatusCode())
    .when()
      .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL);

    verify(validatorMock).validate("java.lang.String");
    verifyNoMoreInteractions(validatorMock);

    verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey),
        argThat(EqualsObjectValue.objectValueMatcher().isDeserialized().value("test")));
  } finally {
    when(processEngine.getProcessEngineConfiguration().isDeserializationTypeValidationEnabled()).thenReturn(previousIsValidationEnabled);
    when(processEngine.getProcessEngineConfiguration().getDeserializationTypeValidator()).thenReturn(previousValidator);
  }
}
 
Example #21
Source File: ConsumerArgumentsMapperCreator.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
protected void processBeanParameter(int consumerParamIdx, java.lang.reflect.Parameter consumerParameter) {
  ConsumerBeanParamMapper mapper = new ConsumerBeanParamMapper(
      this.providerMethod.getParameters()[consumerParamIdx].getName());
  JavaType consumerType = TypeFactory.defaultInstance().constructType(consumerParameter.getParameterizedType());
  for (BeanPropertyDefinition propertyDefinition : serializationConfig.introspect(consumerType).findProperties()) {
    String parameterName = collectParameterName(providerMethod, propertyDefinition);
    Integer swaggerIdx = findSwaggerParameterIndex(parameterName);
    if (swaggerIdx == null) {
      // unknown field, ignore it
      LOGGER.warn(
          "new consumer invoke old version producer, bean parameter({}) is not exist in contract, method={}:{}.",
          parameterName, providerMethod.getDeclaringClass().getName(), providerMethod.getName());
      continue;
    }

    Getter<Object, Object> getter;
    if (propertyDefinition.hasGetter()) {
      getter = LambdaMetafactoryUtils.createLambda(propertyDefinition.getGetter().getAnnotated(), Getter.class);
    } else {
      getter = LambdaMetafactoryUtils.createGetter(propertyDefinition.getField().getAnnotated());
    }

    mapper.addField(parameterName, getter);
    processedSwaggerParamters.add(parameterName);
  }
  mappers.add(mapper);
}
 
Example #22
Source File: JsonTreeMapJsonToJavaTest.java    From camunda-spin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldMapListByCanonicalString() throws JsonProcessingException {
  JavaType desiredType =
      TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, Order.class);

  List<Order> orders = JSON(EXAMPLE_JSON_COLLECTION).mapTo(desiredType.toCanonical());

  assertThat(orders.size()).isEqualTo(1);
  assertIsExampleOrder(orders.get(0));
}
 
Example #23
Source File: JsonDeserializationValidationTest.java    From camunda-spin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFailOnceForMapClass() {
  // given
  JavaType type = TypeFactory.defaultInstance().constructFromCanonical("java.util.HashMap<java.lang.String, java.lang.String>");
  validator = createValidatorMock(false);

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

  // when
  format.getMapper().validateType(type, validator);
}
 
Example #24
Source File: VirtualHostAddressingSepTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Parameterized.Parameters
public static List<TestCaseModel> testInputs() throws IOException {
    final ObjectMapper objectMapper = new ObjectMapper();
    TypeFactory typeFactory = objectMapper.getTypeFactory();
    InputStream jsonData = VirtualHostAddressingSepTest.class.getResourceAsStream(TEST_FILE_PATH);
    return objectMapper.readValue(jsonData,
                                  typeFactory.constructCollectionType(List.class, TestCaseModel.class));
}
 
Example #25
Source File: TestDataProviderEngineTest.java    From n2o-framework with 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"));
}
 
Example #26
Source File: JacksonUtil.java    From JuniperBot with 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 #27
Source File: TestModelResolverExt.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@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 #28
Source File: TestDataProviderEngineTest.java    From n2o-framework with 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 #29
Source File: MinimalClassNameIdResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected MinimalClassNameIdResolver(JavaType baseType, TypeFactory typeFactory)
{
    super(baseType, typeFactory);
    String base = baseType.getRawClass().getName();
    int ix = base.lastIndexOf('.');
    if (ix < 0) { // can this ever occur?
        _basePackageName = "";
        _basePackagePrefix = ".";
    } else {
        _basePackagePrefix = base.substring(0, ix+1);
        _basePackageName = base.substring(0, ix);
    }
}
 
Example #30
Source File: CyclopsTypeModifier.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Override
public JavaType modifyType(JavaType type, Type jdkType, TypeBindings bindings, TypeFactory typeFactory) {

    if (type.isReferenceType() || type.isContainerType()) {
        return type;
    }
    final Class<?> raw = type.getRawClass();
    if (raw == Option.class)
        return ReferenceType.upgradeFrom(type, type.containedTypeOrUnknown(0));

    if (raw == Eval.class)
        return ReferenceType.upgradeFrom(type, type.containedTypeOrUnknown(0));
    if (raw == Trampoline.class)
        return ReferenceType.upgradeFrom(type, type.containedTypeOrUnknown(0));
    if (raw == Either.class)
        return ReferenceType.upgradeFrom(type, type.containedTypeOrUnknown(0));

    if (raw == Value.class)
        return ReferenceType.upgradeFrom(type, type.containedTypeOrUnknown(0));

    for(Class c : collectionLikeTypes){
        if (c.isAssignableFrom(raw)) {
            //   return CollectionType.upgradeFrom(type, type.containedTypeOrUnknown(0));
            return CollectionLikeType.upgradeFrom(type, type.containedTypeOrUnknown(0));
        }
    }



    return type;
}