Java Code Examples for com.fasterxml.jackson.databind.JavaType

The following are top voted examples for showing how to use com.fasterxml.jackson.databind.JavaType. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: validator-web   File: AbstractJackson2HttpMessageReader.java   Source Code and License 6 votes vote down vote up
@Override
protected boolean supports(Class<?> clazz) {
    JavaType javaType = getJavaType(clazz);
    AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>();
    if (this.objectMapper.canDeserialize(javaType, causeRef)) {
        return true;
    }
    Throwable cause = causeRef.get();
    if (cause != null) {
        String msg = "Failed to evaluate deserialization for type " + javaType;
        if (logger.isDebugEnabled()) {
            logger.warn(msg, cause);
        }
        else {
            logger.warn(msg + ": " + cause);
        }
    }
    return false;
}
 
Example 2
Project: rskj   File: LocalRLPTest.java   Source Code and License 6 votes vote down vote up
@BeforeClass
public static void init() throws ParseException, IOException {
    logger.info("    Initializing RLP tests...");
    String json = getJSON("rlptest");

    Assume.assumeFalse("Local test is not available", json.equals(""));

    ObjectMapper mapper = new ObjectMapper();
    JavaType type = mapper.getTypeFactory().
            constructMapType(HashMap.class, String.class, RLPTestCase.class);

    TEST_SUITE = mapper.readValue(json, type);
}
 
Example 3
Project: validator-web   File: AbstractJackson2HttpMessageReader.java   Source Code and License 6 votes vote down vote up
private Object readJavaType(JavaType javaType, HttpServletRequest request) {
    try {
        InputStream in = request.getInputStream();
        return this.objectMapper.readValue(in, javaType);
    } catch (IOException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    }
}
 
Example 4
Project: GitHub   File: Jackson2AfterBurnCodec.java   Source Code and License 5 votes vote down vote up
@Override
public void encode(OutputStream out, Object object) throws Exception {
    Class<?> clazz = object.getClass();
    JsonGenerator generator = constructGenerator(out);
    JavaType type = mapper.getTypeFactory().constructType(clazz);
    ObjectWriter writer = mapper.writerFor(type);
    writer.writeValue(generator, object);
    generator.close();
}
 
Example 5
Project: role-api   File: UsersSteps.java   Source Code and License 5 votes vote down vote up
@Then("^I should get all users with the following properties: (.*)$")
public void i_should_get_all_users_with_the_following_properties(List<String> properties) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, User.class);
    List<User> users = mapper.readValue(httpWorld.loadResponse().getBody(), type);

    for (String property : properties) {
        assertThat(users, everyItem(HasProperty.hasProperty(property)));
    }
}
 
Example 6
Project: goodees   File: ImmutableEventTypeResolver.java   Source Code and License 5 votes vote down vote up
JavaType typeFromId(String id, TypeFactory typeFactory) throws IllegalStateException {
    String className = basePackage + "." + generateClassName(id);
    try {
        return typeFactory.constructType(typeFactory.findClass(className));
    } catch (ClassNotFoundException ex) {
        throw new IllegalStateException("Could not find event class for type " + id, ex);
    }
}
 
Example 7
Project: iiif-apis   File: DeserializerModifier.java   Source Code and License 5 votes vote down vote up
@Override
public JsonDeserializer<?> modifyEnumDeserializer(DeserializationConfig config, JavaType type,
    BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
  if (Arrays.asList(Quality.class, Format.class).contains(type.getRawClass())) {
    return new EnumDeserializer((Class<? extends Enum>) type.getRawClass());
  }
  return super.modifyEnumDeserializer(config, type, beanDesc, deserializer);
}
 
Example 8
Project: fdk-java   File: JacksonCoercion.java   Source Code and License 5 votes vote down vote up
@Override
public Optional<Object> tryCoerceParam(InvocationContext currentContext, int param, InputEvent input, MethodWrapper method) {

    Type type = method.getTargetMethod().getGenericParameterTypes()[param];
    JavaType javaType = objectMapper(currentContext).constructType(type);

    return Optional.ofNullable(input.consumeBody(inputStream -> {
        try {
            return objectMapper(currentContext).readValue(inputStream, javaType);
        } catch (IOException e) {
            throw coercionFailed(type, e);
        }
    }));

}
 
Example 9
Project: lams   File: MappingJackson2HttpMessageConverter.java   Source Code and License 5 votes vote down vote up
private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) {
	try {
		return this.objectMapper.readValue(inputMessage.getBody(), javaType);
	}
	catch (IOException ex) {
		throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
	}
}
 
Example 10
Project: incubator-servicecomb-java-chassis   File: ArrayPropertyConverter.java   Source Code and License 5 votes vote down vote up
@Override
public JavaType doConvert(ClassLoader classLoader, String packageName, Swagger swagger, Object property) {
  ArrayProperty arrayProperty = (ArrayProperty) property;

  return findJavaType(classLoader,
      packageName,
      swagger,
      arrayProperty.getItems(),
      arrayProperty.getUniqueItems());
}
 
