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:eu.europa.ec.fisheries.uvms.reporting.rest.resources.ReportingResource.java

private ObjectNode mapToGeoJson(ExecutionResultDTO dto) throws IOException {

    ObjectNode rootNode;//from  w  w w  . jav  a2  s  .co m

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    rootNode = mapper.createObjectNode();
    StringWriter stringWriter = new StringWriter();

    GeometryMapper.INSTANCE.featureCollectionToGeoJson(dto.getMovements(), stringWriter);

    rootNode.set("movements", mapper.readTree(stringWriter.toString()));

    stringWriter.getBuffer().setLength(0);
    GeometryMapper.INSTANCE.featureCollectionToGeoJson(dto.getSegments(), stringWriter);
    rootNode.set("segments", mapper.readTree(stringWriter.toString()));

    rootNode.putPOJO("tracks", dto.getTracks());
    rootNode.putPOJO("trips", dto.getTrips());

    ObjectNode activityNode = new FeatureToGeoJsonJacksonMapper().convert(dto.getActivities());
    rootNode.putPOJO("activities", activityNode);

    rootNode.putPOJO("criteria", dto.getFaCatchSummaryDTO());

    return rootNode;
}

From source file:com.netflix.dyno.queues.redis.RedisDynoQueue.java

public RedisDynoQueue(String redisKeyPrefix, String queueName, Set<String> allShards, String shardName,
        ExecutorService dynoCallExecutor) {
    this.redisKeyPrefix = redisKeyPrefix;
    this.queueName = queueName;
    this.allShards = allShards.stream().collect(Collectors.toList());
    this.shardName = shardName;
    this.messageStoreKey = redisKeyPrefix + ".MESSAGE." + queueName;
    this.myQueueShard = getQueueShardKey(queueName, shardName);

    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);
    om.disable(SerializationFeature.INDENT_OUTPUT);

    this.om = om;
    this.monitor = new QueueMonitor(queueName, shardName);
    this.prefetchedIds = new LinkedBlockingQueue<>();
    this.executorService = dynoCallExecutor;

    Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> processUnacks(), unackScheduleInMS,
            unackScheduleInMS, TimeUnit.MILLISECONDS);
    Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> prefetchIds(), 0, 10, TimeUnit.MILLISECONDS);

    logger.info(RedisDynoQueue.class.getName() + " is ready to serve " + queueName);

}

From source file:de.undercouch.bson4jackson.BsonParserTest.java

@Test
public void parseBig() throws Exception {
    BSONObject o = new BasicBSONObject();
    o.put("Double", 5.0);
    o.put("Int32", 1234);
    BSONEncoder enc = new BasicBSONEncoder();
    byte[] b = enc.encode(o);

    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    ObjectMapper mapper = new ObjectMapper(new BsonFactory());
    mapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
    mapper.configure(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS, true);
    Map<?, ?> data = mapper.readValue(bais, Map.class);
    assertEquals(BigDecimal.class, data.get("Double").getClass());
    assertEquals(BigInteger.class, data.get("Int32").getClass());
}

From source file:com.corundumstudio.socketio.parser.JacksonJsonSupport.java

protected void init(ObjectMapper objectMapper) {
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Event.class, eventDeserializer);
    module.addDeserializer(JsonObject.class, jsonObjectDeserializer);
    module.addDeserializer(AckArgs.class, ackArgsDeserializer);
    objectMapper.registerModule(module);

    objectMapper.setSerializationInclusion(Include.NON_NULL);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN, true);

    //        TODO If jsonObjectDeserializer will be not enough
    //        TypeResolverBuilder<?> typer = new DefaultTypeResolverBuilder(DefaultTyping.NON_FINAL);
    //        typer.init(JsonTypeInfo.Id.CLASS, null);
    //        typer.inclusion(JsonTypeInfo.As.PROPERTY);
    //        typer.typeProperty(configuration.getJsonTypeFieldName());
    //        objectMapper.setDefaultTyping(typer);
}

From source file:com.muk.services.configuration.ServiceConfig.java

/**
 * @return A json object mapper used in all muk interactions.
 *///from w w w . j a  va2 s .c  om
