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

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

Introduction

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

Prototype

public ObjectMapper configure(JsonGenerator.Feature f, boolean state) 

Source Link

Document

Method for changing state of an on/off JsonGenerator feature for JsonFactory instance this object mapper uses.

Usage

From source file:org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService.java

private static OvsdbClient getChannelClient(Channel channel, ConnectionType type,
        ExecutorService executorService) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.setSerializationInclusion(Include.NON_NULL);

    JsonRpcEndpoint factory = new JsonRpcEndpoint(objectMapper, channel);
    JsonRpcServiceBinderHandler binderHandler = new JsonRpcServiceBinderHandler(factory);
    binderHandler.setContext(channel);/*from  ww w.java  2  s  .co  m*/
    channel.pipeline().addLast(binderHandler);

    OvsdbRPC rpc = factory.getClient(channel, OvsdbRPC.class);
    OvsdbClientImpl client = new OvsdbClientImpl(rpc, channel, type, executorService);
    connections.put(client, channel);
    ChannelFuture closeFuture = channel.closeFuture();
    closeFuture.addListener(new ChannelConnectionHandler(client));
    return client;
}

From source file:com.currencyfair.onesignal.OneSignal.java

private static OneSignalComms oneSignal() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    objectMapper.setSerializationInclusion(Include.NON_EMPTY);
    JacksonDecoder decoder = new JacksonDecoder(objectMapper);
    return Feign.builder().encoder(new JacksonEncoder(objectMapper)).decoder(decoder).decode404()
            .errorDecoder(new OneSignalErrorDecoder(decoder)).logger(new Slf4jLogger()).logLevel(Level.FULL)
            .target(OneSignalComms.class, "https://onesignal.com/api/v1");
}

From source file:com.unboundid.scim2.common.utils.MapperFactory.java

/**
 * Creates a custom SCIM compatible Jackson ObjectMapper. Creating new
 * ObjectMapper instances are expensive so instances should be shared if
 * possible. This can be used to set the factory used to build new instances
 * of the object mapper used by the SCIM 2 SDK.
 *
 * @return an Object Mapper with the correct options set for serializing
 *     and deserializing SCIM JSON objects.
 */// w  w  w .  java 2 s  . com
public static ObjectMapper createObjectMapper() {
    ObjectMapper mapper = new ObjectMapper(new ScimJsonFactory());

    // Don't serialize POJO nulls as JSON nulls.
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);

    // Only use ISO8601 format for dates.
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.setDateFormat(new ScimDateFormat());

    // Do not care about case when de-serializing POJOs.
    mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

    // Use the case-insensitive JsonNodes.
    mapper.setNodeFactory(new ScimJsonNodeFactory());

    for (DeserializationFeature feature : deserializationCustomFeatures.keySet()) {
        mapper.configure(feature, deserializationCustomFeatures.get(feature));
    }

    for (JsonGenerator.Feature feature : jsonGeneratorCustomFeatures.keySet()) {
        mapper.configure(feature, jsonGeneratorCustomFeatures.get(feature));
    }

    for (JsonParser.Feature feature : jsonParserCustomFeatures.keySet()) {
        mapper.configure(feature, jsonParserCustomFeatures.get(feature));
    }

    for (MapperFeature feature : mapperCustomFeatures.keySet()) {
        mapper.configure(feature, mapperCustomFeatures.get(feature));
    }

    for (SerializationFeature feature : serializationCustomFeatures.keySet()) {
        mapper.configure(feature, serializationCustomFeatures.get(feature));
    }

    return mapper;
}

From source file:de.javagl.jgltf.model.io.JacksonUtils.java

/**
 * Perform a default configuration of the given object mapper for
 * parsing glTF data/*w  w w  .j  a  v a 2s  .c om*/
 * 
 * @param objectMapper The object mapper
 * @param jsonErrorConsumer The consumer for {@link JsonError}s. If this 
 * is <code>null</code>, then the errors will not be handled.
 * <code>null</code>, then log outputs will be created for the errors
 */
static void configure(ObjectMapper objectMapper, Consumer<? super JsonError> jsonErrorConsumer) {
    // Some glTF files have single values instead of arrays,
    // so accept this for compatibility reasons
    objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    objectMapper.addHandler(createDeserializationProblemHandler(jsonErrorConsumer));

    // Register the module that will initialize the setup context
    // with the error handling bean deserializer modifier
    objectMapper.registerModule(new SimpleModule() {
        /**
         * Serial UID
         */
        private static final long serialVersionUID = 1L;

        @Override
        public void setupModule(SetupContext context) {
            super.setupModule(context);
            context.addBeanDeserializerModifier(createErrorHandlingBeanDeserializerModifier(jsonErrorConsumer));
        }
    });

}

From source file:com.monarchapis.client.resource.AbstractResource.java

private static ObjectMapper getObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();

    mapper.registerModule(new JodaModule());
    mapper.registerModule(new GuavaModule());

    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return mapper;
}

From source file:com.dell.asm.asmcore.asmmanager.util.deployment.HostnameUtilTest.java

static Deployment loadEsxiDeployment() throws IOException {
    // Set up some mock component data
    // Get some deployment data
    URL uri = HostnameUtilTest.class.getClassLoader().getResource("esxi_deployment.json");
    assertNotNull("Failed to load esxi_deployment.json", uri);
    String json = IOUtils.toString(uri, Charsets.UTF_8);

    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector ai = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    mapper.setAnnotationIntrospector(ai);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper.readValue(json, Deployment.class);
}

From source file:org.sead.repositories.reference.util.SEADGoogleLogin.java