Example 11
Project: incubator-servicecomb-java-chassis   File: StringPropertyConverter.java   Source Code and License 5 votes vote down vote up
private static JavaType getOrCreateEnumByNames(ClassLoader classLoader, String packageName, List<String> enums) {
  String strEnums = enums.toString();

  synchronized (LOCK) {
    JavaType javaType = enumMap.get(strEnums);
    if (javaType != null) {
      return javaType;
    }

    String enumClsName = packageName + ".Enum" + enumMap.size();
    @SuppressWarnings("rawtypes")
    Class<? extends Enum> enumCls = JavassistUtils.createEnum(classLoader, enumClsName, enums);
    javaType = TypeFactory.defaultInstance().constructType(enumCls);
    enumMap.put(strEnums, javaType);

    return javaType;
  }
}
 
Example 12
Project: incubator-servicecomb-java-chassis   File: StringPropertyConverter.java   Source Code and License 5 votes vote down vote up
@Override
public JavaType doConvert(ClassLoader classLoader, String packageName, Swagger swagger, Object property) {
  StringProperty stringProperty = (StringProperty) property;

  List<String> enums = stringProperty.getEnum();
  return findJavaType(classLoader,
      packageName,
      swagger,
      stringProperty.getType(),
      stringProperty.getFormat(),
      enums);
}
 
Example 13
Project: SugarOnRest   File: LinkedModulesTests.java   Source Code and License 5 votes vote down vote up
public static void bulkLinkedRead1Test() throws IOException {
    SugarRestClient client = new SugarRestClient(TestAccount.Url, TestAccount.Username, TestAccount.Password);

    // -------------------Read Account Link Contact-------------------
    int count = 10;
    SugarRestResponse response = LinkedModules.bulkReadAccountLinkContact(client, count);

    assertNotNull(response);
    assertEquals(response.getStatusCode(), HttpStatus.SC_OK);

    String jsonData = response.getJData();
    assertNull(response.getData());
    assertNotNull(jsonData);

    // Deserialize json data to custom object
    ObjectMapper mapper = JsonObjectMapper.getMapper();
    JavaType type = mapper.getTypeFactory().constructCollectionType(ArrayList.class, CustomAcccount1.class) ;
    List<CustomAcccount1> customAccounts = mapper.readValue(jsonData, type);
    assertNotNull(customAccounts);
    assertEquals(customAccounts.size(), count);
}
 
Example 14
Project: autojackson   File: ComplexDeserializerCreator.java   Source Code and License 5 votes vote down vote up
@Override
protected MethodSpec implementDeserializeMethod(TypeElement typeElement, Builder deserializeMethodBuilder) {
    Optional<DeserializationConstructs> constructs = loadConstructs(typeElement);
    if (!constructs.isPresent()) {
        return deserializeMethodBuilder.addStatement("return null").build();
    }

    TypeElement enumTypeElement = constructs.get().getEnumTypeElement();
    ImmutableList<Element> enumValueElements = constructs.get().getEnumValueElements();
    ExecutableElement enumValueAccessorMethod = constructs.get().getEnumValueAccessorMethod();
    ExecutableElement enumInstanceAccessorMethod = constructs.get().getEnumInstanceAccessorMethod();

    String memberVariableName = this.processorUtil.createMemberVariableName(enumValueAccessorMethod);

    deserializeMethodBuilder.addStatement("$T codec = $L.getCodec()", ObjectCodec.class, JSON_PARSER_PARAMETER_NAME)
            .addStatement("$T rootNode = codec.readTree($L)", JsonNode.class, JSON_PARSER_PARAMETER_NAME)
            .addStatement("$T typeNode = rootNode.get($S)", JsonNode.class, memberVariableName)
            .beginControlFlow("if (typeNode == null)")
            .addStatement("$T javaType = $L.constructType($T.class)", JavaType.class, DESERIALIZATION_CONTEXT_PARAMETER_NAME, enumTypeElement)
            .addStatement("throw new $T($L, \"$L not present\", javaType, null)", InvalidTypeIdException.class, JSON_PARSER_PARAMETER_NAME, memberVariableName)
            .endControlFlow()
            .addStatement("$T type = codec.treeToValue(typeNode, $T.$L)", enumTypeElement, enumTypeElement, "class")
            .beginControlFlow("switch (type)");

    enumValueElements.forEach(enumValueElement -> deserializeMethodBuilder
            .beginControlFlow("case $L:", enumValueElement)
            .addStatement("return codec.treeToValue(rootNode, $T.$L.$L)", enumTypeElement, enumValueElement, enumInstanceAccessorMethod)
            .endControlFlow());

    return deserializeMethodBuilder.beginControlFlow("default :")
            .addStatement("return null")
            .endControlFlow()
            .endControlFlow()
            .build();
}
 
