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

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

Introduction

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

Prototype

public ObjectMapper enable(SerializationFeature f) 

Source Link

Document

Method for enabling specified DeserializationConfig feature.

Usage

From source file:com.derpgroup.livefinder.App.java

@Override
public void run(MainConfig config, Environment environment) throws IOException {
    if (config.isPrettyPrint()) {
        ObjectMapper mapper = environment.getObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
    }/*from   www.  ja va  2s .c om*/

    // Health checks
    environment.healthChecks().register("basics", new BasicHealthCheck(config, environment));

    AccountLinkingDAOConfig accountLinkingDAOConfig = config.getDaoConfig().getAccountLinking();

    // DAO
    AccountLinkingDAO accountLinkingDAO = AccountLinkingDAOFactory.getDAO(accountLinkingDAOConfig);

    SteamClientWrapper wrapper = SteamClientWrapper.getInstance();
    wrapper.init(config.getLiveFinderConfig().getApiKey());
    TwitchClientWrapper twitchWrapper = TwitchClientWrapper.getInstance();
    TwitchAccountLinkingConfig twitchConfig = config.getLiveFinderConfig().getTwitchAccountLinkingConfig();
    twitchWrapper.init(twitchConfig.getTwitchApiRootUri(), twitchConfig.getClientId(),
            twitchConfig.getClientSecret(), twitchConfig.getRedirectUri());

    // Resources
    environment.jersey().register(new LiveFinderAlexaResource(config, environment, accountLinkingDAO));
    environment.jersey().register(new AuthResource(config, environment, accountLinkingDAO));
}

From source file:org.apereo.openlrs.Application.java

@Bean
@Primary// ww w  .ja  v a2 s. c om
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    return mapper;
}

From source file:com.derpgroup.echodebugger.App.java

@Override
public void run(MainConfig config, Environment environment) throws IOException {
    if (config.isPrettyPrint()) {
        ObjectMapper mapper = environment.getObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.registerModule(new JavaTimeModule());
        mapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    }/*from  w w w  .ja  va2 s.  c o m*/

    // Health checks
    environment.healthChecks().register("basics", new BasicHealthCheck(config, environment));

    // Load up the content
    UserDaoLocalImpl userDao = new UserDaoLocalImpl(config, environment);
    userDao.initialize();

    // Build the helper thread that saves data every X minutes
    UserDaoLocalImplThread userThread = new UserDaoLocalImplThread(config, userDao);
    userThread.start();

    EchoDebuggerResource debuggerResource = new EchoDebuggerResource(config, environment);
    debuggerResource.setUserDao(userDao);

    // Resources
    environment.jersey().register(debuggerResource);

    // Providers
    environment.jersey().register(new ResponderExceptionMapper());
}

From source file:com.bodybuilding.argos.controller.StreamController.java

@Autowired
public StreamController(ClusterRegistry registry, Observable<Boolean> shutdown) {
    Objects.requireNonNull(registry);
    Objects.requireNonNull(shutdown);
    ObjectMapper om = new ObjectMapper();
    om.enable(MapperFeature.AUTO_DETECT_FIELDS);
    om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

    Observable<HystrixClusterMetrics> metricsObs = registry.observe();

    streamObservable = metricsObs.takeUntil(shutdown).map(d -> {
        try {/*from w  w w  .j av a  2s . com*/
            return om.writeValueAsString(d);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }).share();
}

From source file:com.helpmobile.test.UserTest.java

@Test
public void test() throws IOException {
    ObjectMapper mapper = new RestObjectMapper();
    mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);

    RestAccess rest = new RestAccess();

    User result = rest.retriveId("12345");
    String json = mapper.writeValueAsString(result);

    System.out.println(json);// w w w.j  a v a 2s  .  c  o  m
    //UserReply user = mapper.readValue(result, UserReply.class);

}

From source file:dk.lnj.swagger4ee.AbstractJSonTest.java

public void makeCompare(SWRoot root, String expFile) throws IOException {

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    // make deserializer use JAXB annotations (only)
    mapper.setAnnotationIntrospector(introspector);
    // make serializer use JAXB annotations (only)

    StringWriter sw = new StringWriter();
    mapper.writeValue(sw, root);//from  w  w  w . j av a 2s .  c  o m
    mapper.writeValue(new FileWriter(new File("lasttest.json")), root);

    String actual = sw.toString();
    String expected = new String(Files.readAllBytes(Paths.get(expFile)));

    String[] exp_split = expected.split("\n");
    String[] act_split = actual.split("\n");

    for (int i = 0; i < exp_split.length; i++) {
        String exp = exp_split[i];
        String act = act_split[i];
        String shortFileName = expFile.substring(expFile.lastIndexOf("/"));
        Assert.assertEquals(shortFileName + ":" + (i + 1), superTrim(exp), superTrim(act));
    }

}

