Java Code Examples for org.codehaus.jackson.map.ObjectMapper#readValue()

The following examples show how to use org.codehaus.jackson.map.ObjectMapper#readValue() . 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: JsonUpdateJvmDeserializerTest.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeserializeJsonUpdateJvm() throws Exception {
    final InputStream in = this.getClass().getResourceAsStream("/json-update-jvm-data.json");
    final String jsonData = IOUtils.toString(in, Charset.defaultCharset());

    final ObjectMapper mapper = new ObjectMapper();

    final JsonUpdateJvm jsonUpdateJvm = mapper.readValue(jsonData, JsonUpdateJvm.class);
    assertEquals("1", jsonUpdateJvm.getJvmId());
    assertEquals("my-jvm", jsonUpdateJvm.getJvmName());
    assertEquals("some-host", jsonUpdateJvm.getHostName());
    assertEquals("jwala", jsonUpdateJvm.getUserName());
    assertEquals("/manager", jsonUpdateJvm.getStatusPath());
    assertEquals("1", jsonUpdateJvm.getJdkMediaId());
    assertTrue(StringUtils.isNotEmpty(jsonUpdateJvm.getEncryptedPassword()));
    assertNotEquals("password", jsonUpdateJvm.getEncryptedPassword());
    assertEquals("8893", jsonUpdateJvm.getAjpPort());
    assertEquals("8889", jsonUpdateJvm.getHttpPort());
    assertEquals("8890", jsonUpdateJvm.getHttpsPort());
    assertEquals("8891", jsonUpdateJvm.getRedirectPort());
    assertEquals("8892", jsonUpdateJvm.getShutdownPort());
    assertEquals("1", jsonUpdateJvm.getGroupIds().get(0).getGroupId());
}
 
Example 2
Source File: PCache.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
  public static void rebuildCache(String cacheCode, String newConfig) {
  	Map<String, String> attrs;
  	try {  
			ObjectMapper objectMapper = new ObjectMapper();
			attrs = objectMapper.readValue(newConfig, Map.class);
} 
  	catch (Exception e) {  
	throw new BusinessException("CACHE_PARAM[" + cacheCode + "] config has error: \n" + newConfig, e);
	    } 
  	
  	CacheStrategy strategy = new CacheStrategy();
BeanUtil.setDataToBean(strategy, attrs);

  	Pool pool = JCache.pools.get(cacheCode);
if(pool != null) { 
	pool.setCacheStrategy(strategy); // 如pool已存在,则只刷新其策略
}
else {
	JCache.pools.put(cacheCode, strategy.getPoolInstance()); // 新建
}
  }
 
Example 3
Source File: AdminTestHelper.java    From helix with Apache License 2.0 6 votes vote down vote up
public static ZNRecord get(Client client, String url) throws IOException {
  Reference resourceRef = new Reference(url);
  Request request = new Request(Method.GET, resourceRef);
  Response response = client.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();
  result.write(sw);

  String responseStr = sw.toString();
  Assert.assertTrue(responseStr.toLowerCase().indexOf("error") == -1);
  Assert.assertTrue(responseStr.toLowerCase().indexOf("exception") == -1);
  ObjectMapper mapper = new ObjectMapper();
  ZNRecord record = mapper.readValue(new StringReader(responseStr), ZNRecord.class);
  return record;
}
 
Example 4
Source File: Importer.java    From socialauth with MIT License 6 votes vote down vote up
/**
 * Generates AccessGrant object from a file generated by
 * {@link GenerateToken}
 * 
 * @param reader
 *            Reader object created with access token file generated by
 *            {@link GenerateToken}
 * @return AccessGrant object
 * @throws Exception
 */
public static AccessGrant importAccessGrant(final Reader reader)
		throws Exception {
	LOG.info("Importing AccessGrant");
	StringBuffer sb = new StringBuffer();
	char[] buf = new char[1024];
	int numRead = 0;
	while ((numRead = reader.read(buf)) != -1) {
		String readData = String.valueOf(buf, 0, numRead);
		sb.append(readData);
		buf = new char[1024];
	}
	reader.close();

	String jsonStr = sb.toString();
	LOG.debug("AccessGrant json :: " + jsonStr);
	ObjectMapper mapper = new ObjectMapper();
	AccessGrant grant = mapper.readValue(jsonStr, AccessGrant.class);
	LOG.debug(grant.toString());
	return grant;
}
 