Example 15
Project: BlogBookApp   File: JacksonConverterFactory.java   Source Code and License 5 votes vote down vote up
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                                                        Retrofit retrofit) {
    JavaType javaType = mapper.getTypeFactory().constructType(type);
    ObjectReader reader = mapper.readerFor(javaType);
    return new JacksonResponseBodyConverter<>(reader, type);
}
 
Example 16
Project: incubator-servicecomb-java-chassis   File: ConverterMgr.java   Source Code and License 5 votes vote down vote up
public static JavaType findJavaType(ClassLoader classLoader, String packageName, Swagger swagger, Object def) {
  if (def == null) {
    return VOID_JAVA_TYPE;
  }
  Converter converter = converterMap.get(def.getClass());
  if (converter == null) {
    throw new Error("not support def type: " + def.getClass());
  }

  return converter.convert(classLoader, packageName, swagger, def);
}
 
Example 17
Project: dremio-oss   File: EnumTypeIdResolver.java   Source Code and License 5 votes vote down vote up
@Override
public JavaType typeFromId(DatabindContext context, String id) {
  JavaType type = nameToType.get(id.toLowerCase());
  if (type == null) {
    throw new NullPointerException(
        format("no subtype of %s found for enum value %s. existing mappings:\n%s",
            baseType, id, description));

  }
  return type;
}
 
Example 18
Project: incubator-servicecomb-java-chassis   File: ArrayModelConverter.java   Source Code and License 5 votes vote down vote up
@Override
public JavaType doConvert(ClassLoader classLoader, String packageName, Swagger swagger, Object model) {
  ArrayModel arrayModel = (ArrayModel) model;

  if (arrayModel.getItems() != null) {
    return ArrayPropertyConverter.findJavaType(classLoader,
        packageName,
        swagger,
        arrayModel.getItems(),
        false);
  }

  // don't know when will this happen.
  throw new Error("not support null array model items.");
}
 
Example 19
Project: rskj   File: StateTestSuite.java   Source Code and License 5 votes vote down vote up
public StateTestSuite(String json) throws IOException {

        ObjectMapper mapper = new ObjectMapper();
        JavaType type = mapper.getTypeFactory().
                constructMapType(HashMap.class, String.class, StateTestCase.class);

        testCases = new ObjectMapper().readValue(json, type);
    }
 
Example 20
Project: incubator-servicecomb-java-chassis   File: ClassUtils.java   Source Code and License 5 votes vote down vote up
public static Class<?> getOrCreateClass(ClassLoader classLoader, String packageName, Swagger swagger,
    Map<String, Property> properties,
    String clsName) {
  Class<?> cls = getClassByName(classLoader, clsName);
  if (cls != null) {
    return cls;
  }

  ClassConfig classConfig = new ClassConfig();
  classConfig.setClassName(clsName);

  if (null != properties) {
    for (Entry<String, Property> entry : properties.entrySet()) {
      JavaType propertyJavaType =
          ConverterMgr.findJavaType(classLoader,
              packageName,
              swagger,
              entry.getValue());
      classConfig.addField(entry.getKey(), propertyJavaType);
    }
  }

  cls = JavassistUtils.createClass(classLoader, classConfig);
  return cls;
}
 
Example 21
Project: incubator-servicecomb-java-chassis   File: ClassUtils.java   Source Code and License 5 votes vote down vote up
public static Class<?> getOrCreateBodyClass(OperationGenerator operationGenerator,
    List<BodyParameter> bodyParameters) {
  SwaggerGenerator swaggerGenerator = operationGenerator.getSwaggerGenerator();
  Method method = operationGenerator.getProviderMethod();
  String clsName = swaggerGenerator.ensureGetPackageName() + "." + method.getName() + "Body";
  Class<?> cls = getClassByName(swaggerGenerator.getClassLoader(), clsName);
  if (cls != null) {
    return cls;
  }

  ClassConfig classConfig = new ClassConfig();
  classConfig.setClassName(clsName);

  // 1.全是预备body
  // 2.预备body与明确body混合
  for (BodyParameter bp : bodyParameters) {
    JavaType javaType = ConverterMgr.findJavaType(swaggerGenerator.getClassLoader(),
        swaggerGenerator.ensureGetPackageName(),
        swaggerGenerator.getSwagger(),
        bp);
    classConfig.addField(bp.getName(), javaType);
  }

  return JavassistUtils.createClass(swaggerGenerator.getClassLoader(), classConfig);
}
 
Example 22
Project: rskj   File: DifficultyTestSuite.java   Source Code and License 5 votes vote down vote up
public DifficultyTestSuite(String json) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JavaType type = mapper.getTypeFactory().
            constructMapType(HashMap.class, String.class, DifficultyTestCase.class);

    Map<String, DifficultyTestCase> caseMap = new ObjectMapper().readValue(json, type);

    for (Map.Entry<String, DifficultyTestCase> e : caseMap.entrySet()) {
        e.getValue().setName(e.getKey());
        testCases.add(e.getValue());
    }

    Collections.sort(testCases, new Comparator<DifficultyTestCase>() {
        @Override
        public int compare(DifficultyTestCase t1, DifficultyTestCase t2) {
            return t1.getName().compareTo(t2.getName());
        }
    });
}
 
