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.jivesoftware.os.amza.deployable.Main.java

public void run(String[] args) throws Exception {

    String hostname = args[0];/*w ww .j  av  a2  s  .  c o  m*/
    String clusterName = (args.length > 1 ? args[1] : "unnamed");
    String hostPortPeers = (args.length > 2 ? args[2] : null);

    int port = Integer.parseInt(System.getProperty("amza.port", "1175"));
    String multicastGroup = System.getProperty("amza.discovery.group", "225.4.5.6");
    int multicastPort = Integer.parseInt(System.getProperty("amza.discovery.port", "1223"));

    String logicalName = System.getProperty("amza.logicalName", hostname + ":" + port);
    String datacenter = System.getProperty("host.datacenter", "unknownDatacenter");
    String rack = System.getProperty("host.rack", "unknownRack");

    RingMember ringMember = new RingMember(logicalName);
    RingHost ringHost = new RingHost(datacenter, rack, hostname, port);

    // todo need a better way to create writer id.
    int writerId = Integer.parseInt(System.getProperty("amza.id", String.valueOf(new Random().nextInt(512))));

    SnowflakeIdPacker idPacker = new SnowflakeIdPacker();
    JiveEpochTimestampProvider timestampProvider = new JiveEpochTimestampProvider();
    final TimestampedOrderIdProvider orderIdProvider = new OrderIdProviderImpl(
            new ConstantWriterIdProvider(writerId), idPacker, timestampProvider);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(SerializationFeature.INDENT_OUTPUT, false);

    final AmzaServiceConfig amzaServiceConfig = new AmzaServiceConfig();
    final AmzaStats amzaSystemStats = new AmzaStats();
    final AmzaStats amzaStats = new AmzaStats();
    final SickThreads sickThreads = new SickThreads();
    final SickPartitions sickPartitions = new SickPartitions();

    AtomicInteger systemRingSize = new AtomicInteger(-1);
    amzaServiceConfig.workingDirectories = System.getProperty("amza.working.dirs", "./data1,./data2,./data3")
            .split(",");
    amzaServiceConfig.systemRingSize = Integer.parseInt(System.getProperty("amza.system.ring.size", "-1"));
    if (amzaServiceConfig.systemRingSize > 0) {
        systemRingSize.set(amzaServiceConfig.systemRingSize);
    }

    AmzaInterner amzaInterner = new AmzaInterner();

    PartitionPropertyMarshaller partitionPropertyMarshaller = new PartitionPropertyMarshaller() {
        @Override
        public PartitionProperties fromBytes(byte[] bytes) {
            try {
                return mapper.readValue(bytes, PartitionProperties.class);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        @Override
        public byte[] toBytes(PartitionProperties partitionProperties) {
            try {
                return mapper.writeValueAsBytes(partitionProperties);
            } catch (JsonProcessingException ex) {
                throw new RuntimeException(ex);
            }
        }
    };

    //  hmmm
    LABPointerIndexConfig labConfig = BindInterfaceToConfiguration.bindDefault(LABPointerIndexConfig.class);
    labConfig.setLeapCacheMaxCapacity(
            Integer.parseInt(System.getProperty("amza.leap.cache.max.capacity", "1000000")));

    BinaryPrimaryRowMarshaller primaryRowMarshaller = new BinaryPrimaryRowMarshaller(); // hehe you cant change this :)
    BinaryHighwaterRowMarshaller highwaterRowMarshaller = new BinaryHighwaterRowMarshaller(amzaInterner);

    AtomicReference<Callable<RingTopology>> topologyProvider = new AtomicReference<>(); // bit of a hack

    InstanceDescriptor instanceDescriptor = new InstanceDescriptor(datacenter, rack, "", "", "", "", "", "", "",
            "", 0, "", "", "", 0L, true);
    ConnectionDescriptorsProvider connectionsProvider = (connectionDescriptorsRequest,
            expectedReleaseGroup) -> {
        try {
            RingTopology systemRing = topologyProvider.get().call();
            List<ConnectionDescriptor> descriptors = Lists.newArrayList(Iterables.transform(systemRing.entries,
                    input -> new ConnectionDescriptor(instanceDescriptor, false, false,
                            new HostPort(input.ringHost.getHost(), input.ringHost.getPort()),
                            Collections.emptyMap(), Collections.emptyMap())));
            return new ConnectionDescriptorsResponse(200, Collections.emptyList(), "", descriptors,
                    connectionDescriptorsRequest.getRequestUuid());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    };
    TenantsServiceConnectionDescriptorProvider<String> connectionPoolProvider = new TenantsServiceConnectionDescriptorProvider<>(
            Executors.newScheduledThreadPool(1), "", connectionsProvider, "", "", 10_000); // TODO config
    connectionPoolProvider.start();

    TenantAwareHttpClient<String> httpClient = new TenantRoutingHttpClientInitializer<String>(null)
            .builder(connectionPoolProvider, new HttpDeliveryClientHealthProvider("", null, "", 5000, 100))
            .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).maxConnections(1_000)
            .socketTimeoutInMillis(60_000).build(); //TODO expose to conf

    AvailableRowsTaker availableRowsTaker = new HttpAvailableRowsTaker(httpClient, amzaInterner, mapper); // TODO config
    AquariumStats aquariumStats = new AquariumStats();

    AmzaService amzaService = new AmzaServiceInitializer().initialize(amzaServiceConfig, amzaInterner,
            aquariumStats, amzaSystemStats, amzaStats,
            new HealthTimer(CountersAndTimers.getOrCreate("quorumLatency"), "quorumLatency",
                    new NoOpHealthChecker<>("quorumLatency")),
            () -> amzaServiceConfig.systemRingSize, sickThreads, sickPartitions, primaryRowMarshaller,
            highwaterRowMarshaller, ringMember, ringHost, Collections.emptySet(), orderIdProvider, idPacker,
            partitionPropertyMarshaller, (workingIndexDirectories, indexProviderRegistry,
                    ephemeralRowIOProvider, persistentRowIOProvider, partitionStripeFunction) -> {
                indexProviderRegistry
                        .register(
                                new BerkeleyDBWALIndexProvider(BerkeleyDBWALIndexProvider.INDEX_CLASS_NAME,
                                        partitionStripeFunction, workingIndexDirectories),
                                persistentRowIOProvider);

                indexProviderRegistry.register(new LABPointerIndexWALIndexProvider(amzaInterner, labConfig,
                        Executors.newCachedThreadPool(), Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool(), Executors.newCachedThreadPool(),
                        LABPointerIndexWALIndexProvider.INDEX_CLASS_NAME, partitionStripeFunction,
                        workingIndexDirectories), persistentRowIOProvider);
            }, availableRowsTaker, () -> {
                return new HttpRowsTaker("system", amzaStats, httpClient, mapper, amzaInterner,
                        Executors.newSingleThreadExecutor(), Executors.newCachedThreadPool());
            }, () -> {
                return new HttpRowsTaker("striped", amzaStats, httpClient, mapper, amzaInterner,
                        Executors.newSingleThreadExecutor(), Executors.newCachedThreadPool());
            }, Optional.absent(), (changes) -> {
            }, (threadCount, name) -> {
                return Executors.newCachedThreadPool();
            });

    topologyProvider.set(() -> amzaService.getRingReader().getRing(AmzaRingReader.SYSTEM_RING, -1));

    TailAtScaleStrategy tailAtScaleStrategy = new TailAtScaleStrategy(
            BoundedExecutor.newBoundedExecutor(1024, "tas"), 100, // TODO config
            95, // TODO config
            1000 // TODO config
    );

    AmzaClientProvider<HttpClient, HttpClientException> clientProvider = new AmzaClientProvider<>(
            new HttpPartitionClientFactory(),
            new HttpPartitionHostsProvider(httpClient, tailAtScaleStrategy, mapper),
            new RingHostHttpClientProvider(httpClient), BoundedExecutor.newBoundedExecutor(1024, "amza-client"),
            10_000, //TODO expose to conf
            -1, -1);

    final JerseyEndpoints jerseyEndpoints = new JerseyEndpoints().addEndpoint(AmzaEndpoints.class)
            .addInjectable(AmzaService.class, amzaService).addEndpoint(AmzaReplicationRestEndpoints.class)
            .addInjectable(AmzaInstance.class, amzaService).addEndpoint(AmzaClientRestEndpoints.class)
            .addInjectable(AmzaInterner.class, amzaInterner).addInjectable(ObjectMapper.class, mapper)
            .addInjectable(AmzaClientService.class, new AmzaClientService(amzaService.getRingReader(),
                    amzaService.getRingWriter(), amzaService));

    new AmzaUIInitializer().initialize(clusterName, ringHost, amzaService, clientProvider, aquariumStats,
            amzaStats, timestampProvider, idPacker, amzaInterner, new AmzaUIInitializer.InjectionCallback() {
                @Override
                public void addEndpoint(Class clazz) {
                    System.out.println("Adding endpoint=" + clazz);
                    jerseyEndpoints.addEndpoint(clazz);
                }

                @Override
                public void addInjectable(Class clazz, Object instance) {
                    System.out.println("Injecting " + clazz + " " + instance);
                    jerseyEndpoints.addInjectable(clazz, instance);
                }

                @Override
                public void addSessionAuth(String... paths) throws Exception {
                    System.out.println("Ignoring session auth request for paths: " + Arrays.toString(paths));
                }
            });

    InitializeRestfulServer initializeRestfulServer = new InitializeRestfulServer(false, port, "AmzaNode",
            false, null, null, null, 128, 10000);
    initializeRestfulServer.addClasspathResource("/resources");
    initializeRestfulServer.addContextHandler("/", jerseyEndpoints);
    RestfulServer restfulServer = initializeRestfulServer.build();
    restfulServer.start();

    System.out.println("-----------------------------------------------------------------------");
    System.out.println("|      Jetty Service Online");
    System.out.println("-----------------------------------------------------------------------");

    amzaService.start(ringMember, ringHost);

    System.out.println("-----------------------------------------------------------------------");
    System.out.println("|      Amza Service Online");
    System.out.println("-----------------------------------------------------------------------");

    if (clusterName != null) {
        if (hostPortPeers != null) {
            System.out.println("-----------------------------------------------------------------------");
            System.out.println("|     Amza Service is in manual Discovery mode. Cluster Name:" + clusterName);
            String[] peers = hostPortPeers.split(",");
            for (String peer : peers) {
                String[] hostPort = peer.trim().split(":");
                if (hostPort.length != 2 && hostPort.length != 3) {
                    System.out.println("|     Malformed peer:" + peer
                            + " expected form: <host>:<port> or <logicalName>:<host>:<port>");
                } else {
                    String peerLogicalName = (hostPort.length == 2) ? hostPort[0] + ":" + hostPort[1]
                            : hostPort[0];
                    String peerHostname = (hostPort.length == 2) ? hostPort[0] : hostPort[1];
                    String peerPort = (hostPort.length == 2) ? hostPort[1] : hostPort[2];

                    RingMember peerRingMember = new RingMember(peerLogicalName);
                    RingHost peerRingHost = new RingHost("unknown", "unknown", peerHostname,
                            Integer.parseInt(peerPort));

                    System.out.println("|     Adding ringMember:" + peerRingMember + " on host:" + peerRingHost
                            + " to cluster: " + clusterName);
                    amzaService.getRingWriter().register(peerRingMember, peerRingHost, writerId, false);
                }
            }
            systemRingSize.set(1 + peers.length);
            System.out.println("-----------------------------------------------------------------------");
        } else {
            AmzaDiscovery amzaDiscovery = new AmzaDiscovery(amzaService.getRingReader(),
                    amzaService.getRingWriter(), clusterName, multicastGroup, multicastPort, systemRingSize);
            amzaDiscovery.start();
            System.out.println("-----------------------------------------------------------------------");
            System.out.println("|      Amza Service Discovery Online: Cluster Name:" + clusterName);
            System.out.println("-----------------------------------------------------------------------");
        }
    } else {
        System.out.println("-----------------------------------------------------------------------");
        System.out.println("|     Amza Service is in manual Discovery mode.  No cluster name was specified");
        System.out.println("-----------------------------------------------------------------------");
    }
}

From source file:com.jivesoftware.os.upena.deployable.UpenaEndpoints.java

private NodeHealth buildNodeHealth() throws Exception {
    NodeHealth nodeHealth = new NodeHealth(ringHostKey.getKey(), ringHost.getHost(), ringHost.getPort());
    for (Entry<String, Nanny> nanny : ubaService.iterateNannies()) {
        Nanny n = nanny.getValue();/*from   w  w  w .  j av  a2  s .co  m*/
        InstanceDescriptor id = n.getInstanceDescriptor();
        List<String> log = n.getDeployLog().commitedLog();
        List<String> copyLog = n.getHealthLog().commitedLog();
        ServiceHealth serviceHealth = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

            if (!copyLog.isEmpty()) {
                serviceHealth = mapper.readValue(Joiner.on("").join(copyLog), ServiceHealth.class);
                nodeHealth.health = Math.min(nodeHealth.health, serviceHealth.health);
            }
        } catch (Exception x) {
            LOG.warn("Failed parsing service health for " + id + " " + Joiner.on("").join(copyLog), x);
            nodeHealth.health = 0.0d;
            log.add("Failed to parse serviceHealth" + x.getMessage());
        }
        if (serviceHealth == null) {
            serviceHealth = new ServiceHealth();
            serviceHealth.health = -1;
        }
        String uptime = "unknown";
        if (nanny.getValue().getStartTimeMillis() > 0) {
            uptime = humanReadableUptime(System.currentTimeMillis() - nanny.getValue().getStartTimeMillis());
        }

        NannyHealth nannyHealth = new NannyHealth(uptime, id, log, serviceHealth);
        if (nanny.getValue().getUnexpectedRestartTimestamp() > -1) {
            nannyHealth.unexpectedRestart = nanny.getValue().getUnexpectedRestartTimestamp();
        }

        Map<String, String> lastOverrideFetchedVersion = upenaConfigStore.changesSinceLastFetch(id.instanceKey,
                "override");
        Map<String, String> lastOverrideHealthFetchedVersion = upenaConfigStore
                .changesSinceLastFetch(id.instanceKey, "override-health");
        nannyHealth.configIsStale = lastOverrideFetchedVersion;
        nannyHealth.healthConfigIsStale = lastOverrideHealthFetchedVersion;

        nannyHealth.status = n.getStatus();
        nodeHealth.nannyHealths.add(nannyHealth);

    }
    return nodeHealth;

}

From source file:cc.arduino.contributions.packages.ContributionsIndexer.java

private ContributionsIndex parseIndex(File indexFile) throws IOException {
    InputStream inputStream = null;
    try {/*  www.ja va 2 s.  com*/
        inputStream = new FileInputStream(indexFile);
        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);
        return mapper.readValue(inputStream, ContributionsIndex.class);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:uk.ac.sanger.npg.picard.AlignmentFilterTest.java

public int compareJSONFiles(String file_one, String file_two) throws FileNotFoundException, IOException {

    ObjectMapper objectMapper = new ObjectMapper();
    byte[] jsonData_one = Files.readAllBytes(Paths.get(file_one));
    byte[] jsonData_two = Files.readAllBytes(Paths.get(file_two));

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    JSONtest filter_one = objectMapper.readValue(jsonData_one, JSONtest.class);
    JSONtest filter_two = objectMapper.readValue(jsonData_two, JSONtest.class);

    assertEquals(filter_one.programCommand, filter_two.programCommand);
    assertEquals(filter_one.numberAlignments, filter_two.numberAlignments);
    assertEquals(filter_one.totalReads, filter_two.totalReads);
    assertEquals(filter_one.readsCountUnaligned, filter_two.readsCountUnaligned);
    assertArrayEquals(filter_one.readsCountPerRef, filter_two.readsCountPerRef);
    assertArrayEquals(filter_one.chimericReadsCount, filter_two.chimericReadsCount);
    assertArrayEquals(filter_one.readsCountByAlignedNumReverse, filter_two.readsCountByAlignedNumReverse);
    assertArrayEquals(filter_one.readsCountByAlignedNumForward, filter_two.readsCountByAlignedNumForward);

    return 1;//from ww w  . j  a v a  2s .co m
}

From source file:org.primeframework.mvc.test.RequestResult.java

/**
 * Verifies that the response body is equal to the given JSON text.
 *
 * @param json The JSON text.//from   www. j a  v  a 2 s . com
 * @return This.
 * @throws IOException If the JSON marshalling failed.
 */
public RequestResult assertJSON(String json) throws IOException {
    ObjectMapper objectMapper = injector.getInstance(ObjectMapper.class);
    Object response = objectMapper.readValue(body, Object.class);
    Object file = objectMapper.readValue(json, Object.class);
    if (!response.equals(file)) {
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        String bodyString = objectMapper.writeValueAsString(response);
        String fileString = objectMapper.writeValueAsString(file);
        throw new AssertionError("The body doesn't match the expected JSON output. expected [" + fileString
                + "] but found [" + bodyString + "]");
    }
    return this;
}

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

public static JSONObject getServerByProjectAndUserAccess(Long projectId, String providerName, Long serverId) {

    //SecurityUtils.getSubject()

    try {/*ww w . j ava 2  s  . c  om*/

        Set<ProjectProviders> lstProviders = ProjectImpl.getCloudProviders(projectId);

        Iterator<ProjectProviders> itrProviders = lstProviders.iterator();
        JSONObject res = new JSONObject();
        JSONArray jsoServersArray = new JSONArray();

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

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

            //TODO: Refactor to support more Cloud Providers....
            try {
                Logger.debug("API KEY : " + prov.getApikey() + " and secret : " + prov.getSecretkey());
                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;
                            }
                        }

                        JSONObject jsoDropletImage = JSONObject.fromObject(ow.writeValueAsString(droplet));

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

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

                        if (dsize != null) {
                            jsoDropletImage.put("size", dsize);
                        }
                        jsoServersArray.add(jsoDropletImage);
                    }

                } else {
                    //nothing
                }

                res.put("servers", jsoServersArray);
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
        //res.put("servers",jsoServersArray);
        return res;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.commonjava.cartographer.client.CartographerRESTClient.java

public ObjectMapper newObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModules(new CartoAPIObjectMapperModules().getSerializerModules());
    mapper.setVisibility(ALL, NONE);/*  w  w  w. ja v a  2 s  .c  om*/
    mapper.setVisibility(FIELD, ANY);
    mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper;
}

From source file:com.dawg6.d3api.server.D3IO.java

public CareerProfile readCareerProfile(String string, boolean ignoreUnknown)
        throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    if (ignoreUnknown) {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }//from w  ww .ja  v a  2 s  . co m
    CareerProfile out = mapper.readValue(new File(string), CareerProfile.class);
    return out;
}

From source file:com.dawg6.d3api.server.D3IO.java

public HeroProfile readHeroProfile(String string, boolean ignoreUnknown)
        throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    if (ignoreUnknown) {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }//w  w w  . j  a va  2  s  . co  m
    HeroProfile out = mapper.readValue(new File(string), HeroProfile.class);
    return out;
}

From source file:com.dawg6.d3api.server.D3IO.java

public ItemInformation readItemInformation(String string, boolean ignoreUnknown)
        throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    if (ignoreUnknown) {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }//from   ww  w. java 2  s.c om
    ItemInformation out = mapper.readValue(new File(string), ItemInformation.class);
    return out;
}