List of usage examples for com.fasterxml.jackson.databind ObjectMapper convertValue
@SuppressWarnings("unchecked") public <T> T convertValue(Object fromValue, JavaType toValueType) throws IllegalArgumentException
From source file:org.openmhealth.reference.request.DataWriteRequest.java
/** * Validates the data and, if valid, stores it. *//*from w w w .j a v a 2 s . c om*/ @Override public void service() throws OmhException { // First, short-circuit if this request has already been serviced. if (isServiced()) { return; } else { setServiced(); } // Check to be sure the schema is known. MultiValueResult<? extends Schema> schemas = Registry.getInstance().getSchemas(schemaId, version, 0, 1); if (schemas.count() == 0) { throw new OmhException( "The schema ID, '" + schemaId + "', and version, '" + version + "', pair is unknown."); } Schema schema = schemas.iterator().next(); // Get the user that owns this token. User requestingUser = authToken.getUser(); // Parse the data. JsonNode dataNode; try { dataNode = JSON_FACTORY.createJsonParser(data).readValueAs(JsonNode.class); } catch (JsonParseException e) { throw new OmhException("The data was not well-formed JSON.", e); } catch (JsonProcessingException e) { throw new OmhException("The data was not well-formed JSON.", e); } catch (IOException e) { throw new OmhException("The data could not be read.", e); } // Make sure it is a JSON array. if (!(dataNode instanceof ArrayNode)) { throw new OmhException("The data was not a JSON array."); } ArrayNode dataArray = (ArrayNode) dataNode; // Get the number of data points. int numDataPoints = dataArray.size(); // Create the result list of data points. List<Data> dataPoints = new ArrayList<Data>(numDataPoints); // Create a new ObjectMapper that will be used to convert the meta-data // node into a MetaData object. ObjectMapper mapper = new ObjectMapper(); // For each element in the array, be sure it is a JSON object that // represents a valid data point for this schema. for (int i = 0; i < numDataPoints; i++) { // Get the current data point. JsonNode dataPoint = dataArray.get(i); // Validate that it is a JSON object. if (!(dataPoint instanceof ObjectNode)) { throw new OmhException("A data point was not a JSON object: " + i); } ObjectNode dataObject = (ObjectNode) dataPoint; // Attempt to get the meta-data; MetaData metaData = null; JsonNode metaDataNode = dataObject.get(Data.JSON_KEY_METADATA); if (metaDataNode != null) { metaData = mapper.convertValue(metaDataNode, MetaData.class); } // Attempt to get the schema data. JsonNode schemaData = dataObject.get(Data.JSON_KEY_DATA); // If the data is missing, fail the request. if (schemaData == null) { throw new OmhException("A data point's '" + Data.JSON_KEY_DATA + "' field is missing."); } // Create and add the point to the set of data. dataPoints.add(schema.validateData(requestingUser.getUsername(), metaData, schemaData)); } // Store the data. DataSet.getInstance().storeData(dataPoints); }
From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java
private boolean verify(Message message, MsgCheck check) { String sVal = ""; if (check.getField().equals(MESSAGECONTENTFIELD)) { try {//from w ww .j a va 2s.co m if (message instanceof TextMessage) { sVal = ((TextMessage) message).getText(); } else if (message instanceof MapMessage) { MapMessage mm = (MapMessage) message; ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.createObjectNode(); @SuppressWarnings("unchecked") Enumeration<String> e = mm.getMapNames(); while (e.hasMoreElements()) { String field = e.nextElement(); root.set(field, mapper.convertValue(mm.getObject(field), JsonNode.class)); } sVal = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root); } else if (message instanceof BytesMessage) { BytesMessage bm = (BytesMessage) message; bm.reset(); byte[] bytes = new byte[(int) bm.getBodyLength()]; if (bm.readBytes(bytes) == bm.getBodyLength()) { sVal = new String(bytes); } } } catch (JMSException e) { return false; } catch (JsonProcessingException e) { return false; } } else { Enumeration<String> propNames = null; try { propNames = message.getPropertyNames(); while (propNames.hasMoreElements()) { String propertyName = propNames.nextElement(); if (propertyName.equals(check.getField())) { if (message.getObjectProperty(propertyName) != null) { sVal = message.getObjectProperty(propertyName).toString(); break; } } } } catch (JMSException e) { return false; } } String eVal = ""; if (check.getExpectedValue() != null) { eVal = check.getExpectedValue(); } if (Pattern.compile(eVal).matcher(sVal).find()) { return true; } return false; }
From source file:com.thinkbiganalytics.integration.IntegrationTestBase.java
protected FeedSummary[] getFeeds() { final ObjectMapper mapper = new ObjectMapper(); SearchResult searchResult = getFeedsExpectingStatus(HTTP_OK).as(SearchResultImpl.class); return searchResult.getData().stream().map(o -> mapper.convertValue(o, FeedSummary.class)) .toArray(FeedSummary[]::new); }
From source file:it.sayservice.platform.smartplanner.otp.OTPHandler.java
public List<AnnotatedTrip> buildAnnotatedTrips(String router, String agencyId) throws Exception { String fileName = System.getenv("OTP_HOME") + System.getProperty("file.separator") + router + System.getProperty("file.separator") + "cache" + System.getProperty("file.separator") + "client" + System.getProperty("file.separator") + Constants.AUXILIARY_CACHE_DIR + System.getProperty("file.separator") + agencyId + "_" + Constants.ANNOTATED_TRIPS + ".txt"; File f = new File(fileName); List<AnnotatedTrip> annotatedTrips = Lists.newArrayList(); if (f.exists()) { ObjectMapper mapper = new ObjectMapper(); List maps = mapper.readValue(f, List.class); for (Object o : maps) { AnnotatedTrip at = mapper.convertValue(o, AnnotatedTrip.class); annotatedTrips.add(at);//w ww . ja v a2s . c om } return annotatedTrips; } else { return new ArrayList<AnnotatedTrip>(); } }
From source file:org.wso2.carbon.bpmn.rest.service.base.BaseExecutionService.java
protected Response createExecutionVariable(Execution execution, boolean override, int variableType, HttpServletRequest httpServletRequest, UriInfo uriInfo) { Object result = null;//from w w w . jav a 2s . c om Response.ResponseBuilder responseBuilder = Response.ok(); List<RestVariable> inputVariables = new ArrayList<>(); List<RestVariable> resultVariables = new ArrayList<>(); if (Utils.isApplicationJsonRequest(httpServletRequest)) { try { ObjectMapper objectMapper = new ObjectMapper(); @SuppressWarnings("unchecked") List<Object> variableObjects = (List<Object>) objectMapper .readValue(httpServletRequest.getInputStream(), List.class); for (Object restObject : variableObjects) { RestVariable restVariable = objectMapper.convertValue(restObject, RestVariable.class); inputVariables.add(restVariable); } } catch (Exception e) { throw new ActivitiIllegalArgumentException("Failed to serialize to a RestVariable instance", e); } } else if (Utils.isApplicationXmlRequest(httpServletRequest)) { JAXBContext jaxbContext = null; try { jaxbContext = JAXBContext.newInstance(RestVariableCollection.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); RestVariableCollection restVariableCollection = (RestVariableCollection) jaxbUnmarshaller .unmarshal(httpServletRequest.getInputStream()); if (restVariableCollection == null) { throw new ActivitiIllegalArgumentException("xml request body could not be transformed to a " + "RestVariable Collection instance."); } List<RestVariable> restVariableList = restVariableCollection.getRestVariables(); if (restVariableList.size() == 0) { throw new ActivitiIllegalArgumentException( "xml request body could not identify any rest " + "variables to be updated"); } for (RestVariable restVariable : restVariableList) { inputVariables.add(restVariable); } } catch (JAXBException | IOException e) { throw new ActivitiIllegalArgumentException( "xml request body could not be transformed to a " + "RestVariable instance.", e); } } if (inputVariables.size() == 0) { throw new ActivitiIllegalArgumentException("Request didn't contain a list of variables to create."); } RestVariable.RestVariableScope sharedScope = null; RestVariable.RestVariableScope varScope = null; Map<String, Object> variablesToSet = new HashMap<String, Object>(); for (RestVariable var : inputVariables) { // Validate if scopes match varScope = var.getVariableScope(); if (var.getName() == null) { throw new ActivitiIllegalArgumentException("Variable name is required"); } if (varScope == null) { varScope = RestVariable.RestVariableScope.LOCAL; } if (sharedScope == null) { sharedScope = varScope; } if (varScope != sharedScope) { throw new ActivitiIllegalArgumentException( "Only allowed to update multiple variables in the same scope."); } if (!override && hasVariableOnScope(execution, var.getName(), varScope)) { throw new BPMNConflictException("Variable '" + var.getName() + "' is already present on execution '" + execution.getId() + "'."); } Object actualVariableValue = new RestResponseFactory().getVariableValue(var); variablesToSet.put(var.getName(), actualVariableValue); resultVariables.add(new RestResponseFactory().createRestVariable(var.getName(), actualVariableValue, varScope, execution.getId(), variableType, false, uriInfo.getBaseUri().toString())); } if (!variablesToSet.isEmpty()) { RuntimeService runtimeService = BPMNOSGIService.getRuntimeService(); if (sharedScope == RestVariable.RestVariableScope.LOCAL) { runtimeService.setVariablesLocal(execution.getId(), variablesToSet); } else { if (execution.getParentId() != null) { // Explicitly set on parent, setting non-local variables on execution itself will override local-variables if exists runtimeService.setVariables(execution.getParentId(), variablesToSet); } else { // Standalone task, no global variables possible throw new ActivitiIllegalArgumentException("Cannot set global variables on execution '" + execution.getId() + "', task is not part of process."); } } } RestVariableCollection restVariableCollection = new RestVariableCollection(); restVariableCollection.setRestVariables(resultVariables); responseBuilder.entity(restVariableCollection); return responseBuilder.status(Response.Status.CREATED).build(); }
From source file:org.apache.streams.data.MoreoverJsonActivitySerializer.java
@Override public Activity deserialize(String serialized) { serialized = serialized.replaceAll("\\[[ ]*\\]", "null"); System.out.println(serialized); ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory()); mapper.setAnnotationIntrospector(introspector); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE); mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, Boolean.FALSE); mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE); mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE); mapper.configure(DeserializationFeature.WRAP_EXCEPTIONS, Boolean.TRUE); Article article;/* ww w .j a v a 2 s .co m*/ try { ObjectNode node = (ObjectNode) mapper.readTree(serialized); node.remove("tags"); node.remove("locations"); node.remove("companies"); node.remove("topics"); node.remove("media"); node.remove("outboundUrls"); ObjectNode jsonNodes = (ObjectNode) node.get("source").get("feed"); jsonNodes.remove("editorialTopics"); jsonNodes.remove("tags"); jsonNodes.remove("autoTopics"); article = mapper.convertValue(node, Article.class); } catch (IOException e) { throw new IllegalArgumentException("Unable to deserialize", e); } return MoreoverUtils.convert(article); }
From source file:org.apache.streams.moreover.MoreoverJsonActivitySerializer.java
@Override public Activity deserialize(String serialized) { serialized = serialized.replaceAll("\\[[ ]*\\]", "null"); LOGGER.debug(serialized);// w w w . j a v a 2 s . com ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory()); mapper.setAnnotationIntrospector(introspector); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE); mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, Boolean.FALSE); mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE); mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE); mapper.configure(DeserializationFeature.WRAP_EXCEPTIONS, Boolean.TRUE); Article article; try { ObjectNode node = (ObjectNode) mapper.readTree(serialized); node.remove("tags"); node.remove("locations"); node.remove("companies"); node.remove("topics"); node.remove("media"); node.remove("outboundUrls"); ObjectNode jsonNodes = (ObjectNode) node.get("source").get("feed"); jsonNodes.remove("editorialTopics"); jsonNodes.remove("tags"); jsonNodes.remove("autoTopics"); article = mapper.convertValue(node, Article.class); } catch (IOException ex) { throw new IllegalArgumentException("Unable to deserialize", ex); } return MoreoverUtils.convert(article); }
From source file:jp.aegif.nemaki.dao.impl.couch.ContentDaoServiceImpl.java
private Content convertJsonToEachBaeType(ViewResult result) { if (result.getRows().isEmpty()) { return null; } else {//from ww w . j a v a 2s . co m Iterator<Row> iterator = result.getRows().iterator(); while (iterator.hasNext()) { ObjectMapper mapper = new ObjectMapper(); JsonNode jn = iterator.next().getValueAsNode(); String baseType = jn.path("type").textValue(); if (BaseTypeId.CMIS_DOCUMENT.value().equals(baseType)) { CouchDocument cd = mapper.convertValue(jn, CouchDocument.class); return cd.convert(); } else if (BaseTypeId.CMIS_FOLDER.value().equals(baseType)) { CouchFolder cf = mapper.convertValue(jn, CouchFolder.class); return cf.convert(); } else if (BaseTypeId.CMIS_POLICY.value().equals(baseType)) { CouchPolicy cp = mapper.convertValue(jn, CouchPolicy.class); return cp.convert(); } else if (BaseTypeId.CMIS_RELATIONSHIP.value().equals(baseType)) { CouchRelationship cr = mapper.convertValue(jn, CouchRelationship.class); return cr.convert(); } else if (BaseTypeId.CMIS_ITEM.value().equals(baseType)) { CouchItem ci = mapper.convertValue(jn, CouchItem.class); return ci.convert(); } } } return null; }
From source file:it.sayservice.platform.smartplanner.otp.OTPHandler.java
public Multimap<String, StopTime> getTimesByRoutes(String router, String agencyId, String stopId, long from, long to) throws Exception { Multimap<String, StopTime> result = ArrayListMultimap.create(); Long timeInterval = Math.abs(to - from) / 1000; // otp expect seconds // since midnight. try {//from www . jav a2 s . co m String stopIdOTP = agencyId + ":" + stopId; String res = HTTPConnector.doGet(otpURL + Constants.OP_STOPS + "/" + stopIdOTP + Constants.OP_STOPTIMES, "startTime=" + from / 1000 + "&timeRange=" + timeInterval + "&numberOfDepartures=100", null, MediaType.APPLICATION_JSON); com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper(); JsonNode root = mapper.readTree(res); List<String> used = new ArrayList<String>(); ArrayNode rootList = mapper.convertValue(root, ArrayNode.class); for (JsonNode pattern : rootList) { ArrayNode times = mapper.convertValue(pattern.get("times"), ArrayNode.class); for (JsonNode timeNode : times) { String[] ids = timeNode.get("tripId").asText().split(":"); // long time = SmartPlannerUtils.addSecondsToTimeStamp(from, timeNode.get("scheduledDeparture").asInt()); long time = SmartPlannerUtils.computeDate(timeNode.get("scheduledDeparture").asInt(), timeNode.get("serviceDay").asLong() * 1000); Id id = new Id(); id.setAgency(agencyId); id.setId(ids[1]); String u = time + "_" + id.getId() + id.getAgency(); if (used.contains(u)) { continue; } String tripId = id.getId(); String tripRouteId = routerTripsMap.get(router).get(agencyId + "_" + tripId); if (tripRouteId != null) { StopTime stopTime = new StopTime(); stopTime.setTime(time); stopTime.setTrip(id); result.put(tripRouteId, stopTime); used.add(u); } else { System.err.println("ERROR: missing tripId " + agencyId + "_" + tripId); } } } } catch (Exception e) { e.printStackTrace(); } return result; }