Example 23
Project: Spitfire   File: AbstractRequest.java   Source Code and License 5 votes vote down vote up
/**
 * Parses the network response {@link NetworkResponse} and returns the expected Type for the request.
 * @param response {@link NetworkResponse} The response for the request (Success or error).
 * @return Response object linked to a specific type
 */
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
    this.networkResponse = response;

    JavaType returnType = getReturnType();
    T returnData = null;
    if (returnType != null) {
        try {
            if (response.data != null) {
                returnData = SpitfireManager.getObjectMapper().readValue(response.data, returnType);
            }
        } catch (Exception e) {
            VolleyLog.e(e, "An error occurred while parsing network response:");
            returnData = null;
        }
    }

    if (returnData == null && classResponse != Void.class) {
        ParseError parseError = new ParseError(response);
        String content = "";
        if (response.data != null) {
            content = new String(response.data);
        }
        VolleyLog.e(parseError, "Return data is null. API returned : "+ content);
        return Response.error(parseError);
    }

    return Response.success(returnData, HttpHeaderParser.parseCacheHeaders(response));
}
 
Example 24
Project: incubator-servicecomb-java-chassis   File: ModelResolverExt.java   Source Code and License 5 votes vote down vote up
private void checkType(JavaType type) {
  // 原子类型/string在java中是abstract的
  if (type.getRawClass().isPrimitive()
      || propertyCreatorMap.containsKey(type.getRawClass())
      || String.class.equals(type.getRawClass())) {
    return;
  }

  String msg = "Must be a concrete type.";
  if (type.isMapLikeType()) {
    Class<?> keyTypeClass = type.getKeyType().getRawClass();
    if (!String.class.equals(keyTypeClass)) {
      // swagger中map的key只允许为string
      throw new Error("Type of key in map must be string, but got " + keyTypeClass.getName());
    }
  }

  if (type.isContainerType()) {
    checkType(type.getContentType());
    return;
  }

  if (type.getRawClass().isInterface()) {
    throw new ServiceCombException(type.getTypeName() + " is interface. " + msg);
  }

  if (Modifier.isAbstract(type.getRawClass().getModifiers())) {
    throw new ServiceCombException(type.getTypeName() + " is abstract class. " + msg);
  }
}
 
Example 25
Project: incubator-servicecomb-java-chassis   File: ModelResolverExt.java   Source Code and License 5 votes vote down vote up
@Override
public Model resolve(JavaType type, ModelConverterContext context, Iterator<ModelConverter> next) {
  // property is not a model
  if (propertyCreatorMap.containsKey(type.getRawClass())) {
    return null;
  }

  Model model = super.resolve(type, context, next);
  if (model == null) {
    return null;
  }

  checkType(type);

  // 只有声明model的地方才需要标注类型
  if (ModelImpl.class.isInstance(model) && !StringUtils.isEmpty(((ModelImpl) model).getName())) {
    setType(type, model.getVendorExtensions());
  }
  return model;
}
 
Example 26
Project: dremio-oss   File: EnumTypeIdResolver.java   Source Code and License 5 votes vote down vote up
@Override
public void init(JavaType baseType) {
  this.baseType = baseType;
  Class<?> baseClass = baseType.getRawClass();
  TypesEnum typesEnum = baseClass.getAnnotation(TypesEnum.class);
  while (baseClass != null && typesEnum == null) {
    baseClass = baseClass.getSuperclass();
    typesEnum = baseClass.getAnnotation(TypesEnum.class);
  }
  if (typesEnum == null) {
    throw new NullPointerException("Missing annotation TypesEnum on " + baseType.getRawClass());
  }
  SubTypeMapping mapping = new SubTypeMapping(typesEnum);
  TypeFactory defaultInstance = TypeFactory.defaultInstance();
  StringBuilder sb = new StringBuilder();
  for (Enum<?> e : mapping.getEnumConstants()) {
    String name = e.name();
    String className = mapping.getClassName(e);
    try {
      Class<?> c = Class.forName(className, false, this.getClass().getClassLoader());
      JavaType type = defaultInstance.uncheckedSimpleType(c);
      this.nameToType.put(name.toLowerCase(), type);
      this.typeToName.put(c, name);
      sb.append(name + " => " + c.getName() + "\n");
    } catch (ClassNotFoundException e1) {
      throw new RuntimeException(String.format(
          "class not found %s for enum value %s for base type %s",
          className, name, baseType
          ) , e1);
    }
  }
  this.description = sb.toString();
}
 
