Example usage for com.fasterxml.jackson.databind ObjectMapper convertValue

List of usage examples for com.fasterxml.jackson.databind ObjectMapper convertValue

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper convertValue.

Prototype

@SuppressWarnings("unchecked")
    public <T> T convertValue(Object fromValue, JavaType toValueType) throws IllegalArgumentException 

Source Link

Usage

From source file:org.openmhealth.reference.request.SchemaRequest.java

@Override
public void service() throws OmhException {
    // First, short-circuit if this request has already been serviced.
    if (isServiced()) {
        return;//from w ww  .j  a  va2  s.c  o m
    } else {
        setServiced();
    }

    // Get the schema.
    Schema schema = Registry.getInstance().getSchema(schemaId, schemaVersion);

    // Make sure the schema exists.
    if (schema == null) {
        throw new NoSuchSchemaException(
                "The schema with id '" + schemaId + "' and version '" + schemaVersion + "' does not exist.");
    }

    // Convert the result to a map.
    ObjectMapper mapper = new ObjectMapper();
    // We need to suppress Java's type erasure. :(
    @SuppressWarnings("unchecked")
    Map<String, Object> metaData = mapper.convertValue(schema, Map.class);

    // Remove the schema from the meta-data.
    metaData.remove(Schema.JSON_KEY_SCHEMA);

    // Save the meta-data.
    setMetaData(metaData);

    // Set the schema itself as the data.
    setData(schema.getSchema());
}

From source file:org.mule.modules.cookbook.CookbookConnector.java

/**
 * Description for get/*w  ww.java 2 s.co m*/
 *
 * {@sample.xml ../../../doc/cook-book-connector.xml.sample cook-book:get}
 *
 * @param id
 *            Id of the entity to retrieve
 * @return return Ingredient with Id from the system.
 *
 * @throws SessionExpiredException
 * @throws InvalidEntityException
 * @throws NoSuchEntityException
 */
@SuppressWarnings("unchecked")
@OAuthProtected
@Processor
@OnException(handler = CookbookHandler.class)
@ReconnectOn(exceptions = { SessionExpiredException.class })
public Map<String, Object> get(@MetaDataKeyParam(affects = MetaDataKeyParamAffectsType.OUTPUT) String type,
        @Default("1") Integer id)
        throws InvalidEntityException, SessionExpiredException, NoSuchEntityException {
    ObjectMapper m = new ObjectMapper();
    return m.convertValue(this.getConfig().getClient().get(id), Map.class);
}

From source file:com.almende.eve.rpc.jsonrpc.JSONResponse.java

/**
 * Sets the result./*from  w  w  w .j ava2s. c  om*/
 *
 * @param result the new result
 */
public void setResult(final Object result) {
    if (result != null) {
        final ObjectMapper mapper = JOM.getInstance();
        resp.put(RESULT, mapper.convertValue(result, JsonNode.class));
        setError(null);
    } else {
        if (resp.has(RESULT)) {
            resp.remove(RESULT);
        }
    }
}

From source file:com.twosigma.beakerx.kernel.MagicKernelManager.java

private Message parseMessage(String stringJson) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode json = mapper.readTree(stringJson);
    Message msg = new Message(mapper.convertValue(json.get("header"), Header.class));
    msg.setContent(mapper.convertValue(json.get("content"), Map.class));
    msg.setMetadata(mapper.convertValue(json.get("metadata"), Map.class));
    msg.setBuffers(mapper.convertValue(json.get("buffers"), List.class));
    List<byte[]> identities = mapper.convertValue(json.get("comm_id"), List.class);
    msg.setIdentities(identities == null ? new ArrayList<>() : identities);
    return msg;/*  ww w  . ja v a2 s  .c om*/
}

From source file:org.apache.streams.rss.serializer.SyndEntryActivitySerializer.java

/**
 * Given an RSS object and an existing activity,
 * add the Rome extension to that activity and return it
 *
 * @param activity/*from   www.  j av  a  2  s  .co m*/
 * @param entry
 * @return
 */
private Activity addRomeExtension(Activity activity, ObjectNode entry) {
    ObjectMapper mapper = StreamsJacksonMapper.getInstance();
    ObjectNode activityRoot = mapper.convertValue(activity, ObjectNode.class);
    ObjectNode extensions = JsonNodeFactory.instance.objectNode();

    extensions.put("rome", entry);
    activityRoot.put("extensions", extensions);

    activity = mapper.convertValue(activityRoot, Activity.class);

    return activity;
}

From source file:eu.trentorise.smartcampus.mobility.processor.handlers.BikeSharingCache.java

