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:com.neovisionaries.security.JsonDigestUpdater.java

private ObjectMapper createObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();

    mapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);

    return mapper;
}

From source file:cc.arduino.contributions.libraries.LibrariesIndexer.java

private void parseIndex(File file) throws IOException {
    InputStream indexIn = null;// ww w . ja  v a2s  .c  om
    try {
        indexIn = new FileInputStream(file);
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new MrBeanModule());
        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        mapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH, true);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        LibrariesIndex newIndex = mapper.readValue(indexIn, LibrariesIndex.class);

        newIndex.getLibraries().stream()
                .filter(library -> library.getCategory() == null || "".equals(library.getCategory())
                        || !Constants.LIBRARY_CATEGORIES.contains(library.getCategory()))
                .forEach(library -> library.setCategory("Uncategorized"));

        index = newIndex;
    } catch (JsonParseException | JsonMappingException e) {
        System.err.println(format(tr(
                "Error parsing libraries index: {0}\nTry to open the Library Manager to update the libraries index."),
                e.getMessage()));
    } catch (Exception e) {
        System.err.println(format(tr("Error reading libraries index: {0}"), e.getMessage()));
    } finally {
        IOUtils.closeQuietly(indexIn);
    }
}

From source file:com.esri.geoportal.commons.gpt.client.Client.java

private <T> T execute(HttpUriRequest req, Class<T> clazz) throws IOException {

    try (CloseableHttpResponse httpResponse = execute(req);
            InputStream contentStream = httpResponse.getEntity().getContent();) {
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
        }//from w w  w.  j  a va 2s.  c  o  m
        String responseContent = IOUtils.toString(contentStream, "UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.readValue(responseContent, clazz);
    }
}

From source file:org.apache.nifi.processors.att.m2x.PutM2XStream.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;//  w w  w  .  j  a va2  s  . com
    }

    final ProcessorLog logger = getLogger();
    final OkHttpClient httpClient = getHttpClient();
    final StateManager stateManager = context.getStateManager();
    final String apiKey = context.getProperty(M2X_API_KEY).getValue();
    final String apiUrl = context.getProperty(M2X_API_URL).getValue();
    final String deviceId = context.getProperty(M2X_DEVICE_ID).getValue();
    final String streamName = context.getProperty(M2X_STREAM_NAME).getValue();
    final String streamType = context.getProperty(M2X_STREAM_TYPE).getValue();
    final String streamUrl = new StringBuilder().append(apiUrl.replaceAll("/*$", "")).append("/devices/")
            .append(deviceId).append("/streams/").append(streamName).append("/value").toString();

    try {
        final AtomicReference<String> postBodyRef = new AtomicReference<>();
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream is) {
                try {
                    String timestamp = flowFile.getAttribute("m2x.stream.value.timestamp");
                    if (StringUtils.isEmpty(timestamp)) {
                        timestamp = ISODateTimeFormat.dateTime().print(flowFile.getEntryDate());
                    }
                    final String value = IOUtils.toString(is, StandardCharsets.UTF_8);

                    final M2XStreamValue m2xValue = new M2XStreamValue();
                    m2xValue.setValue(value);
                    m2xValue.setTimestamp(timestamp);

                    final ObjectMapper mapper = new ObjectMapper();
                    mapper.registerModule(new JodaModule());
                    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

                    final String postBody = mapper.writeValueAsString(m2xValue);
                    logger.warn("POST body is {}", new Object[] { postBody });
                    postBodyRef.set(postBody);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        });

        final String postBody = postBodyRef.get();
        if (StringUtils.isEmpty(postBody)) {
            logger.error("FlowFile {} contents didn't produce a valid M2X stream value",
                    new Object[] { flowFile });
            session.transfer(flowFile, REL_FAILURE);
            return;
        }

        final Request request = new Request.Builder().url(streamUrl).addHeader("X-M2X-KEY", apiKey)
                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody)).build();
        final Response response = httpClient.newCall(request).execute();

        if (!response.isSuccessful()) {
            logger.error(response.message());
            context.yield();
            session.penalize(flowFile);
            return;
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        context.yield();
        session.penalize(flowFile);
        return;
    }

    session.transfer(flowFile, REL_SUCCESS);
}

From source file:io.dockstore.webservice.DockstoreWebserviceApplication.java