Example 27
Project: incubator-servicecomb-java-chassis   File: TestSwaggerUtils.java   Source Code and License 5 votes vote down vote up
@Test
public void testConverter() {
  SwaggerGenerator generator = new SwaggerGeneratorForTest(context, null);
  Swagger swagger = generator.getSwagger();
  ParamUtils.addDefinitions(swagger, User.class);
  Model model = swagger.getDefinitions().get("User");
  model.getVendorExtensions().clear();

  JavaType javaType = ConverterMgr.findJavaType(generator, model);
  checkJavaType(swagger, javaType);

  RefModel refModel = new RefModel();
  refModel.setReference("User");
  javaType = ConverterMgr.findJavaType(generator, refModel);
  checkJavaType(swagger, javaType);
}
 
Example 28
Project: rskj   File: NetworkStateExporterTest.java   Source Code and License 5 votes vote down vote up
private Map writeAndReadJson(Repository repository) throws Exception {
    NetworkStateExporter nse = new NetworkStateExporter(repository);
    Assert.assertTrue(nse.exportStatus(jsonFileName));

    InputStream inputStream = new FileInputStream(jsonFileName);
    String json = new String(ByteStreams.toByteArray(inputStream));

    ObjectMapper mapper = new ObjectMapper();
    JavaType type = mapper.getTypeFactory().constructType(HashMap.class);
    Map result = new ObjectMapper().readValue(json, type);
    return result;
}
 
Example 29
Project: camunda-task-dispatcher   File: ExternalTaskRestServiceImplTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testFetchAndLock() throws CamundaRestException, IOException {
    FetchExternalTasksDto dto = new FetchExternalTasksDto();
    List<LockedExternalTaskDto> externalTasks = service.fetchAndLock(dto);

    Assert.assertNotNull(externalTasks);
    Assert.assertEquals(1, externalTasks.size());
    Assert.assertNotNull(externalTasks.get(0));

    Mockito.verify(objectMapper, Mockito.times(1)).writeValueAsString(Mockito.any());
    Mockito.verify(objectMapper, Mockito.times(1)).getTypeFactory();
    Mockito.verify(objectMapper, Mockito.times(1)).readValue(Mockito.<InputStream>any(), Mockito.<JavaType>any());
    Mockito.verify(httpClient, Mockito.times(1)).execute(Mockito.any());
}
 
Example 30
Project: retrofit-converter-msgpack   File: MessagePackConverterFactory.java   Source Code and License 5 votes vote down vote up
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
        Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit)
{
    JavaType javaType = mapper.getTypeFactory().constructType(type);
    ObjectWriter writer = mapper.writerFor(javaType);
    return new MessagePackRequestBodyConverter<>(writer);
}
 
Example 31
Project: Spitfire   File: AbstractRequest.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the type for the response.
 * @return null, Array, List, Map or Object.
 */
@Nullable
private JavaType getReturnType() {
    if (classResponse == Void.class) {
        return null;
    } else if (classResponse.isArray()) {
        return TypeFactory.defaultInstance().constructArrayType(classResponse.getComponentType());
    } else if (classResponse == List.class) {
        return TypeFactory.defaultInstance().constructCollectionType(List.class, classResponse.getComponentType());
    } else if (classResponse == Map.class) {
        return TypeFactory.defaultInstance().constructMapType(Map.class, String.class, classResponse.getComponentType());
    }
    return TypeFactory.defaultInstance().constructType(classResponse);
}
 
Example 32
Project: incubator-servicecomb-java-chassis   File: FormProcessorCreator.java   Source Code and License 5 votes vote down vote up
@Override
public ParamValueProcessor create(Parameter parameter, Type genericParamType) {
  JavaType targetType = TypeFactory.defaultInstance().constructType(genericParamType);

  if (isPart(parameter)) {
    return new PartProcessor(parameter.getName(), targetType);
  }
  return new FormProcessor(parameter.getName(), targetType);
}
 
Example 33
Project: incubator-servicecomb-java-chassis   File: ProduceProcessor.java   Source Code and License 5 votes vote down vote up
default Object decodeResponse(InputStream input, JavaType type) throws Exception {
  if (input.available() == 0) {
    return null;
  }

  return doDecodeResponse(input, type);
}
 
Example 34
Project: xm-ms-config   File: TenantService.java   Source Code and License 5 votes vote down vote up
@SneakyThrows
private Map<String, Set<TenantState>> getTenantsList() {
    Optional<Configuration> maybeConfiguration = configurationService.findConfiguration(CONFIG_LIST_STORAGE);
    if (!maybeConfiguration.isPresent()) {
        return new HashMap<>();
    }
    Configuration configuration = maybeConfiguration.get();

    JavaType setType = om.getTypeFactory().constructCollectionType(Set.class, TenantState.class);
    JavaType stringType = om.getTypeFactory().constructType(String.class);
    JavaType mapType = om.getTypeFactory().constructMapType(Map.class, stringType, setType);

    return om.readValue(configuration.getContent(), mapType);
}
 