Example 5
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public TaggerAttribute createNewAttribute(TaggerAttribute attribute)
		throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		WebTarget webResource = client.target(taggerMainUrl + "/attribute");

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper
				.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).post(
				Entity.json(objectMapper.writeValueAsString(attribute
						.toDTO())), Response.class);

		// String jsonResponse = clientResponse.getEntity(String.class);
		String jsonResponse = clientResponse.readEntity(String.class);
		NominalAttributeDTO dto = objectMapper.readValue(jsonResponse,
				NominalAttributeDTO.class);
		TaggerAttribute newAttribute = dto != null ? new TaggerAttribute(
				dto) : null;
		if (newAttribute != null) {
			logger.info("Attribute with ID "
					+ newAttribute.getNominalAttributeID()
					+ " was created in Tagger");
		}
		return newAttribute;
	} catch (Exception e) {
		logger.error("Error while creating new attribute", e);
		throw new AidrException(
				"Error while creating new attribute in Tagger", e);
	}
}
 
Example 6
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<TaggerCrisis> getCrisesByUserId(Integer userId)
		throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		/**
		 * Rest call to Tagger
		 */
		WebTarget webResource = client.target(taggerMainUrl
				+ "/crisis?userID=" + userId);

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper.configure(
				DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
				false);
		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).get();

		String jsonResponse = clientResponse.readEntity(String.class);

		TaggerAllCrisesResponse taggerAllCrisesResponse = objectMapper
				.readValue(jsonResponse, TaggerAllCrisesResponse.class);

		if (taggerAllCrisesResponse.getCrisises() != null) {
			logger.info("Tagger returned "
					+ taggerAllCrisesResponse.getCrisises().size()
					+ " crisis for user");
		}

		return taggerAllCrisesResponse.getCrisises();
	} catch (Exception e) {
		logger.error("Exception while fetching crisis by userId: "+userId, e);
		throw new AidrException(
				"No collection is enabled for Tagger. Please enable tagger for one of your collections.",
				e);
	}
}
 
Example 7
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
protected List<ErrorVO> parseErrorArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<ErrorVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 8
Source File: ResourceHandlerConfigurationTest.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCreateGroupLevelWebAppBinaryResourceHandler() throws IOException {
    final Group mockGroup = mock(Group.class);
    final Set<Jvm> jvms = new HashSet<>();
    jvms.add(mock(Jvm.class));
    when(mockGroup.getJvms()).thenReturn(jvms);
    when(MockConfig.MOCK_GROUP_PERSISTENCE_SERVICE.getGroup(anyString())).thenReturn(mockGroup);
    final List<Application> applications = new ArrayList<>();
    final Application mockApplication = mock(Application.class);
    when(mockApplication.getName()).thenReturn("sampleApp");
    applications.add(mockApplication);
    when(MockConfig.MOCK_APPLICATION_PERSISTENCE_SERVICE.findApplicationsBelongingTo(anyString())).thenReturn(applications);
    final Entity entity = new Entity(null, null, null, null, true);

    final ObjectMapper objectMapper = new ObjectMapper();
    final Map<String, Object> metaDataMap = objectMapper.readValue(metaData.getJsonData(), Map.class);
    metaDataMap.put("entity", entity);
    metaDataMap.put("contentType", "application/zip");
    metaData = resourceService.getMetaData(objectMapper.writeValueAsString(metaDataMap));

    when(MockConfig.MOCK_APPLICATION_PERSISTENCE_SERVICE.getApplication(anyString())).thenReturn(mock(Application.class));
    resourceHandler.createResource(getGroupLevelAppResourceIdentifier(), metaData, "some.war");
    verify(MockConfig.getMockGroupPersistenceService()).populateGroupAppTemplate(anyString(), anyString(), anyString(),
            anyString(), anyString());
    verify(MockConfig.MOCK_APPLICATION_PERSISTENCE_SERVICE).uploadAppTemplate(any(UploadAppTemplateRequest.class), any(JpaJvm.class));
    verify(MockConfig.MOCK_APPLICATION_PERSISTENCE_SERVICE).updateWarInfo(anyString(), anyString(), anyString(), anyString());
}
 
