org.codehaus.jackson.type.TypeReference Java Examples

The following examples show how to use org.codehaus.jackson.type.TypeReference. 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: JsonUtils.java    From bbs with GNU Affero General Public License v3.0 8 votes vote down vote up
/**
 * JSON串转换为Java泛型对象,可以是各种类型,此方法最为强大。用法看测试用例。
 * @param <T>
 * @param jsonString JSON字符串
* @param tr TypeReference,例如: new TypeReference< List<FamousUser> >(){}
 * @return List对象列表
 */
public static <T> T toGenericObject(String jsonString, TypeReference<T> tr) {
 
    if (jsonString == null || "".equals(jsonString)) {
        return null;
    } else {
        try {
            return objectMapper.readValue(jsonString, tr);
        } catch (Exception e) {
         //	e.printStackTrace();
         if (logger.isErrorEnabled()) {
         	logger.error("JSON串转换为Java泛型对象",e);
		    }
        
        }
    }
    return null;
}
 
Example #2
Source File: DiagnosticsStreamMessage.java    From samza with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to use {@link SamzaObjectMapper} to deserialize {@link ContainerModel}s.
 * {@link SamzaObjectMapper} provides several conventions and optimizations for deserializing containerModels.
 * @return
 */
private static Map<String, ContainerModel> deserializeContainerModelMap(
    String serializedContainerModel) {
  Map<String, ContainerModel> containerModelMap = null;
  ObjectMapper samzaObjectMapper = SamzaObjectMapper.getObjectMapper();

  try {
    if (serializedContainerModel != null) {
      containerModelMap = samzaObjectMapper.readValue(serializedContainerModel, new TypeReference<Map<String, ContainerModel>>() {
      });
    }
  } catch (IOException e) {
    LOG.error("Exception in deserializing container model ", e);
  }

  return containerModelMap;
}
 
Example #3
Source File: ProjectService.java    From jira-rest-client with Apache License 2.0 6 votes vote down vote up
public Project getProjectDetail(String idOrKey) throws IOException {
	if (client == null)
		throw new IllegalStateException("HTTP Client not Initailized");
	
	client.setResourceName(Constants.JIRA_RESOURCE_PROJECT + "/" + idOrKey);
	ClientResponse response = client.get();
				
	String content = response.getEntity(String.class);	
	
	ObjectMapper mapper = new ObjectMapper();
	mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true);
	
	TypeReference<Project> ref = new TypeReference<Project>(){};
	Project prj = mapper.readValue(content, ref);
	
	return prj;
}
 
Example #4
Source File: CountryDaoLocalJsonFileImpl.java    From website with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Map<String, Country> loadCountries() throws Exception {
	ClassPathResource classPathResource = new ClassPathResource("countries.json");
	InputStreamReader reader = new InputStreamReader(classPathResource.getInputStream());
	try {
		Map<String, String> countryMap = new ObjectMapper().readValue(classPathResource.getInputStream(), new TypeReference<Map<String, String>>() {});
		Map<String, Country> countries = new LinkedHashMap<String, Country>();
		for (String key : countryMap.keySet()) {
			Country country = new Country();
			country.setName(WordUtils.capitalizeFully(key));
			country.setCode(countryMap.get(key));
			countries.put(country.getCode(), country);
		}
		return countries;
	} finally {
		reader.close();
	}
}
 
Example #5
Source File: IssueService.java    From jira-rest-client with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of all issue types visible to the user
 *
 * @return List list of IssueType
 *
 * @throws IOException json decoding failed
 */
public List<IssueType> getAllIssueTypes() throws IOException {

    client.setResourceName(Constants.JIRA_RESOURCE_ISSUETYPE);

    ClientResponse response = client.get();
    String content = response.getEntity(String.class);

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true);

    TypeReference<List<IssueType>> ref = new TypeReference<List<IssueType>>() {
    };
    List<IssueType> issueTypes = mapper.readValue(content, ref);

    return issueTypes;
}
 
Example #6
Source File: TaskPartitionAssignmentManager.java    From samza with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the task partition assignments from the underlying storage layer.
 * @return the task partition assignments.
 */