Example 35
Project: incubator-servicecomb-java-chassis   File: ProduceProcessor.java   Source Code and License 5 votes vote down vote up
default Object decodeResponse(Buffer buffer, JavaType type) throws Exception {
  if (buffer.length() == 0) {
    return null;
  }

  try (BufferInputStream input = new BufferInputStream(buffer.getByteBuf())) {
    return doDecodeResponse(input, type);
  }
}
 
Example 36
Project: incubator-servicecomb-java-chassis   File: ProduceTextPlainProcessor.java   Source Code and License 5 votes vote down vote up
@Override
public Object doDecodeResponse(InputStream input, JavaType type) throws Exception {
  // plainText类型,肯定是返回string的,想不出有其他类型的场景
  return IOUtils.toString(input, StandardCharsets.UTF_8);
  // TODO: 该方法尚需进一步修改
  //        Class<?> returnCls = type.getRawClass();
  //        if (returnCls.isPrimitive()) {
  //            // 处理char类型
  //            if (returnCls == char.class) {
  //                return ((String)result).charAt(0);
  //            }
  //            // 处理其他如int, long, boolean等类型
  //            return RestObjectMapper.INSTANCE.readValue((String)result, type);
  //        }
  //        else {
  //            // 处理如String等其他复杂类型
  //            // 对于更多处理不了的复杂类型建议使用"application/json"
  //            return returnCls.getConstructor(new Class<?>[] {String.class})
  //                    .newInstance((String)result);
  //        }
}
 
Example 37
Project: incubator-servicecomb-java-chassis   File: TestProduceJsonProcessor.java   Source Code and License 5 votes vote down vote up
@Test
public void testdecodeResponseNull() throws Exception {
  JavaType resultType = TypeFactory.unknownType();
  Object result = pp.decodeResponse(Buffer.buffer(), resultType);
  Assert.assertNull(result);

  ByteArrayInputStream is = new ByteArrayInputStream(new byte[] {});
  result = pp.decodeResponse(is, resultType);
  Assert.assertNull(result);
}
 
Example 38
Project: util   File: JsonMapper.java   Source Code and License 5 votes vote down vote up
/**
 * 反序列化复杂Collection如List<Bean>,
 * contructCollectionType()或contructMapType()构造类型, 然后调用本函数.
 * 
 * @see #createCollectionType(Class, Class...)
 */
@SuppressWarnings("unchecked")
public <T> T fromJson(@Nullable String jsonString, JavaType javaType) {
	if (StringUtils.isEmpty(jsonString)) {
		return null;
	}

	try {
		return (T) mapper.readValue(jsonString, javaType);
	} catch (IOException e) {
		logger.warn("parse json string error:" + jsonString, e);
		return null;
	}
}
 
Example 39
Project: teamcity-hashicorp-vault-plugin   File: AbstractJackson2HttpMessageConverter.java   Source Code and License 5 votes vote down vote up
@Override
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	JavaType javaType = getJavaType(type, contextClass);
	return readJavaType(javaType, inputMessage);
}
 
Example 40
Project: teamcity-hashicorp-vault-plugin   File: AbstractJackson2HttpMessageConverter.java   Source Code and License 5 votes vote down vote up
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	JavaType javaType = getJavaType(clazz, null);
	return readJavaType(javaType, inputMessage);
}
 
Example 41
Project: incubator-servicecomb-java-chassis   File: ProtobufSchemaUtils.java   Source Code and License 5 votes vote down vote up
public static WrapSchema getOrCreateSchema(Type type) {
  JavaType javaType = TypeFactory.defaultInstance().constructType(type);
  // List<String> -> java.util.List<java.lang.String>
  // List<List<String>> -> java.util.List<java.util.List<java.lang.String>>
  String key = javaType.toCanonical();
  return getOrCreateSchema(key, () -> {
    if (!isNeedWrap(javaType.getRawClass())) {
      // 可以直接使用
      Schema<?> schema = RuntimeSchema.createFrom(javaType.getRawClass());
      return WrapSchemaFactory.createSchema(schema, WrapType.NOT_WRAP);
    }

    // 需要包装
    WrapClassConfig config = new WrapClassConfig();
    config.setType(WrapType.NORMAL_WRAP);

    config.setClassName("gen.wrap.protobuf." + key.replaceAll("[<>]", "_").replace("[", "array_"));
    if (!Void.TYPE.isAssignableFrom(javaType.getRawClass())) {
      config.addField("field0", javaType);
    }

    JavassistUtils.genSingleWrapperInterface(config);

    return createWrapSchema(config);
  });
}
 