Example 9
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public ModelHistoryWrapper getModelHistoryByModelFamilyID(Integer start,
		Integer limit, Integer id, String sortColumn, String sortDirection) throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		// WebResource webResource = client.resource(taggerMainUrl +
		// "/model/modelFamily/" + id
		// + "?start=" + start
		// + "&limit=" + limit);
		WebTarget webResource = client.target(taggerMainUrl
				+ "/model/modelFamily/" + id + "?start=" + start
				+ "&limit=" + limit+ "&sortColumn=" + sortColumn + "&sortDirection="
				+ sortDirection);

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		// ClientResponse clientResponse =
		// webResource.type(MediaType.APPLICATION_JSON)
		// .accept(MediaType.APPLICATION_JSON)
		// .get(ClientResponse.class);
		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).get();

		// String jsonResponse = clientResponse.getEntity(String.class);
		String jsonResponse = clientResponse.readEntity(String.class);

		ModelHistoryWrapper modelHistoryWrapper = objectMapper.readValue(
				jsonResponse, ModelHistoryWrapper.class);
		return modelHistoryWrapper;
	} catch (Exception e) {
		logger.error("Error while Getting history records for Mode", e);
		throw new AidrException(
				"Error while Getting history records for Model.", e);
	}
}
 
Example 10
Source File: CollectionServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public JSONArray searchFacebookProfiles(String keyword, Integer offset, Integer limit, UserAccount userEntity){
	UserConnection userConnection = userConnectionService.fetchByCombinedUserName(userEntity.getUserName());
	userConnection.getAccessToken();
	try{
		Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();
		WebTarget webResource = client.target(fetchMainUrl + "/" +SocialSignInProvider.FACEBOOK + "/searchProfiles"
				+ "?offset=" + offset + "&limit=" + limit + "&keyword=" + URLEncoder.encode(keyword, "UTF-8"));

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();

		Response clientResponse = webResource.request(
	MediaType.APPLICATION_JSON).post(
	Entity.json(userConnection.getAccessToken()),
	Response.class);
				
		String jsonString = clientResponse.readEntity(String.class);
		JSONParser parser = new JSONParser();
		JSONObject jsonResponse = (JSONObject) parser.parse(jsonString);
		JSONArray response = objectMapper.readValue(jsonResponse.get("entity").toString(), JSONArray.class);
		return response;
	}catch(Exception e){
		logger.error("Exception while searching facebok profiles",e);
	}
	return null;
	
}
 
Example 11
Source File: UserAuthenticationMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
private List<AuthenticationVO> parseAuthenticationArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<AuthenticationVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 12
Source File: ZkUtils.java    From samza with Apache License 2.0 5 votes vote down vote up
/**
 * get the job model from ZK by version
 * @param jobModelVersion jobModel version to get
 * @return job model for this version
 */
public JobModel getJobModel(String jobModelVersion) {
  LOG.info("Read the model ver=" + jobModelVersion + " from " + keyBuilder.getJobModelPath(jobModelVersion));
  Object data = zkClient.readData(keyBuilder.getJobModelPath(jobModelVersion));
  metrics.reads.inc();
  ObjectMapper mmapper = SamzaObjectMapper.getObjectMapper();
  JobModel jm;
  try {
    jm = mmapper.readValue((String) data, JobModel.class);
  } catch (IOException e) {
    throw new SamzaException("failed to read JobModel from ZK", e);
  }
  return jm;
}
 
Example 13
Source File: TaskManagerEntityMapper.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Deprecated
public <E> E deSerializeList(String jsonString, TypeReference<E> type) {
	ObjectMapper mapper = new ObjectMapper();
	mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	try {
		if (jsonString != null) {
			E docList = mapper.readValue(jsonString, type);
			return docList;
		}	
	} catch (Exception e) {
		logger.error("JSON deserialization exception",e);
	}
	return null;
}
 