private void getExistingStations() throws Exception {
    existingStations = Sets.newHashSet();
    ObjectMapper mapper = new ObjectMapper();
    String bs = smartPlannerHelper.bikeStations();
    List bsl = mapper.readValue(bs, List.class);
    for (Object o : bsl) {
        Map<String, Object> station = mapper.convertValue(o, Map.class);
        String idParts[] = ((String) station.get("id")).split("@");
        existingStations.add(idParts[0]);
    }//from w  ww  . ja  va  2 s  .  com
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Utility function to create a mapping out of all the different system components (see also ElasticsearchUtils)
 * @param bucket//from  w  w  w . j a v a  2s .  com
 * @param config
 * @return
 */
public static XContentBuilder createIndexMapping(final DataBucketBean bucket,
        final Optional<String> secondary_buffer, final boolean is_primary,
        final ElasticsearchIndexServiceConfigBean schema_config, final ObjectMapper mapper,
        final String index_type) {
    final JsonNode default_mapping = mapper.convertValue(schema_config.search_technology_override(),
            JsonNode.class);

    // Also get JsonNodes for the default field config bit

    final boolean columnar_enabled = Optional.ofNullable(bucket.data_schema())
            .map(DataSchemaBean::columnar_schema).filter(s -> Optional.ofNullable(s.enabled()).orElse(true))
            .isPresent();

    final boolean doc_enabled = Optional.ofNullable(bucket.data_schema()).map(DataSchemaBean::document_schema)
            .filter(s -> Optional.ofNullable(s.enabled()).orElse(true)).isPresent();

    // (these can't be null by construction)
    final JsonNode enabled_analyzed_field = columnar_enabled
            ? mapper.convertValue(schema_config.columnar_technology_override().enabled_field_data_analyzed(),
                    JsonNode.class)
            : mapper.createObjectNode();
    final JsonNode enabled_not_analyzed_field = columnar_enabled
            ? mapper.convertValue(schema_config.columnar_technology_override().enabled_field_data_notanalyzed(),
                    JsonNode.class)
            : mapper.createObjectNode();
    final JsonNode default_analyzed_field = columnar_enabled
            ? mapper.convertValue(schema_config.columnar_technology_override().default_field_data_analyzed(),
                    JsonNode.class)
            : mapper.createObjectNode();
    final JsonNode default_not_analyzed_field = columnar_enabled
            ? mapper.convertValue(schema_config.columnar_technology_override().default_field_data_notanalyzed(),
                    JsonNode.class)
            : mapper.createObjectNode();
    final Optional<JsonNode> doc_schema = doc_enabled
            ? Optional.ofNullable(mapper.convertValue(schema_config.document_schema_override(), JsonNode.class))
            : Optional.empty();

    // Get a list of field overrides Either<String,Tuple2<String,String>> for dynamic/real fields

    final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> field_lookups = ElasticsearchIndexUtils
            .parseDefaultMapping(default_mapping,
                    (CollidePolicy.new_type == Optional
                            .ofNullable(schema_config.search_technology_override().collide_policy())
                            .orElse(CollidePolicy.new_type))
                                    ? Optional.empty()
                                    : Optional.ofNullable(
                                            schema_config.search_technology_override().type_name_or_prefix()),
                    Optionals.of(() -> bucket.data_schema().search_index_schema()),
                    Optionals.of(() -> bucket.data_schema().document_schema()),
                    schema_config.search_technology_override(), mapper);

    // If a time field is present then adding the default mapping for it (overwrite @timestamp if that's the specified field):

    final Optional<JsonNode> time_mapping = Optional.ofNullable(schema_config.temporal_technology_override())
            .map(DataSchemaBean.TemporalSchemaBean::technology_override_schema)
            .map(t -> (Object) t.get("default_timefield_mapping"))
            .map(js -> mapper.convertValue(js, JsonNode.class));
    time_mapping.ifPresent(json -> {
        Optional.ofNullable(bucket.data_schema()).map(DataSchemaBean::temporal_schema)
                .filter(s -> Optional.ofNullable(s.enabled()).orElse(true)).map(t -> t.time_field())
                .ifPresent(time_field -> {
                    field_lookups.put(Either.left(time_field), json); //(MUTABLE CODE WARNING)
                });
    });

    final XContentBuilder test_result = getFullMapping(bucket, secondary_buffer, is_primary, schema_config,
            field_lookups, enabled_not_analyzed_field, enabled_analyzed_field, default_not_analyzed_field,
            default_analyzed_field, doc_schema, schema_config.search_technology_override(), mapper, index_type);

    return test_result;
}

From source file:com.almende.eve.protocol.jsonrpc.formats.JSONResponse.java

/**
 * Sets the result.//from  w w w  .j a  v  a  2  s  . c  o  m
 * 
 * @param result
 *            the new result
 */
public void setResult(final Object result) {
    if (result != null) {
        final ObjectMapper mapper = JOM.getInstance();
        resp.set(RESULT, (JsonNode) mapper.convertValue(result, JSONNODETYPE));
        setError(null);
    } else {
        if (resp.has(RESULT)) {
            resp.remove(RESULT);
        }
    }
}

From source file:net.mostlyharmless.jghservice.connector.jira.SearchIssues.java

@Override
public List<JiraEvent.Issue> processResponse(String jsonResponse) throws IOException {
    ObjectMapper m = new ObjectMapperProvider().getContext(JiraEvent.Issue.class);
    ObjectNode root = (ObjectNode) m.readTree(jsonResponse);
    JavaType t = m.getTypeFactory().constructCollectionType(List.class, JiraEvent.Issue.class);
    return m.convertValue(root.get("issues"), t);
}

From source file:com.hpe.caf.worker.testing.validation.ReferenceDataValidator.java

@Override
public boolean isValid(Object testedPropertyValue, Object validatorPropertyValue) {

    if (testedPropertyValue == null && validatorPropertyValue == null)
        return true;

    ObjectMapper mapper = new ObjectMapper();

    ContentFileTestExpectation expectation = mapper.convertValue(validatorPropertyValue,
            ContentFileTestExpectation.class);

    ReferencedData referencedData = mapper.convertValue(testedPropertyValue, ReferencedData.class);

    InputStream dataStream;/* w w w  . ja  va 2  s  . co  m*/

    if (expectation.getExpectedContentFile() == null && expectation.getExpectedSimilarityPercentage() == 0) {
        return true;
    }

    try {
        System.out.println("About to retrieve content for " + referencedData.toString());
        dataStream = ContentDataHelper.retrieveReferencedData(dataStore, codec, referencedData);
        System.out.println("Finished retrieving content for " + referencedData.toString());
    } catch (DataSourceException e) {
        e.printStackTrace();
        System.err.println("Failed to acquire referenced data.");
        e.printStackTrace();
        TestResultHelper.testFailed("Failed to acquire referenced data. Exception message: " + e.getMessage(),
                e);
        return false;
    }
    try {
        String contentFileName = expectation.getExpectedContentFile();
        Path contentFile = Paths.get(contentFileName);
        if (Files.notExists(contentFile) && !Strings.isNullOrEmpty(testSourcefileBaseFolder)) {
            contentFile = Paths.get(testSourcefileBaseFolder, contentFileName);
        }

        if (Files.notExists(contentFile)) {
            contentFile = Paths.get(testDataFolder, contentFileName);
        }

        byte[] expectedFileBytes = Files.readAllBytes(contentFile);

        if (expectation.getComparisonType() == ContentComparisonType.TEXT) {

            String actualText = IOUtils.toString(dataStream, StandardCharsets.UTF_8);
            String expectedText = new String(expectedFileBytes, StandardCharsets.UTF_8);

            if (expectation.getExpectedSimilarityPercentage() == 100) {
                boolean equals = actualText.equals(expectedText);
                if (!equals) {
                    String message = "Expected and actual texts were different.\n\n*** Expected Text ***\n"
                            + expectedText + "\n\n*** Actual Text ***\n" + actualText;
                    System.err.println(message);
                    if (throwOnValidationFailure)
                        TestResultHelper.testFailed(message);
                    return false;
                }
                return true;
            }

            double similarity = ContentComparer.calculateSimilarityPercentage(expectedText, actualText);

            System.out.println("Compared text similarity:" + similarity + "%");

            if (similarity < expectation.getExpectedSimilarityPercentage()) {
                String message = "Expected similarity of " + expectation.getExpectedSimilarityPercentage()
                        + "% but actual similarity was " + similarity + "%";
                System.err.println(message);
                if (throwOnValidationFailure)
                    TestResultHelper.testFailed(message);
                return false;
            }
        } else {
            byte[] actualDataBytes = IOUtils.toByteArray(dataStream);
            boolean equals = Arrays.equals(actualDataBytes, expectedFileBytes);
            if (!equals) {
                String actualContentFileName = contentFile.getFileName() + "_actual";
                Path actualFilePath = Paths.get(contentFile.getParent().toString(), actualContentFileName);
                Files.deleteIfExists(actualFilePath);
                Files.write(actualFilePath, actualDataBytes, StandardOpenOption.CREATE);
                String message = "Data returned was different than expected for file: " + contentFileName
                        + "\nActual content saved in file: " + actualFilePath.toString();
                System.err.println(message);
                if (throwOnValidationFailure)
                    TestResultHelper.testFailed(message);
                return false;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        TestResultHelper.testFailed("Error while processing reference data! " + e.getMessage(), e);
        return false;
    }
    return true;
}