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.springframework.data.rest.tests.RepositoryTestsConfig.java

@Bean
public ObjectMapper objectMapper() {

    RelProvider relProvider = new EvoInflectorRelProvider();
    ObjectMapper mapper = new ObjectMapper();

    mapper.registerModule(new Jackson2HalModule());
    mapper.registerModule(persistentEntityModule());
    mapper.setHandlerInstantiator(new Jackson2HalModule.HalHandlerInstantiator(relProvider, null, null));
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(Include.NON_EMPTY);

    return mapper;
}

From source file:sg.yeefan.searchenginewrapper.clients.WikipediaClient.java

/**
 * Makes a query to Google Custom Search using a default query.
 *///from  w w  w.jav a 2  s .  c om
private SearchEngineResults getResults(DefaultSearchEngineQuery query) throws SearchEngineException {
    if (query == null)
        throw new SearchEngineFatalException("Missing query.");
    String keyString = query.getKey();
    String label = query.getLabel();
    String queryString = query.getQuery();
    long startIndex = query.getStartIndex();
    if (startIndex < 1)
        throw new SearchEngineFatalException("Start index must be at least 1.");
    String encodedQuery = null;
    try {
        encodedQuery = URLEncoder.encode(queryString, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new SearchEngineFatalException(e);
    }
    long startTime = System.currentTimeMillis();
    FileDownloader downloader = new FileDownloader();
    String jsonString = null;
    try {
        downloader.setUserAgent(
                "Search Engine Wrapper (http://wing.comp.nus.edu.sg/~tanyeefa/downloads/searchenginewrapper/)");
        String requestUrl = "http://" + this.host + "/w/api.php?action=query&list=search&srsearch="
                + encodedQuery + "&srinfo=totalhits&srprop=snippet&sroffset=" + (startIndex - 1)
                + "&srlimit=50&format=json";
        byte[] bytes = downloader.download(requestUrl);
        jsonString = new String(bytes, "UTF-8");
    } catch (FileDownloaderException e) {
        // It appears that rate-limiting quotas is not
        // implemented.
        throw new SearchEngineException(e);
    } catch (UnsupportedEncodingException e) {
        throw new SearchEngineException(e);
    }
    long endTime = System.currentTimeMillis();
    Response response = null;
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        response = mapper.readValue(jsonString, Response.class);
    } catch (IOException e) {
        throw new SearchEngineException(e);
    }
    Query responseQuery = response.getQuery();
    SearchEngineResults results = new SearchEngineResults();
    results.setLabel(label);
    results.setQuery(queryString);
    results.setTotalResults(responseQuery.getSearchinfo().getTotalhits());
    results.setStartIndex(startIndex);
    Item[] items = responseQuery.getSearch();
    SearchEngineResult[] resultArray = new SearchEngineResult[items.length];
    for (int i = 0; i < items.length; i++) {
        String title = items[i].getTitle();
        String snippet = items[i].getSnippet();
        resultArray[i] = new SearchEngineResult();
        resultArray[i].setURL(getArticleURL(title));
        resultArray[i].setTitle(title);
        resultArray[i].setSnippet(processSnippet(snippet));
    }
    results.setResults(resultArray);
    results.setStartTime(startTime);
    results.setEndTime(endTime);
    if (response.getQueryContinue() != null) {
        DefaultSearchEngineQuery nextQuery = new DefaultSearchEngineQuery();
        nextQuery.setKey(keyString);
        nextQuery.setLabel(label);
        nextQuery.setQuery(queryString);
        nextQuery.setStartIndex(startIndex + items.length);
        results.setNextQuery(nextQuery);
    }
    return results;
}

From source file:alfio.config.MvcConfiguration.java

@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    return mapper;
}

From source file:com.ning.metrics.action.endpoint.HdfsBrowser.java

@GET
@Produces(MediaType.APPLICATION_JSON)//  w w  w .  ja  v a  2  s  .c  om
@Path("/viewer")
@Timed
public Response prettyPrintOneLine(@QueryParam("object") final String object) throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ObjectMapper mapper = new ObjectMapper();

    final String objectURIDecoded = URLDecoder.decode(object, "UTF-8");
    final byte[] objectBase64Decoded = Base64.decodeBase64(objectURIDecoded.getBytes());

    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    final LinkedHashMap map = mapper.readValue(new String(objectBase64Decoded), LinkedHashMap.class);

    // We need to re-serialize the json (pretty print works only on serialization)
    mapper.writeValue(out, map);

    return Response.ok().entity(new String(out.toByteArray())).build();
}

From source file:com.netflix.discovery.converters.jackson.EurekaJsonJacksonCodec.java