Example 14
Source File: GroupMgmtITCase.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 15
Source File: CitationHelperAction.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
protected Map<String, Object> dragAndDrop(ParameterParser params, SessionState state) {

		String message = null;
		String errorMessage = null;
		Map<String, Object> results = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		List<CitationCollectionOrder> citationCollectionOrders;

		try {
			String citationCollectionId = params.getString("citationCollectionId");
			String nestedCitations = params.getString("data");
			if (nestedCitations!=null){

				// Java has a bug where it throws a stackoverflow error when pattern matching very long strings
				// http://bugs.java.com/view_bug.do?bug_id=5050507
				// For very big lists, we just split the string
				if (nestedCitations.length()>20000){
					String[] parts = nestedCitations.split("\"sectiontype\"");
					nestedCitations = "";
					for (String part : parts) {
						part = part.replaceAll("\\s+(?=([^\"]*\"[^\"]*\")*[^\"]*$)", "") + "\"sectiontype\"";  // replace whitespace (except between quotation marks) so can strip extra JSON arrays //  (it would be much better just to find a way of parsing the JSON without this string manipulation)
						nestedCitations = nestedCitations + part;
					}
				}
				else {
					nestedCitations = nestedCitations.replaceAll("\\s+(?=([^\"]*\"[^\"]*\")*[^\"]*$)", "");
				}

				nestedCitations = nestedCitations.replaceAll("\'", "&apos;"); // escape single quotes so they can be used in attributes

				// remove extra parentheses in json
				// needed because of the extra ol's for accordion effect
				nestedCitations = nestedCitations
						.replaceAll(",\"children\":\\[\\[\\]\\]", "")
						.replaceAll(",\"children\":\\[\\[\\],\\[\\]\\]", "")
						.replaceAll(",\\{\"children\":\\[\\[\\]\\]\\}", "")
						.replaceAll(",\"children\":\\[\\[\\],", ",\"children\":[")
						.replaceAll(",\"children\":\\[\\[", ",\"children\":[")
						.replaceAll(",\\{\"children\":\\[\\[", ",{\"children\":[")
						.replaceAll("\\{\"children\":\\[\\[", "{\"children\":[")
						.replaceAll("\\}\\],\\[\\{\"section", "},{\"section")
						.replaceAll("\\}\\]\\]", "}]")
						.replaceAll("\\}\\],\\[\\]\\]", "}]")
						.replaceAll("\\}\\],\\[\\{", "},{");

				citationCollectionOrders = mapper.readValue(nestedCitations,
						TypeFactory.collectionType(List.class, CitationCollectionOrder.class));

				CitationCollection collection = getCitationCollection(state, false);
				errorMessage = getCitationValidator().getDragAndDropErrorMessage(citationCollectionOrders, collection);
				if (errorMessage==null){
					getCitationService().save(citationCollectionOrders, citationCollectionId);
					message = rb.getString("resource.updated");
					state.setAttribute(STATE_CITATION_COLLECTION, null);
					log.debug("Reading list with collection id: {} successfully updated. Drag and drop successful", collection.getId());
				}
				else {
					message = errorMessage;
					log.warn("Invalid citation list with collection id: {} in dragAndDrop(). {}", collection.getId(), errorMessage);
				}
			}
		}
		catch (Exception e){
			message = e.getMessage();
			log.warn("Exception in dragandDrop() {}", e);
		}
		if(errorMessage==null && message != null && ! message.trim().equals("")) {
			results.put("message", message);
		}
		else {
			results.put("Error: ", new String[]{errorMessage});
		}
		return results;
	}
 
Example 16
Source File: SystemSetting.java    From seppb with MIT License 4 votes vote down vote up
public static List<JenkinsConfig> settingToJenkinsConfig(SystemSetting systemSetting) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readValue(systemSetting.getSettingValue(), new TypeReference<List<JenkinsConfig>>() {
    });
}
 