public Map<SystemStreamPartition, List<String>> readTaskPartitionAssignments() {
  try {
    Map<SystemStreamPartition, List<String>> sspToTaskNamesMap = new HashMap<>();
    Map<String, byte[]> allMetadataEntries = metadataStore.all();
    for (Map.Entry<String, byte[]> entry : allMetadataEntries.entrySet()) {
      SystemStreamPartition systemStreamPartition = deserializeSSPFromJson(entry.getKey());
      String taskNamesAsJson = valueSerde.fromBytes(entry.getValue());
      List<String> taskNames = taskNamesMapper.readValue(taskNamesAsJson, new TypeReference<List<String>>() { });
      sspToTaskNamesMap.put(systemStreamPartition, taskNames);
    }
    return sspToTaskNamesMap;
  } catch (Exception e) {
    throw new SamzaException("Exception occurred when reading task partition assignments.", e);
  }
}
 
Example #7
Source File: AbstractCommand.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
protected <T> T readValue(HttpResponseWrapper response, TypeReference<T> valueType,
        ApplicationContext currentContext) {
    try {
        return currentContext.getObjectMapper().readValue(response.getContent(), valueType);
    } catch (IOException ioe) {
        throw new CLIException(REASON_IO_ERROR, ioe);
    }

}
 
Example #8
Source File: JsonConfigLoader.java    From stagen with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> getConfigMap(File dataFile) throws ExecutorException {
    try {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> out = mapper.readValue(dataFile,
                new TypeReference<Map<String, Object>>() {});
        return out;
    }
    catch(IOException ex) {
        throw new ExecutorException(ex);
    }
}
 
Example #9
Source File: ForumITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
protected List<MessageVO> parseMessageArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<MessageVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #10
Source File: GroupMetadataType.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public Map<String, ?> fromString(String stringValue)
{
	try
	{
		Map<String, Object> metadataValues = new HashMap<String, Object>(metadataTypes.size());

		if (stringValue == null || stringValue.isEmpty())
			return metadataValues;

		Map<String, String> stringValues = new ObjectMapper().readValue(stringValue, new TypeReference<Map<String, String>>()
		{
		});

		for (MetadataType metadataType : metadataTypes)
		{
			String uniqueName = metadataType.getUniqueName();
			Object metadataValue = metadataType.getConverter().fromString(stringValues.get(uniqueName));
			if (metadataValue != null)
				metadataValues.put(uniqueName, metadataValue);
		}

		return metadataValues;
	}
	catch (IOException e)
	{
		throw new RuntimeException(e);
	}
}
 
Example #11
Source File: JsonMetadataParser.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public List<MetadataType> parse(InputStream inputStream)
{
	/**
	 *  FIXME: The ContextClassLoader is switched in order to work with {@link org.codehaus.jackson.map.jsontype.impl#typeFromId(String)}
	 *  The current ContextClassLoader is the one from the tool making the call (ie. ContentTool) so it doesn't contain the actual implementation of metadatatypes
	 *  The classloader is switched back later in the finally clause (as it HAS to be restored)
	 *
	 *  See JACKSON-350.
	 */
	ClassLoader cl = Thread.currentThread().getContextClassLoader();
	try
	{
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.getDeserializationConfig().addMixInAnnotations(MetadataType.class, MetadataTypeMixin.class);
		objectMapper.getDeserializationConfig().addMixInAnnotations(ListMetadataType.class, ListMetadataTypeMixin.class);
		Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
		return objectMapper.readValue(inputStream, new TypeReference<List<MetadataType>>() {});
	}
	catch (IOException e)
	{
		throw new RuntimeException(e);
	}
	finally
	{
		Thread.currentThread().setContextClassLoader(cl);
	}
}
 
Example #12
Source File: EnrichmentValue.java    From metron with Apache License 2.0 5 votes vote down vote up
public Map<String, Object> stringToValue(String s){
    try {
        return _mapper.get().readValue(s, new TypeReference<Map<String, Object>>(){});
    } catch (IOException e) {
        throw new RuntimeException("Unable to convert string to metadata: " + s);
    }
}
 