private static void initGProps() {
    ObjectMapper mapper = new ObjectMapper();
    // Read Google Oauth2 info
    try {/*  ww  w .  j a v a 2s .c  om*/
        gProps = mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true)
                .readValue(new File("sead-google.json"), GoogleProps.class);
    } catch (Exception e) {
        log.error("Error reading sead-google.json file: " + e.getMessage());
    }

}

From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java

/**
 * Uploads the specified file to the community site. The return identifier
 * can be used later when composing other requests.
 * //  ww  w .j a v a2  s .  c  om
 * @param httpclient
 *            the http client
 * @param attachment
 *            the file to attach
 * @param authCookie
 *            the session cookie to use for authentication purpose
 * @return the identifier of the file uploaded, <code>null</code> otherwise
 * @throws CommunityAPIException
 */
public static String uploadFile(CloseableHttpClient httpclient, File attachment, Cookie authCookie)
        throws CommunityAPIException {
    FileInputStream fin = null;
    try {
        fin = new FileInputStream(attachment);
        byte fileContent[] = new byte[(int) attachment.length()];
        fin.read(fileContent);

        byte[] encodedFileContent = Base64.encodeBase64(fileContent);
        FileUploadRequest uploadReq = new FileUploadRequest(attachment.getName(), encodedFileContent);

        HttpPost fileuploadPOST = new HttpPost(CommunityConstants.FILE_UPLOAD_URL);
        EntityBuilder fileUploadEntity = EntityBuilder.create();
        fileUploadEntity.setText(uploadReq.getAsJSON());
        fileUploadEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE));
        fileUploadEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET);
        fileuploadPOST.setEntity(fileUploadEntity.build());

        CloseableHttpResponse resp = httpclient.execute(fileuploadPOST);
        int httpRetCode = resp.getStatusLine().getStatusCode();
        String responseBodyAsString = EntityUtils.toString(resp.getEntity());

        if (HttpStatus.SC_OK == httpRetCode) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            JsonNode jsonRoot = mapper.readTree(responseBodyAsString);
            String fid = jsonRoot.get("fid").asText(); //$NON-NLS-1$
            return fid;
        } else {
            CommunityAPIException ex = new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError);
            ex.setHttpStatusCode(httpRetCode);
            ex.setResponseBodyAsString(responseBodyAsString);
            throw ex;
        }

    } catch (FileNotFoundException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_FileNotFoundError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e);
    } catch (UnsupportedEncodingException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e);
    } catch (IOException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e);
    } finally {
        IOUtils.closeQuietly(fin);
    }
}

From source file:com.netflix.conductor.contribs.http.HttpTask.java

private static ObjectMapper objectMapper() {
    final ObjectMapper om = new ObjectMapper();
    om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    om.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
    om.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
    om.setSerializationInclusion(Include.NON_NULL);
    om.setSerializationInclusion(Include.NON_EMPTY);
    return om;/*from   w  ww.  ja  va 2s  .co  m*/
}

From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java

/**
 * Creates a new issue in the community tracker.
 * /*from w  w  w . ja va  2 s.c  o  m*/
 * @param httpclient
 *            the http client
 * @param newIssue
 *            the new issue to create on the community tracker
 * @param attachmentsIds
 *            the list of file identifiers that will be attached to the
 *            final issue
 * @param authCookie
 *            the session cookie to use for authentication purpose
 * @return the tracker URL of the newly created issue
 * @throws CommunityAPIException
 */
public static String createNewIssue(CloseableHttpClient httpclient, IssueRequest newIssue,
        List<String> attachmentsIds, Cookie authCookie) throws CommunityAPIException {
    try {
        // Add attachments if any
        if (!attachmentsIds.isEmpty()) {
            IssueField attachmentsField = new IssueField() {
                @Override
                protected String getValueAttributeName() {
                    return "fid"; //$NON-NLS-1$
                }

                @Override
                public boolean isArray() {
                    return true;
                }
            };
            attachmentsField.setName("field_bug_attachments"); //$NON-NLS-1$
            attachmentsField.setValues(attachmentsIds);
            newIssue.setAttachments(attachmentsField);
        }

        HttpPost issueCreationPOST = new HttpPost(CommunityConstants.ISSUE_CREATION_URL);
        EntityBuilder newIssueEntity = EntityBuilder.create();
        newIssueEntity.setText(newIssue.getAsJSON());
        newIssueEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE));
        newIssueEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET);
        issueCreationPOST.setEntity(newIssueEntity.build());
        HttpResponse httpResponse = httpclient.execute(issueCreationPOST);
        int httpRetCode = httpResponse.getStatusLine().getStatusCode();
        String responseBodyAsString = EntityUtils.toString(httpResponse.getEntity());

        if (HttpStatus.SC_OK != httpRetCode) {
            CommunityAPIException ex = new CommunityAPIException(
                    Messages.RESTCommunityHelper_IssueCreationError);
            ex.setHttpStatusCode(httpRetCode);
            ex.setResponseBodyAsString(responseBodyAsString);
            throw ex;
        } else {
            // extract the node ID information in order
            // to retrieve the issue URL available on the tracker
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            JsonNode jsonRoot = mapper.readTree(responseBodyAsString);
            String nodeID = jsonRoot.get("nid").asText(); //$NON-NLS-1$
            JsonNode jsonNodeContent = retrieveNodeContentAsJSON(httpclient, nodeID, authCookie);
            return jsonNodeContent.get("path").asText(); //$NON-NLS-1$
        }

    } catch (UnsupportedEncodingException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_IssueCreationError, e);
    } catch (IOException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_IssueCreationError, e);
    }
}