@Bean(name = { "jsonObjectMapper" })
public ObjectMapper jsonObjectMapper() {
    final ObjectMapper mapper = new ObjectMapper();

    mapper.registerModule(new PairModule());
    mapper.registerModule(new JavaTimeModule());
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    return mapper;
}

From source file:com.acentera.utils.ProjectsHelpers.java

public static JSONObject getServersByProjectAndUserAccess(Long projectId, User user) {

    JSONObject res = new JSONObject();
    JSONArray jsoServersArray = new JSONArray();
    res.put("servers", jsoServersArray);
    try {/*w  w  w.j  a  v a 2s  .  c o  m*/
        //TODO: Take the one that match the selected api tags only (ie: have access to)
        Set<ProjectProviders> lstProviders = ProjectImpl.getCloudProviders(projectId);

        Iterator<ProjectProviders> itrProviders = lstProviders.iterator();

        Logger.debug("GOT PROVIDER : " + lstProviders);

        List<DropletImage> lstDropletImages = null;
        List<Region> lstRegions = null;
        List<DropletSize> lstSize = null;

        Project p = ProjectImpl.getProject(projectId, user);
        Set<ProjectDevices> deviceSet = DeviceImpl.getDevices(projectId);

        HashMap<String, ProjectDevices> devicesToReturn = new HashMap<String, ProjectDevices>();
        Set<Long> processedDevices = new HashSet<Long>();

        while (itrProviders.hasNext()) {
            ProjectProviders prov = itrProviders.next();

            //TODO: Refactor to support more Cloud Providers....
            try {
                DigitalOcean apiClient = new DigitalOceanClient(prov.getApikey(), prov.getSecretkey());

                List<Droplet> lstDroplets = apiClient.getAvailableDroplets();

                if (lstDroplets != null) {
                    JSONObject jso = new JSONObject();

                    ObjectMapper mapper = new ObjectMapper();
                    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
                    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
                    ObjectWriter ow = mapper.writer();

                    //jsoServersArray.add(ow.writeValueAsString(lstDroplets));
                    for (int i = 0; i < lstDroplets.size(); i++) {
                        Droplet droplet = lstDroplets.get(i);

                        if (lstDropletImages == null) {
                            lstDropletImages = apiClient.getAvailableImages();
                        }
                        if (lstRegions == null) {
                            lstRegions = apiClient.getAvailableRegions();
                        }

                        if (lstSize == null) {
                            lstSize = apiClient.getAvailableSizes();
                        }

                        DropletImage dimage = null;
                        Iterator<DropletImage> itrImages = lstDropletImages.iterator();
                        while (dimage == null && itrImages.hasNext()) {
                            DropletImage img = itrImages.next();
                            if (img.getId().intValue() == droplet.getImageId().intValue()) {
                                dimage = img;
                            }
                        }

                        Region dregion = null;
                        Iterator<Region> itrRegions = lstRegions.iterator();
                        while (dregion == null && itrRegions.hasNext()) {
                            Region region = itrRegions.next();
                            if (region.getId().intValue() == droplet.getRegionId().intValue()) {
                                dregion = region;
                            }
                        }

                        DropletSize dsize = null;
                        Iterator<DropletSize> itrSize = lstSize.iterator();
                        while (dsize == null && itrSize.hasNext()) {
                            DropletSize size = itrSize.next();
                            Logger.debug("COMPARE SIZE OF : " + size.getId() + " VS " + droplet.getSizeId());
                            if (size.getId().intValue() == droplet.getSizeId().intValue()) {
                                Logger.debug("COMPARE SIZE OF : " + size.getId() + " VS " + droplet.getSizeId()
                                        + " FOUND");
                                dsize = size;
                            }
                        }

                        ProjectDevices deviceInProjectMapping = null;
                        Iterator<ProjectDevices> itrDevices = deviceSet.iterator();
                        while (itrDevices.hasNext() && deviceInProjectMapping == null) {
                            ProjectDevices pd = itrDevices.next();
                            //Try to find a device that matches the current one we are looking at..
                            if (((pd.getExternalId().compareTo(String.valueOf(droplet.getId())) == 0) && (pd
                                    .getProviders().getType().compareToIgnoreCase(prov.getType()) == 0))) {
                                deviceInProjectMapping = pd;
                            }
                        }

                        if (deviceInProjectMapping == null) {
                            //Device does not exists...
                            //Lets create a Generic GUID and also save the mapping...

                            //First create a Device
                            //Currently the framework doesn't automatically import data..
                            /*
                            Device dev = new Device();
                            dev.setProject(p);
                            dev.setPartner_id(user.getProject_id());
                            dev.setGUID(Utils.getUniqueGUID());
                            dev.setSalt(Utils.getRandomSalt());
                                    
                            ProjectDevices projectDevice = new ProjectDevices();
                            projectDevice.setDevice(dev);
                            projectDevice.setProject(p);
                            projectDevice.setExternalId( String.valueOf(droplet.getId()));
                            projectDevice.setProviders(prov);
                                    
                            DAO.save(dev);
                            DAO.save(projectDevice);
                            deviceInProjectMapping = projectDevice;
                            */
                        }

                        Logger.debug("deviceInProjectMapping");
                        if (deviceInProjectMapping != null) {
                            JSONObject jsoDroplet = JSONObject.fromObject(ow.writeValueAsString(droplet));

                            if (dimage != null) {
                                jsoDroplet.put("image_distibution", dimage.getDistribution());
                                jsoDroplet.put("image_name", dimage.getName());
                            }

                            if (dregion != null) {
                                jsoDroplet.put("region_slug", dregion.getSlug());
                                jsoDroplet.put("region_name", dregion.getName());
                            }

                            if (dsize != null) {
                                jsoDroplet.put("size", dsize);
                            }
                            ////jsoDroplet.put("acenteraid", deviceInProjectMapping.getDevice().getId());
                            jsoDroplet.put("acenteraid", deviceInProjectMapping.getId());

                            Logger.debug("deviceInProjectMapping acenteraid " + deviceInProjectMapping.getId());
                            jsoDroplet.put("external_id", droplet.getId());
                            jsoDroplet.put("id", deviceInProjectMapping.getId());
                            jsoDroplet.put("type", deviceInProjectMapping.getType());
                            deviceInProjectMapping.getDevice().setDropletInfo(jsoDroplet);

                            devicesToReturn.put(droplet.getId() + "_" + prov.getId(), deviceInProjectMapping);
                        }

                    }

                } else {
                    //nothing
                }

                //CHeck if all the api returned all the values... (what about api that we deleted??)
                Iterator<ProjectDevices> itrDevices = deviceSet.iterator();
                Logger.debug("GOT ProjectDevices  ??? ");
                while (itrDevices.hasNext()) {
                    ProjectDevices pd = itrDevices.next();
                    Logger.debug("GOT ProjectDevices : " + pd);
                    String key = pd.getExternalId() + "_" + pd.getProviders().getId();
                    if (!(devicesToReturn.containsKey(key))) {
                        //Device not found lets add

                        //We must get the JSONValue...
                        devicesToReturn.put(key, pd);
                    }
                }

                //At this point deviceTOReturn contains all of the entries...

                Logger.debug("deviceTOReturn ProjectDevices  ??? ");
                Iterator<Map.Entry<String, ProjectDevices>> itrResponse = devicesToReturn.entrySet().iterator();
                while (itrResponse.hasNext()) {
                    Map.Entry<String, ProjectDevices> item = itrResponse.next();
                    Logger.debug("deviceTOReturn ProjectDevices  : " + item.getValue());
                    Logger.debug("deviceTOReturn ProjectDevices  Device : " + item.getValue().getDevice());
                    Logger.debug("deviceTOReturn ProjectDevices  Device getDropletInfo : "
                            + item.getValue().getDevice().getDropletInfo());
                    if (item.getValue().getDevice().getDropletInfo().has("id")) {
                        if (!(processedDevices.contains(item.getValue().getDevice().getId()))) {
                            processedDevices.add(item.getValue().getDevice().getId());
                            jsoServersArray.add(item.getValue().getDevice().getDropletInfo());
                        }
                    }
                }

                Logger.debug("deviceInProjectMapping REGURNING OF : " + jsoServersArray);
                res.put("servers", jsoServersArray);
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
        //res.put("servers",jsoServersArray);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return res;
}

From source file:com.corundumstudio.socketio.protocol.JacksonJsonSupport.java

protected void init(ObjectMapper objectMapper) {
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(modifier);
    module.addDeserializer(Event.class, eventDeserializer);
    module.addDeserializer(AckArgs.class, ackArgsDeserializer);
    objectMapper.registerModule(module);

    objectMapper.setSerializationInclusion(Include.NON_NULL);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN, true);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}

From source file:com.rcv.ResultsWriter.java

private void generateSummaryJson(Map<Integer, Map<String, BigDecimal>> roundTallies, String precinct,
        String outputPath) throws IOException {

    // mapper converts java objects to json
    ObjectMapper mapper = new ObjectMapper();
    // set mapper to order keys alphabetically for more legible output
    mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
    // create a module to contain a serializer for BigDecimal serialization
    SimpleModule module = new SimpleModule();
    module.addSerializer(BigDecimal.class, new ToStringSerializer());
    // attach serializer to mapper
    mapper.registerModule(module);/*from   www . j a  v  a2 s.c  om*/

    // jsonWriter writes those object to disk
    ObjectWriter jsonWriter = mapper.writer(new DefaultPrettyPrinter());
    // jsonPath for output json summary
    String jsonPath = outputPath + ".json";
    // log output location
    Logger.log(Level.INFO, "Generating summary JSON file: %s...", jsonPath);
    // outFile is the target file
    File outFile = new File(jsonPath);

    // root outputJson dict will have two entries:
    // results - vote totals, transfers, and candidates elected / eliminated
    // config - global config into
    HashMap<String, Object> outputJson = new HashMap<>();
    // config will contain contest configuration info
    HashMap<String, Object> configData = new HashMap<>();
    // add config header info
    configData.put("contest", config.getContestName());
    configData.put("jurisdiction", config.getContestJurisdiction());
    configData.put("office", config.getContestOffice());
    configData.put("date", config.getContestDate());
    configData.put("threshold", winningThreshold);
    if (precinct != null && !precinct.isEmpty()) {
        configData.put("precinct", precinct);
    }
    // results will be a list of round data objects
    ArrayList<Object> results = new ArrayList<>();
    // for each round create objects for json serialization
    for (int round = 1; round <= numRounds; round++) {
        // container for all json data this round:
        HashMap<String, Object> roundData = new HashMap<>();
        // add round number (this is implied by the ordering but for debugging we are explicit)
        roundData.put("round", round);
        // add actions if this is not a precinct summary
        if (precinct == null || precinct.isEmpty()) {
            // actions is a list of one or more action objects
            ArrayList<Object> actions = new ArrayList<>();
            addActionObjects("elected", roundToWinningCandidates.get(round), round, actions);
            // add any elimination actions
            addActionObjects("eliminated", roundToEliminatedCandidates.get(round), round, actions);
            // add action objects
            roundData.put("tallyResults", actions);
        }
        // add tally object
        roundData.put("tally", updateCandidateNamesInTally(roundTallies.get(round)));
        // add roundData to results list
        results.add(roundData);
    }
    // add config data to root object
    outputJson.put("config", configData);
    // add results to root object
    outputJson.put("results", results);
    // write results to disk
    try {
        jsonWriter.writeValue(outFile, outputJson);
    } catch (IOException exception) {
        Logger.log(Level.SEVERE, "Error writing to JSON file: %s\n%s", jsonPath, exception.toString());
        throw exception;
    }
}

From source file:eu.trentorise.opendata.jackan.CkanClient.java

/**
 * Configures the provided Jackson ObjectMapper exactly as the internal JSON
 * mapper used for reading operations. If you want to perform
 * create/update/delete operations, use// w w  w .j  a  va2  s.  c o  m
 * {@link #configureObjectMapperForPosting(com.fasterxml.jackson.databind.ObjectMapper, java.lang.Class) }
 * instead.
 *
 * @param om
 *            a Jackson object mapper
 * @since 0.4.1
 */
public static void configureObjectMapper(ObjectMapper om) {
    om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    om.registerModule(new JackanModule());
}

From source file:org.opendaylight.groupbasedpolicy.renderer.opflex.lib.messages.OpflexMessageTest.java

@Before
public void setUp() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}