private ObjectMapper createObjectMapper(KeyFormatter keyFormatter, boolean compact, boolean wrapped) {
    ObjectMapper newMapper = new ObjectMapper();
    SimpleModule jsonModule = new SimpleModule();
    jsonModule.setSerializerModifier(/*from ww w  .  j av  a2  s  .  c o  m*/
            EurekaJacksonJsonModifiers.createJsonSerializerModifier(keyFormatter, compact));

    newMapper.registerModule(jsonModule);
    newMapper.setSerializationInclusion(Include.NON_NULL);
    newMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, wrapped);
    newMapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, false);
    newMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapped);
    newMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    newMapper.addMixIn(Applications.class, ApplicationsJsonMixIn.class);
    if (compact) {
        addMiniConfig(newMapper);
    } else {
        newMapper.addMixIn(InstanceInfo.class, InstanceInfoJsonMixIn.class);
    }
    return newMapper;
}

From source file:com.google.code.siren4j.converter.ReflectingConverterTest.java

@Test
//@Ignore//w  w  w.  j a  v a  2s .  c o m
public void testToJacksonThereAndBackEntity() throws Exception {

    Entity ent = ReflectingConverter.newInstance().toEntity(getTestCourse());
    String there = ent.toString();

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    Entity back = mapper.readValue(there, Entity.class);
    assertEquals(ent.toString(), back.toString());
}

From source file:org.springframework.session.data.mongo.JacksonMongoSessionConverter.java

private ObjectMapper buildObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();

    // serialize fields instead of properties
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
    objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

    // ignore unresolved fields (mostly 'principal')
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    objectMapper.setPropertyNamingStrategy(new MongoIdNamingStrategy());
    return objectMapper;
}

From source file:fr.ortolang.diffusion.runtime.engine.task.ImportProfilesTask.java