From source file:com.ericsson.eiffel.remrem.publish.config.GsonHttpMessageConverterWithValidate.java

@Override
protected Object readInternal(Type resolvedType, Reader reader) throws Exception {
    try {// w  w  w  .  java 2s  .  com
        final String json = IOUtils.toString(reader);
        // do the actual validation
        final ObjectMapper mapper = new ObjectMapper();
        mapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
        mapper.readTree(json);
        return this.gson.fromJson(json, resolvedType);
    } catch (JsonParseException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    }

}

From source file:com.ericsson.eiffel.remrem.generate.config.GsonHttpMessageConverterWithValidate.java

@Override
protected Object readInternal(Type resolvedType, Reader reader) throws Exception {
    try {/*from   ww w.  j  a v a  2  s  .  c o m*/
        final String json = IOUtils.toString(reader);
        // do the actual validation
        final ObjectMapper mapper = new ObjectMapper();
        mapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
        mapper.readTree(json);
        return this.gson.fromJson(json, resolvedType);
    } catch (JsonParseException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    }
}

From source file:com.github.helenusdriver.driver.tools.Tool.java

/**
 * Creates all defined Json schemas based on the provided command line
 * information./* www .  ja v  a  2 s. c  o m*/
 *
 * @author paouelle
 *
 * @param  line the command line information
 * @throws Exception if an error occurs while creating schemas
 * @throws LinkageError if the linkage fails for one of the specified entity
 *         class
 * @throws ExceptionInInitializerError if the initialization provoked by one
 *         of the specified entity class fails
 * @throws IllegalArgumentException if no pojos are found in any of the
 *         specified packages
 */
private static void createJsonSchemas(CommandLine line) throws Exception {
    final String[] opts = line.getOptionValues(Tool.jsons.getLongOpt());
    @SuppressWarnings({ "cast", "unchecked", "rawtypes" })
    final Map<String, String> suffixes = (Map<String, String>) (Map) line
            .getOptionProperties(Tool.suffixes.getOpt());
    final boolean matching = line.hasOption(Tool.matches_only.getLongOpt());
    final Map<Class<?>, JsonSchema> schemas = new LinkedHashMap<>();

    System.out.print(
            Tool.class.getSimpleName() + ": searching for Json schema definitions in " + Arrays.toString(opts));
    if (!suffixes.isEmpty()) {
        System.out.print(" with " + (matching ? "matching " : "") + "suffixes " + suffixes);
    }
    System.out.println();
    // start by assuming we have classes; if we do they will be nulled from the array
    Tool.createJsonSchemasFromClasses(opts, suffixes, matching, schemas);
    // now deal with the rest as if they were packages
    Tool.createJsonSchemasFromPackages(opts, suffixes, matching, schemas);
    if (schemas.isEmpty()) {
        System.out.println(
                Tool.class.getSimpleName() + ": no Json schemas found matching the specified criteria");
    } else {
        final String output = line.getOptionValue(Tool.output.getLongOpt(), "." // defaults to current directory
        );
        final File dir = new File(output);

        if (!dir.exists()) {
            dir.mkdirs();
        }
        org.apache.commons.lang3.Validate.isTrue(dir.isDirectory(), "not a directory: %s", dir);
        final ObjectMapper m = new ObjectMapper();

        m.enable(SerializationFeature.INDENT_OUTPUT);
        for (final Map.Entry<Class<?>, JsonSchema> e : schemas.entrySet()) {
            m.writeValue(new File(dir, e.getKey().getName() + ".json"), e.getValue());
            //System.out.println(s.getType() + " = " + m.writeValueAsString(s));
        }
    }
}

From source file:org.dihedron.webmvc.renderers.impl.JsonRenderer.java

/**
 * @see org.dihedron.webmvc.renderers.Renderer#render(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String)
 *//*w  w  w .j a  va2s  .com*/
@Override
public void render(HttpServletRequest request, HttpServletResponse response, String data)
        throws IOException, WebMVCException {
    String bean = data;
    logger.trace("rendering bean '{}'", bean);
    Object object = getBean(request, bean);
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    String json = mapper.writeValueAsString(object);
    logger.trace("json object is:\n{}", json);
    response.setContentType(JSON_MIME_TYPE);
    getWriter(response).print(json);
    getWriter(response).flush();
}