@Override
public void run(DockstoreWebserviceConfiguration configuration, Environment environment) {
    BeanConfig beanConfig = new BeanConfig();
    beanConfig.setSchemes(new String[] { configuration.getScheme() });
    beanConfig.setHost(configuration.getHostname() + ':' + configuration.getPort());
    beanConfig.setBasePath("/");
    beanConfig.setResourcePackage("io.dockstore.webservice.resources,io.swagger.api");
    beanConfig.setScan(true);// w w  w.  j  a v a 2s . com

    final QuayIOAuthenticationResource resource2 = new QuayIOAuthenticationResource(
            configuration.getQuayClientID(), configuration.getQuayRedirectURI());
    environment.jersey().register(resource2);

    final TemplateHealthCheck healthCheck = new TemplateHealthCheck(configuration.getTemplate());
    environment.healthChecks().register("template", healthCheck);

    final UserDAO userDAO = new UserDAO(hibernate.getSessionFactory());
    final TokenDAO tokenDAO = new TokenDAO(hibernate.getSessionFactory());
    final ToolDAO toolDAO = new ToolDAO(hibernate.getSessionFactory());
    final WorkflowDAO workflowDAO = new WorkflowDAO(hibernate.getSessionFactory());
    final WorkflowVersionDAO workflowVersionDAO = new WorkflowVersionDAO(hibernate.getSessionFactory());

    final GroupDAO groupDAO = new GroupDAO(hibernate.getSessionFactory());
    final TagDAO tagDAO = new TagDAO(hibernate.getSessionFactory());
    final LabelDAO labelDAO = new LabelDAO(hibernate.getSessionFactory());
    final FileDAO fileDAO = new FileDAO(hibernate.getSessionFactory());

    LOG.info("Cache directory for OkHttp is: " + cache.directory().getAbsolutePath());
    LOG.info("This is our custom logger saying that we're about to load authenticators");
    // setup authentication to allow session access in authenticators, see https://github.com/dropwizard/dropwizard/pull/1361
    SimpleAuthenticator authenticator = new UnitOfWorkAwareProxyFactory(getHibernate()).create(
            SimpleAuthenticator.class, new Class[] { TokenDAO.class, UserDAO.class },
            new Object[] { tokenDAO, userDAO });
    CachingAuthenticator<String, User> cachingAuthenticator = new CachingAuthenticator<>(environment.metrics(),
            authenticator, configuration.getAuthenticationCachePolicy());
    environment.jersey()
            .register(new AuthDynamicFeature(new OAuthCredentialAuthFilter.Builder<User>()
                    .setAuthenticator(cachingAuthenticator).setAuthorizer(new SimpleAuthorizer())
                    .setPrefix("Bearer").setRealm("SUPER SECRET STUFF").buildAuthFilter()));
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
    environment.jersey().register(RolesAllowedDynamicFeature.class);

    final ObjectMapper mapper = environment.getObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    final HttpClient httpClient = new HttpClientBuilder(environment)
            .using(configuration.getHttpClientConfiguration()).build(getName());
    final DockerRepoResource dockerRepoResource = new DockerRepoResource(mapper, httpClient, userDAO, tokenDAO,
            toolDAO, tagDAO, labelDAO, fileDAO, configuration.getBitbucketClientID(),
            configuration.getBitbucketClientSecret());
    environment.jersey().register(dockerRepoResource);
    environment.jersey().register(new GitHubRepoResource(tokenDAO));
    environment.jersey().register(new DockerRepoTagResource(toolDAO, tagDAO));

    final GitHubComAuthenticationResource resource3 = new GitHubComAuthenticationResource(
            configuration.getGithubClientID(), configuration.getGithubRedirectURI());
    environment.jersey().register(resource3);

    final BitbucketOrgAuthenticationResource resource4 = new BitbucketOrgAuthenticationResource(
            configuration.getBitbucketClientID());
    environment.jersey().register(resource4);

    environment.jersey()
            .register(new TokenResource(tokenDAO, userDAO, configuration.getGithubClientID(),
                    configuration.getGithubClientSecret(), configuration.getBitbucketClientID(),
                    configuration.getBitbucketClientSecret(), httpClient, cachingAuthenticator));

    final WorkflowResource workflowResource = new WorkflowResource(httpClient, userDAO, tokenDAO, workflowDAO,
            workflowVersionDAO, labelDAO, fileDAO, configuration.getBitbucketClientID(),
            configuration.getBitbucketClientSecret());
    environment.jersey().register(workflowResource);

    environment.jersey().register(
            new UserResource(httpClient, tokenDAO, userDAO, groupDAO, workflowResource, dockerRepoResource));

    // attach the container dao statically to avoid too much modification of generated code
    ToolsApiServiceImpl.setToolDAO(toolDAO);
    ToolsApiServiceImpl.setConfig(configuration);
    environment.jersey().register(new ToolsApi());

    // swagger stuff

    // Swagger providers
    environment.jersey().register(ApiListingResource.class);
    environment.jersey().register(SwaggerSerializers.class);

    // optional CORS support
    // Enable CORS headers
    // final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class);
    final FilterHolder filterHolder = environment.getApplicationContext().addFilter(CrossOriginFilter.class,
            "/*", EnumSet.of(REQUEST));

    // Configure CORS parameters
    // cors.setInitParameter("allowedOrigins", "*");
    // cors.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin");
    // cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");

    filterHolder.setInitParameter(ACCESS_CONTROL_ALLOW_METHODS_HEADER, "GET,POST,DELETE,PUT,OPTIONS");
    filterHolder.setInitParameter(ALLOWED_ORIGINS_PARAM, "*");
    filterHolder.setInitParameter(ALLOWED_METHODS_PARAM, "GET,POST,DELETE,PUT,OPTIONS");
    filterHolder.setInitParameter(ALLOWED_HEADERS_PARAM,
            "Authorization, X-Auth-Username, X-Auth-Password, X-Requested-With,Content-Type,Accept,Origin,Access-Control-Request-Headers,cache-control");

    // Add URL mapping
    // cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
    // cors.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, environment.getApplicationContext().getContextPath() +
    // "*");
}