@Override
public void executeTask(DelegateExecution execution) throws RuntimeEngineTaskException {
    checkParameters(execution);//from   w ww  .ja  va  2  s.c  om
    String profilespath = execution.getVariable(PROFILES_PATH_PARAM_NAME, String.class);
    boolean overwrite = false;
    if (execution.hasVariable(PROFILES_OVERWRITE_PARAM_NAME)) {
        overwrite = Boolean.parseBoolean(execution.getVariable(PROFILES_OVERWRITE_PARAM_NAME, String.class));
    }

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    try {
        List<JsonProfile> profiles = Arrays
                .asList(mapper.readValue(new File(profilespath), JsonProfile[].class));
        LOGGER.log(Level.FINE, "- starting import profiles");
        boolean partial = false;
        boolean exists;
        StringBuilder report = new StringBuilder();
        for (JsonProfile profile : profiles) {
            exists = false;
            try {
                getMembershipService().readProfile(profile.pro_login);
                LOGGER.log(Level.FINE, "  profile already exists for username: " + profile.pro_login);
                exists = true;
            } catch (KeyNotFoundException | AccessDeniedException | MembershipServiceException e) {
                //
            }
            if (!exists) {
                try {
                    getMembershipService().createProfile(profile.pro_login, profile.pro_firstname,
                            profile.pro_lastname, profile.pro_emailt, ProfileStatus.ACTIVE);
                } catch (ProfileAlreadyExistsException | AccessDeniedException | MembershipServiceException e) {
                    partial = true;
                    report.append("creation failed for: ").append(profile.pro_login).append("\r\n");
                    LOGGER.log(Level.SEVERE, "  unable to create profile: " + profile.pro_login, e);
                }
            }
            if (exists && overwrite) {
                try {
                    getMembershipService().updateProfile(profile.pro_login, profile.pro_firstname,
                            profile.pro_lastname, profile.pro_emailt, null);
                } catch (KeyNotFoundException | AccessDeniedException | MembershipServiceException e) {
                    partial = true;
                    report.append("update failed for existing profile: ").append(profile.pro_login)
                            .append("\r\n");
                    LOGGER.log(Level.SEVERE, "  unable to update profile: " + profile.pro_login, e);
                }
            }
            if (!exists || (exists && overwrite)) {
                try {
                    if (profile.pro_genre != null && profile.pro_genre.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "civility", profile.pro_genre,
                                ProfileDataVisibility.EVERYBODY, ProfileDataType.ENUM, "");
                    }
                    if (profile.pro_titre != null && profile.pro_titre.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "title", profile.pro_titre,
                                ProfileDataVisibility.EVERYBODY, ProfileDataType.STRING, "");
                    }
                    if (profile.pro_firstname != null && profile.pro_firstname.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "given_name",
                                profile.pro_firstname, ProfileDataVisibility.EVERYBODY, ProfileDataType.STRING,
                                "");
                    }
                    if (profile.pro_lastname != null && profile.pro_lastname.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "family_name",
                                profile.pro_lastname, ProfileDataVisibility.EVERYBODY, ProfileDataType.STRING,
                                "");
                    }
                    if (profile.pro_emailt != null && profile.pro_emailt.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "professional_email",
                                profile.pro_emailt, ProfileDataVisibility.EVERYBODY, ProfileDataType.EMAIL, "");
                    }
                    if (profile.pro_email != null && profile.pro_email.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "rescue_email",
                                profile.pro_email, ProfileDataVisibility.EVERYBODY, ProfileDataType.EMAIL, "");
                    }
                    if (profile.pro_organisme != null && profile.pro_organisme.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "organisation",
                                profile.pro_organisme, ProfileDataVisibility.EVERYBODY, ProfileDataType.STRING,
                                "");
                    }
                    if (profile.pro_metier != null && profile.pro_metier.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "job", profile.pro_metier,
                                ProfileDataVisibility.EVERYBODY, ProfileDataType.STRING, "");
                    }
                    if (profile.pro_domaine_recherche != null && profile.pro_domaine_recherche.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "field_of_research",
                                profile.pro_domaine_recherche, ProfileDataVisibility.EVERYBODY,
                                ProfileDataType.STRING, "");
                    }
                    String address = profile.pro_adresse + ", " + profile.pro_cp + ", " + profile.pro_ville
                            + ", " + profile.pro_pays_nom;
                    if (address.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "address", address,
                                ProfileDataVisibility.EVERYBODY, ProfileDataType.ADDRESS, "");
                    }
                    if (profile.pro_organisme_url != null && profile.pro_organisme_url.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "website",
                                profile.pro_organisme_url, ProfileDataVisibility.EVERYBODY,
                                ProfileDataType.STRING, "");
                    }
                    if (profile.pro_telephonet != null && profile.pro_telephonet.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "professional_tel",
                                profile.pro_telephonet, ProfileDataVisibility.EVERYBODY, ProfileDataType.TEL,
                                "");
                    }
                    if (profile.pro_telephone != null && profile.pro_telephone.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "tel", profile.pro_telephone,
                                ProfileDataVisibility.EVERYBODY, ProfileDataType.TEL, "");
                    }
                    if (profile.pro_telecopie != null && profile.pro_telecopie.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "fax", profile.pro_telecopie,
                                ProfileDataVisibility.EVERYBODY, ProfileDataType.TEL, "");
                    }
                    if (profile.pro_langue != null && profile.pro_langue.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "language", profile.pro_langue,
                                ProfileDataVisibility.EVERYBODY, ProfileDataType.ENUM, "");
                    }
                    if (profile.pro_id_orcid != null && profile.pro_id_orcid.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "orcid", profile.pro_id_orcid,
                                ProfileDataVisibility.EVERYBODY, ProfileDataType.STRING, "");
                    }
                    if (profile.pro_id_viaf != null && profile.pro_id_viaf.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "viaf", profile.pro_id_viaf,
                                ProfileDataVisibility.EVERYBODY, ProfileDataType.STRING, "");
                    }
                    if (profile.pro_id_idref != null && profile.pro_id_idref.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "myidref",
                                profile.pro_id_idref, ProfileDataVisibility.EVERYBODY, ProfileDataType.STRING,
                                "");
                    }
                    if (profile.pro_id_linkedin != null && profile.pro_id_linkedin.length() > 0) {
                        getMembershipService().setProfileInfo(profile.pro_login, "linkedin",
                                profile.pro_id_linkedin, ProfileDataVisibility.EVERYBODY,
                                ProfileDataType.STRING, "");
                    }
                } catch (KeyNotFoundException | AccessDeniedException | MembershipServiceException e) {
                    partial = true;
                    report.append("unable to set info for profile: ").append(profile.pro_login).append("\r\n");
                    LOGGER.log(Level.SEVERE,
                            "  unable to set profile info for identifier: " + profile.pro_login, e);
                }
            }
        }

        if (partial) {
            throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessLogEvent(execution.getProcessBusinessKey(),
                    "Some profiles has not been imported (see trace for detail)"));
            throwRuntimeEngineEvent(RuntimeEngineEvent
                    .createProcessTraceEvent(execution.getProcessBusinessKey(), report.toString(), null));
        }
        throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessLogEvent(execution.getProcessBusinessKey(),
                "Import Profiles done"));
    } catch (IOException e) {
        throw new RuntimeEngineTaskException("error parsing json file: " + e.getMessage());
    }
}

From source file:org.killbill.billing.plugin.util.http.HttpClient.java

protected ObjectMapper createObjectMapper() {
    final ObjectMapper mapper = new ObjectMapper();

    // Tells the serializer to only include those parameters that are not null
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    // Allow special characters
    mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);

    // Write dates using a ISO-8601 compliant notation
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    return mapper;
}

From source file:com.dell.asm.asmcore.asmmanager.client.util.ServiceTemplateClientUtil.java

private static ObjectMapper buildObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector ai = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    mapper.setAnnotationIntrospector(ai);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper;
}