Example 17
Source File: ListQueryAPIResponseConvertHelper.java    From Eagle with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "unchecked" })
public static ListQueryAPIResponseEntity convert(Class<? extends TaggedLogAPIEntity> clazz, ListQueryAPIResponseEntity response) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, JsonGenerationException, JsonMappingException, IOException {
	if (response == null || response.getObj() == null) {
		return response;
	}
	final List<TaggedLogAPIEntity> entities = new ArrayList<TaggedLogAPIEntity>();
	final Object obj = response.getObj();
	final Map<String, Method> settings = getOrCreateSetterMap(clazz);
	final Collection<Map<String, Object>> objs = (Collection<Map<String, Object>>) obj;
	for (Map<String, Object> map : objs) {
		final TaggedLogAPIEntity entity = clazz.newInstance();
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			final String propertyName = entry.getKey();
			Object value = entry.getValue();
			final Method method = settings.get(propertyName);
			final Type type = method.getGenericParameterTypes()[0];
			if ((type == double.class || type == Double.class || type == long.class || type == Long.class)
				&& (value.equals("NaN"))) {
				value = 0;
			}					
			
			final Class<?> parameterClass = method.getParameterTypes()[0];
			if (value instanceof Number || value instanceof String || parameterClass.isInstance(value)) {
				try {
					method.invoke(entity, value);
				}
				catch (Exception e){
					e.printStackTrace();
				}
			} else {
				ObjectMapper om = new ObjectMapper();
				String objJson = om.writeValueAsString(value);
				value = om.readValue(objJson, parameterClass);
				method.invoke(entity, value);
			}
		}
		entities.add(entity);
	}
	response.setObj(entities);
	return response;
}
 
Example 18
Source File: JsonHelper.java    From gocd-git-path-material-plugin with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static Map<String, Object> getResponse(GoPluginApiResponse apiResponse) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.readValue(apiResponse.responseBody(), Map.class);
}
 
Example 19
Source File: SonarProperties.java    From seppb with MIT License 4 votes vote down vote up
public static List<SonarConfig> settingToSonarConfig(SystemSetting systemSetting) throws IOException {
	ObjectMapper mapper = new ObjectMapper();
	return mapper.readValue(systemSetting.getSettingValue(), new TypeReference<List<SonarConfig>>() {
	});
}
 
Example 20
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
	public List<ImageTaskQueueDTO> getTaggedImageDataByCrisisId(Integer crisisId, Integer start, Integer limit, String sortColumn,
			String sortDirection)  throws AidrException {
		Client client = ClientBuilder.newBuilder()
				.register(JacksonFeature.class).build();
		logger.info("Received request for fetching training data for crisisID = "
				+ crisisId);
		try {
			WebTarget webResource = client.target(crowdsourcingAPIMainUrl
					+ "/taggedImage/get?crisisID=" + new Long(crisisId)
					+ "&fromRecord=" + start + "&limit=" + limit
					+ "&sortColumn=" + sortColumn + "&sortDirection="
					+ sortDirection);

			ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
			// ClientResponse clientResponse =
			// webResource.type(MediaType.APPLICATION_JSON)
			// .accept(MediaType.APPLICATION_JSON)
			// .get(ClientResponse.class);
			Response clientResponse = webResource.request(
					MediaType.APPLICATION_JSON).get();

			// String jsonResponse = clientResponse.getEntity(String.class);
			String jsonResponse = clientResponse.readEntity(String.class);

			ImageTaskQueueDTO[] taggedImageData = objectMapper.readValue(jsonResponse.toString(), ImageTaskQueueDTO[].class);
/*			TaggedImageDataRequest trainingDataRequest = objectMapper.readValue(
					jsonResponse, TaggedImageDataRequest.class);
			if (trainingDataRequest != null
					&& trainingDataRequest.getTaggedImageData()!= null) {
				logger.info("Tagger returned "
						+ trainingDataRequest.getTaggedImageData().size()
						+ " training data records for crisis with ID: "
						+ crisisId);8/
*/				return Arrays.asList(taggedImageData);
			
		} catch (Exception e) {
			logger.error(crisisId + " Error while Getting training data for Crisis and Model", e);
			throw new AidrException(
					"Error while Getting training data for Crisis and Model.",
					e);
		}
	}