Example #13
Source File: CourseGroupMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
protected List<GroupVO> parseGroupArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<GroupVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #14
Source File: TaskUtil.java    From helix with Apache License 2.0 5 votes vote down vote up
/**
 * Deserialize a single string into a map of job-level configurations
 * @param commandConfig the serialized job config map
 * @return a map of job config key to config value
 */
// TODO: move this to the JobConfig
@Deprecated
public static Map<String, String> deserializeJobCommandConfigMap(String commandConfig) {
  ObjectMapper mapper = new ObjectMapper();
  try {
    Map<String, String> commandConfigMap =
        mapper.readValue(commandConfig, new TypeReference<HashMap<String, String>>() {
        });
    return commandConfigMap;
  } catch (IOException e) {
    LOG.error("Error deserializing " + commandConfig, e);
  }
  return Collections.emptyMap();
}
 
Example #15
Source File: BTC100Exchange.java    From libdynticker with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public String parseTicker(JsonNode node, Pair pair) throws IOException {
	TypeReference<List<JsonNode>> typeRef = new TypeReference<List<JsonNode>>() {};
	List<JsonNode> nodes = new ObjectMapper().readValue(node, typeRef);
	String id = BTC_CNY_ID;
	int pos = BTC_CNY_POS;
	if(pair.equals(LTC_CNY)) {
		id = LTC_CNY_ID;
		pos = LTC_CNY_POS;
	} else if(pair.equals(DOGE_CNY)) {
		id = DOGE_CNY_ID;
		pos = DOGE_CNY_POS;
	}
	return nodes.get(pos).get(id).asText();
}
 
Example #16
Source File: CoursesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
protected List<CourseVO> parseCourseArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<CourseVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #17
Source File: ZKAssistedDiscovery.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
JacksonInstanceSerializer(ObjectReader objectReader, ObjectWriter objectWriter,
    TypeReference<ServiceInstance<T>> typeRef)
{
  this.objectReader = objectReader;
  this.objectWriter = objectWriter;
  this.typeRef = typeRef;
}
 
Example #18
Source File: CatalogITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
protected List<UserVO> parseUserArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<UserVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #19
Source File: CatalogITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
protected List<UserVO> parseUserArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<UserVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #20
Source File: TestData.java    From samza with Apache License 2.0 5 votes vote down vote up
@Override
public PageView fromBytes(byte[] bytes) {
  try {
    return mapper.readValue(new String(bytes, "UTF-8"), new TypeReference<PageView>() { });
  } catch (Exception e) {
    throw new SamzaException(e);
  }
}
 
Example #21
Source File: TestTasksResource.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTasksWithInvalidJobId() throws IOException {
  String requestUrl = String.format("v1/jobs/%s/%s/tasks", MockJobProxy.JOB_INSTANCE_1_NAME, "BadJobId");
  Response resp = target(requestUrl).request().get();
  assertEquals(400, resp.getStatus());
  final Map<String, String> errorMessage = objectMapper.readValue(resp.readEntity(String.class), new TypeReference<Map<String, String>>() { });
  assertTrue(errorMessage.get("message"), errorMessage.get("message").contains("Invalid arguments for getTasks. "));
  resp.close();
}
 
Example #22
Source File: TestTasksResource.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTasksWithInvalidJobName() throws IOException {
  String requestUrl = String.format("v1/jobs/%s/%s/tasks", "BadJobName", MockJobProxy.JOB_INSTANCE_4_ID);
  Response resp = target(requestUrl).request().get();
  assertEquals(400, resp.getStatus());
  final Map<String, String> errorMessage = objectMapper.readValue(resp.readEntity(String.class), new TypeReference<Map<String, String>>() { });
  assertTrue(errorMessage.get("message"), errorMessage.get("message").contains("Invalid arguments for getTasks. "));
  resp.close();
}
 
Example #23
Source File: TestJobsResource.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutMissingStatus()
    throws IOException {
  Response resp = target(String.format("v1/jobs/%s/%s", MockJobProxy.JOB_INSTANCE_2_NAME, MockJobProxy.JOB_INSTANCE_2_ID)).request()
      .put(Entity.form(new Form()));
  assertEquals(400, resp.getStatus());

  final Map<String, String> errorMessage = objectMapper.readValue(resp.readEntity(String.class), new TypeReference<Map<String, String>>() { });
  assertTrue(errorMessage.get("message").contains("status"));
  resp.close();
}
 