From source file:org.apache.htrace.impl.Conf.java

@Override
public String toString() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    try {//from  w ww.  j  a va  2 s  .c o  m
        return mapper.writeValueAsString(this);
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.wso2.iot.agent.services.operation.OperationProcessor.java

/**
 * Set policy bundle.//www  . j a v  a 2s  . com
 *
 * @param operation - Operation object.
 */
public void setPolicyBundle(org.wso2.iot.agent.beans.Operation operation) throws AndroidAgentException {
    if (isDeviceAdminActive()) {
        if (Preference.getString(context, Constants.PreferenceFlag.APPLIED_POLICY) != null) {
            operationManager.revokePolicy(operation);
        }
        String payload = operation.getPayLoad().toString();
        if (Constants.DEBUG_MODE_ENABLED) {
            Log.d(TAG, "Policy payload: " + payload);
        }
        PolicyOperationsMapper operationsMapper = new PolicyOperationsMapper();
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        try {
            if (payload != null) {
                Preference.putString(context, Constants.PreferenceFlag.APPLIED_POLICY, payload);
            }

            List<Operation> operations = mapper.readValue(payload, mapper.getTypeFactory()
                    .constructCollectionType(List.class, org.wso2.iot.agent.beans.Operation.class));

            for (org.wso2.iot.agent.beans.Operation op : operations) {
                op = operationsMapper.getOperation(op);
                this.doTask(op);
            }
            operation.setStatus(context.getResources().getString(R.string.operation_value_completed));
            operationManager.setPolicyBundle(operation);

            if (Constants.DEBUG_MODE_ENABLED) {
                Log.d(TAG, "Policy applied");
            }
        } catch (IOException e) {
            operation.setStatus(context.getResources().getString(R.string.operation_value_error));
            operation.setOperationResponse("Error occurred while parsing policy bundle stream.");
            operationManager.setPolicyBundle(operation);
            throw new AndroidAgentException("Error occurred while parsing stream", e);
        }
    } else {
        operation.setStatus(context.getResources().getString(R.string.operation_value_error));
        operation.setOperationResponse("Device administrator is not activated, hence cannot execute policies.");
        operationManager.setPolicyBundle(operation);
        throw new AndroidAgentException("Device administrator is not activated, hence cannot execute policies");
    }
}

From source file:ch.bfh.unicert.certimport.Certificate.java

/**
 * Helper method allowing to convert a Date in ISO format string
 * @param date the date to convert/*from   w ww.  j  a  v a 2  s  .c  o m*/
 * @return the string representing the date in ISO format
 */
private String formatDate(Date date) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        return mapper.writeValueAsString(date);
    } catch (JsonProcessingException ex) {
        Logger.getLogger(Certificate.class.getName()).log(Level.SEVERE, "Unable to JSONize date", ex);
        return "\"\"";
    }
}

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

/**
 * Write object.//  w  w w.j  ava2s . com
 *
 * @param out the out
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void writeObject(final java.io.ObjectOutputStream out) throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    mapper.writeValue(out, req);
}

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

/**
 * Read object.//from www .ja v  a 2 s  . c om
 *
 * @param in the in
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ClassNotFoundException the class not found exception
 */
private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
    req = mapper.readValue(in, ObjectNode.class);
}