Example 42
Project: incubator-servicecomb-java-chassis   File: StandardResultCodec.java   Source Code and License 5 votes vote down vote up
@Override
public void init(ProtobufSchema schema, Type... types) {
  writer = ProtobufManager.getMapper().writer(schema);
  reader = ProtobufManager.getMapper().reader(schema);

  // 需要考虑void场景
  if (types.length == 1) {
    JavaType javaType = TypeFactory.defaultInstance().constructType(types[0]);
    writer = writer.forType(javaType);
    reader = reader.forType(javaType);
  }
}
 
Example 43
Project: retrofit-converter-msgpack   File: MessagePackConverterFactory.java   Source Code and License 5 votes vote down vote up
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type,
        Annotation[] annotations, Retrofit retrofit)
{
    JavaType javaType = mapper.getTypeFactory().constructType(type);
    ObjectReader reader = mapper.readerFor(javaType);
    return new MessagePackResponseBodyConverter<>(reader);
}
 
Example 44
Project: incubator-servicecomb-java-chassis   File: AbstractFieldCodec.java   Source Code and License 5 votes vote down vote up
private void initFieldMap(ProtobufSchema schema, Type[] types) {
  Iterator<ProtobufField> fieldIter = schema.getRootType().fields().iterator();
  for (int idx = 0; idx < schema.getRootType().getFieldCount(); idx++) {
    JavaType type = TypeFactory.defaultInstance().constructType(types[idx]);
    ProtobufField field = fieldIter.next();

    ReaderHelpData helpData = new ReaderHelpData();
    helpData.index = idx;
    helpData.deser = ((CseObjectReader) reader).findDeserializer(type);

    readerHelpDataMap.put(field.name, helpData);
  }
}
 
Example 45
Project: RestyPass   File: JsonResponseConverter.java   Source Code and License 5 votes vote down vote up
@Override
public Object convert(byte[] body, Type type, String contentType) {
    JavaType javaType = TypeFactory.defaultInstance().constructType(type);
    try {
        return objectMapper.readValue(body, javaType);
    } catch (IOException e) {
        log.error("JSON转换失败,javaType:{}", javaType, e);
    }
    return null;
}
 
Example 46
Project: simulacron   File: CqlMapper.java   Source Code and License 4 votes vote down vote up
AbstractCodec(JavaType javaType, RawType cqlType, int minProtocolVersion, boolean register) {
  this.javaType = javaType;
  this.cqlType = cqlType;
  this.minProtocolVersion = minProtocolVersion;
  if (register) {
    // only register if requested and meets protocol version requirement.
    register(this);
  }
}
 
Example 47
Project: wish-pay   File: JsonMapper.java   Source Code and License 4 votes vote down vote up
/**
 * 构造Collection类型.
 */
public JavaType contructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass) {
    return mapper.getTypeFactory().constructCollectionType(collectionClass, elementClass);
}
 
Example 48
Project: dremio-oss   File: EnumTypeIdResolver.java   Source Code and License 4 votes vote down vote up
@Override
public JavaType typeFromId(String id) {
  return typeFromId(null, id);
}
 
Example 49
Project: GitHub   File: JacksonConverterFactory.java   Source Code and License 4 votes vote down vote up
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
    Retrofit retrofit) {
  JavaType javaType = mapper.getTypeFactory().constructType(type);
  ObjectReader reader = mapper.readerFor(javaType);
  return new JacksonResponseBodyConverter<>(reader);
}
 
Example 50
Project: GitHub   File: JacksonConverterFactory.java   Source Code and License 4 votes vote down vote up
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
    Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
  JavaType javaType = mapper.getTypeFactory().constructType(type);
  ObjectWriter writer = mapper.writerFor(javaType);
  return new JacksonRequestBodyConverter<>(writer);
}
 
Example 51
Project: GitHub   File: JacksonParserFactory.java   Source Code and License 4 votes vote down vote up
@Override
public Parser<ResponseBody, ?> responseBodyParser(Type type) {
    JavaType javaType = mapper.getTypeFactory().constructType(type);
    ObjectReader reader = mapper.readerFor(javaType);
    return new JacksonResponseBodyParser<>(reader);
}
 
Example 52
Project: GitHub   File: JacksonParserFactory.java   Source Code and License 4 votes vote down vote up
@Override
public Parser<?, RequestBody> requestBodyParser(Type type) {
    JavaType javaType = mapper.getTypeFactory().constructType(type);
    ObjectWriter writer = mapper.writerFor(javaType);
    return new JacksonRequestBodyParser<>(writer);
}
 
Example 53
Project: fishing-village   File: JacksonParameterParser.java   Source Code and License 4 votes vote down vote up
/**
 * 生成java type
 * @param parameter    method parameter
 * @return             java type
 */
private JavaType generateJavaType(MethodParameter parameter) {
    Class<?> parameterClass = parameter.getParameterType();
    Class<?> genericClass = getGenericType(parameterClass, parameter);
    if (Objects.isNull(genericClass)) {
        return SimpleType.constructUnsafe(parameterClass);
    }
    return OBJECT_MAPPER.getTypeFactory().constructParametricType(parameter.getParameterType(), genericClass);
}
 