Example #24
Source File: TestJobsResource.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutBadJobStatus()
    throws IOException {
  Response resp = target(String.format("v1/jobs/%s/%s", MockJobProxy.JOB_INSTANCE_2_NAME, MockJobProxy.JOB_INSTANCE_2_ID))
      .queryParam("status", "BADSTATUS").request().put(Entity.form(new Form()));
  assertEquals(400, resp.getStatus());

  final Map<String, String> errorMessage = objectMapper.readValue(resp.readEntity(String.class), new TypeReference<Map<String, String>>() { });
  assertTrue(errorMessage.get("message").contains("BADSTATUS"));
  resp.close();
}
 
Example #25
Source File: ClusterJspHelper.java    From RDFS with Apache License 2.0 5 votes vote down vote up
NameNodeMXBeanObject(InetSocketAddress namenode, Configuration conf)
  throws IOException, URISyntaxException {
  httpAddress = DFSUtil.getInfoServer(namenode, conf, isAvatar);
  InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(httpAddress);
  String nameNodeMXBeanContent = DFSUtil.getHTMLContent(
      new URI("http", null, infoSocAddr.getHostName(), 
          infoSocAddr.getPort(), "/namenodeMXBean", null, null));
  TypeReference<Map<String, Object>> type = 
      new TypeReference<Map<String, Object>>() { };
  values = mapper.readValue(nameNodeMXBeanContent, type);
}
 
Example #26
Source File: TestJobsResource.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetJobNameNotFound()
    throws IOException {
  Response resp = target(String.format("v1/jobs/%s/%s", "BadJobName", MockJobProxy.JOB_INSTANCE_2_ID)).request().get();
  assertEquals(404, resp.getStatus());

  final Map<String, String> errorMessage = objectMapper.readValue(resp.readEntity(String.class), new TypeReference<Map<String, String>>() { });
  assertTrue(errorMessage.get("message"), errorMessage.get("message").contains("does not exist"));
  resp.close();
}
 
Example #27
Source File: SamzaSqlRelRecordSerdeFactory.java    From samza with Apache License 2.0 5 votes vote down vote up
@Override
public SamzaSqlRelRecord fromBytes(byte[] bytes) {
  try {
    ObjectMapper mapper = new ObjectMapper();
    // Enable object typing to handle nested records
    mapper.enableDefaultTyping();
    return mapper.readValue(new String(bytes, "UTF-8"), new TypeReference<SamzaSqlRelRecord>() { });
  } catch (Exception e) {
    throw new SamzaException(e);
  }
}
 
Example #28
Source File: JsonUtil.java    From samza with Apache License 2.0 5 votes vote down vote up
/**
 * Deserialize a JSON string into an object based on a type reference.
 * This method allows the caller to specify precisely the desired output
 * type for the target object.
 * @param json JSON string
 * @param typeRef type reference of the target object
 * @param <T> type of the target object
 * @return deserialized Java object
 */
public static <T> T fromJson(String json, TypeReference<T> typeRef) {
  Validate.notNull(json, "null JSON string");
  Validate.notNull(typeRef, "null type reference");
  T object;
  try {
    object = MAPPER.readValue(json, typeRef);
  } catch (IOException e) {
    String errorMessage = "Failed to parse json: " + json;
    LOG.error(errorMessage, e);
    throw new SamzaException(errorMessage, e);
  }
  return object;
}
 
Example #29
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
protected List<RepositoryEntryVO> parseRepoArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<RepositoryEntryVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #30
Source File: TestCoordinatorStreamWriter.java    From samza with Apache License 2.0 5 votes vote down vote up
private <T> T deserialize(byte[] bytes, TypeReference<T> reference) {
  try {
    if (bytes != null) {
      String valueStr = new String((byte[]) bytes, "UTF-8");
      return SamzaObjectMapper.getObjectMapper().readValue(valueStr, reference);
    }
  } catch (Exception e) {
    throw new SamzaException(e);
  }

  return null;
}