Example 54
Project: GitHub   File: Jackson2Codec.java   Source Code and License 4 votes vote down vote up
@Override
public void encode(OutputStream out, Object object) throws Exception {
    Class<?> clazz = object.getClass();
    JsonGenerator generator = constructGenerator(out);
    JavaType type = mapper.getTypeFactory().constructType(clazz);
    ObjectWriter writer = mapper.writerFor(type);
    writer.writeValue(generator, object);
    generator.flush();
    generator.close();
}
 
Example 55
Project: BIMplatform   File: JsonUtils.java   Source Code and License 4 votes vote down vote up
public static <T> List<T> readList(byte[] dataBytes, Class<T> classType) throws JsonParseException, JsonMappingException, IOException {
	ObjectMapper objectMapper = new ObjectMapper();
	JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, classType);
	return objectMapper.readValue(dataBytes, javaType);
}
 
Example 56
Project: SugarOnRest   File: WikiTests.java   Source Code and License 4 votes vote down vote up
public void bulkLinkedRead2Test() throws IOException {
    /*
    package com.sugaronrest.tests;

    import com.fasterxml.jackson.databind.JavaType;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.sugaronrest.*;
    import com.sugaronrest.modules.*;
    import com.sugaronrest.tests.custommodels.CustomAcccount2;
    import com.sugaronrest.utils.JsonObjectMapper;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    */

    String url = "http://demo.suiteondemand.com/service/v4_1/rest.php";
    String username = "will";
    String password = "will";

    SugarRestClient client = new SugarRestClient(url, username, password);

    SugarRestRequest request = new SugarRestRequest(RequestType.LinkedBulkRead);
    request.setModuleName("Accounts");
    request.getOptions().setMaxResult(5);

    List<String> selectedFields = new ArrayList<String>();

    selectedFields.add(NameOf.Accounts.Id);
    selectedFields.add(NameOf.Accounts.Name);
    selectedFields.add(NameOf.Accounts.Industry);
    selectedFields.add(NameOf.Accounts.Website);
    selectedFields.add(NameOf.Accounts.ShippingAddressCity);

    request.getOptions().setSelectFields(selectedFields);

    Map<Object, List<String>> linkedListInfo = new HashMap<Object, List<String>>();

    List<String> selectContactFields = new ArrayList<String>();
    selectContactFields.add(NameOf.Contacts.FirstName);
    selectContactFields.add(NameOf.Contacts.LastName);
    selectContactFields.add(NameOf.Contacts.Title);
    selectContactFields.add(NameOf.Contacts.Description);
    selectContactFields.add(NameOf.Contacts.PrimaryAddressPostalcode);

    linkedListInfo.put(Contacts.class, selectContactFields);
    request.getOptions().setLinkedModules(linkedListInfo);

    SugarRestResponse response = client.execute(request);

    String jsonData = response.getJData();

    // Deserialize json data to custom object
    ObjectMapper mapper = JsonObjectMapper.getMapper();
    JavaType type = mapper.getTypeFactory().constructCollectionType(ArrayList.class, CustomAcccount2.class) ;
    List<CustomAcccount2> customAccounts = mapper.readValue(jsonData, type);

    System.out.println(jsonData);
    System.out.println(response.getJsonRawRequest());
    System.out.println(response.getJsonRawResponse());
}
 
Example 57
Project: GitHub   File: JacksonParserFactory.java   Source Code and License 4 votes vote down vote up
@Override
public Parser<ResponseBody, ?> responseBodyParser(Type type) {
    JavaType javaType = mapper.getTypeFactory().constructType(type);
    ObjectReader reader = mapper.readerFor(javaType);
    return new JacksonResponseBodyParser<>(reader);
}
 
Example 58
Project: GitHub   File: JacksonParserFactory.java   Source Code and License 4 votes vote down vote up
@Override
public Parser<?, RequestBody> requestBodyParser(Type type) {
    JavaType javaType = mapper.getTypeFactory().constructType(type);
    ObjectWriter writer = mapper.writerFor(javaType);
    return new JacksonRequestBodyParser<>(writer);
}
 
Example 59
Project: koryphe   File: SimpleClassNameIdResolver.java   Source Code and License 4 votes vote down vote up
@Override
public JavaType typeFromId(final DatabindContext context, final String id) {
    return defaultResolver.typeFromId(context, getClassName(id, baseType));
}
 
Example 60
Project: incubator-servicecomb-java-chassis   File: StringPropertyConverter.java   Source Code and License 4 votes vote down vote up
public static JavaType findJavaType(ClassLoader classLoader, String packageName, Swagger swagger, String type,
    String format, List<String> enums) {
  if (!isEnum(enums)) {
    return ConverterMgr.findJavaType(type, format);
  }

  // enum,且需要动态生成class
  return getOrCreateEnumByNames(classLoader, packageName, enums);
}