Search in sources :

Example 31 with ObjectWriter

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter in project navajo by Dexels.

the class TestRuntime method testVerjaardag.

@Test
public void testVerjaardag() throws IOException, NoJSONOutputException, APIException {
    File art = context.resolveArticle("/verjaardagen");
    TestRuntimeImpl tr = new TestRuntimeImpl("verjaardagen", art, null);
    context.interpretArticle(art, tr);
    String out = tr.getOutput();
    System.err.println(out);
    ObjectMapper mapper = new ObjectMapper();
    JsonNode rootNode = mapper.readValue(out, JsonNode.class);
    ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
    System.out.println(writer.writeValueAsString(rootNode));
    Assert.assertEquals(11, rootNode.size());
}
Also used : ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) TestRuntimeImpl(com.dexels.navajo.article.test.TestRuntimeImpl) JsonNode(com.fasterxml.jackson.databind.JsonNode) File(java.io.File) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 32 with ObjectWriter

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter in project tutorials by eugenp.

the class ExtraAnnotationUnitTest method whenUsingJsonAppendAnnotation_thenCorrect.

@Test
public void whenUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation");
    ObjectWriter writer = mapper.writerFor(BeanWithAppend.class).withAttribute("version", "1.0");
    String jsonString = writer.writeValueAsString(bean);
    assertThat(jsonString, containsString("version"));
    assertThat(jsonString, containsString("1.0"));
}
Also used : BeanWithAppend(com.baeldung.jackson.annotation.extra.AppendBeans.BeanWithAppend) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 33 with ObjectWriter

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter in project Server_Management_Plugin_vRealize by Huawei.

the class ServerDeviceBean method toString.

@Override
public String toString() {
    try {
        // 转换为json字符串
        // .withDefaultPrettyPrinter()
        ObjectWriter ow = new ObjectMapper().writer();
        String json = ow.writeValueAsString(this);
        return json;
    } catch (JsonProcessingException e) {
        return "";
    }
}
Also used : ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 34 with ObjectWriter

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter in project Server_Management_Plugin_vRealize by Huawei.

the class ServerDeviceDetailBean method toString.

@Override
public String toString() {
    try {
        // 转换为json字符串
        // .withDefaultPrettyPrinter()
        ObjectWriter ow = new ObjectMapper().writer();
        String json = ow.writeValueAsString(this);
        return json;
    } catch (JsonProcessingException e) {
        return "";
    }
}
Also used : ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 35 with ObjectWriter

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter in project incubator-pulsar by apache.

the class ManagedLedgerWriter method main.

public static void main(String[] args) throws Exception {
    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-producer");
    try {
        jc.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        jc.usage();
        System.exit(-1);
    }
    if (arguments.help) {
        jc.usage();
        System.exit(-1);
    }
    arguments.testTime = TimeUnit.SECONDS.toMillis(arguments.testTime);
    // Dump config variables
    ObjectMapper m = new ObjectMapper();
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    log.info("Starting Pulsar managed-ledger perf writer with config: {}", w.writeValueAsString(arguments));
    byte[] payloadData = new byte[arguments.msgSize];
    ByteBuf payloadBuffer = PooledByteBufAllocator.DEFAULT.directBuffer(arguments.msgSize);
    payloadBuffer.writerIndex(arguments.msgSize);
    // Now processing command line arguments
    String managedLedgerPrefix = "test-" + DigestUtils.sha1Hex(UUID.randomUUID().toString()).substring(0, 5);
    ClientConfiguration bkConf = new ClientConfiguration();
    bkConf.setUseV2WireProtocol(true);
    bkConf.setLedgerManagerFactoryClass(HierarchicalLedgerManagerFactory.class);
    bkConf.setAddEntryTimeout(30);
    bkConf.setReadEntryTimeout(30);
    bkConf.setThrottleValue(0);
    bkConf.setNumChannelsPerBookie(arguments.maxConnections);
    bkConf.setZkServers(arguments.zookeeperServers);
    ManagedLedgerFactoryConfig mlFactoryConf = new ManagedLedgerFactoryConfig();
    mlFactoryConf.setMaxCacheSize(0);
    ManagedLedgerFactory factory = new ManagedLedgerFactoryImpl(bkConf, mlFactoryConf);
    ManagedLedgerConfig mlConf = new ManagedLedgerConfig();
    mlConf.setEnsembleSize(arguments.ensembleSize);
    mlConf.setWriteQuorumSize(arguments.writeQuorum);
    mlConf.setAckQuorumSize(arguments.ackQuorum);
    mlConf.setMinimumRolloverTime(10, TimeUnit.MINUTES);
    mlConf.setMetadataEnsembleSize(arguments.ensembleSize);
    mlConf.setMetadataWriteQuorumSize(arguments.writeQuorum);
    mlConf.setMetadataAckQuorumSize(arguments.ackQuorum);
    mlConf.setDigestType(arguments.digestType);
    mlConf.setMaxSizePerLedgerMb(2048);
    List<CompletableFuture<ManagedLedger>> futures = new ArrayList<>();
    for (int i = 0; i < arguments.numManagedLedgers; i++) {
        String name = String.format("%s-%03d", managedLedgerPrefix, i);
        CompletableFuture<ManagedLedger> future = new CompletableFuture<>();
        futures.add(future);
        factory.asyncOpen(name, mlConf, new OpenLedgerCallback() {

            @Override
            public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
                future.complete(ledger);
            }

            @Override
            public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
                future.completeExceptionally(exception);
            }
        }, null);
    }
    List<ManagedLedger> managedLedgers = futures.stream().map(CompletableFuture::join).collect(Collectors.toList());
    log.info("Created {} managed ledgers", managedLedgers.size());
    Runtime.getRuntime().addShutdownHook(new Thread() {

        public void run() {
            printAggregatedStats();
        }
    });
    Collections.shuffle(managedLedgers);
    AtomicBoolean isDone = new AtomicBoolean();
    List<List<ManagedLedger>> managedLedgersPerThread = Lists.partition(managedLedgers, Math.max(1, managedLedgers.size() / arguments.numThreads));
    for (int i = 0; i < arguments.numThreads; i++) {
        List<ManagedLedger> managedLedgersForThisThread = managedLedgersPerThread.get(i);
        int nunManagedLedgersForThisThread = managedLedgersForThisThread.size();
        long numMessagesForThisThread = arguments.numMessages / arguments.numThreads;
        int maxOutstandingForThisThread = arguments.maxOutstanding;
        executor.submit(() -> {
            try {
                final double msgRate = arguments.msgRate / (double) arguments.numThreads;
                final RateLimiter rateLimiter = RateLimiter.create(msgRate);
                // Acquire 1 sec worth of messages to have a slower ramp-up
                rateLimiter.acquire((int) msgRate);
                final long startTime = System.currentTimeMillis();
                final Semaphore semaphore = new Semaphore(maxOutstandingForThisThread);
                final AddEntryCallback addEntryCallback = new AddEntryCallback() {

                    @Override
                    public void addComplete(Position position, Object ctx) {
                        long sendTime = (Long) (ctx);
                        messagesSent.increment();
                        bytesSent.add(payloadData.length);
                        long latencyMicros = NANOSECONDS.toMicros(System.nanoTime() - sendTime);
                        recorder.recordValue(latencyMicros);
                        cumulativeRecorder.recordValue(latencyMicros);
                        semaphore.release();
                    }

                    @Override
                    public void addFailed(ManagedLedgerException exception, Object ctx) {
                        log.warn("Write error on message", exception);
                        System.exit(-1);
                    }
                };
                // Send messages on all topics/producers
                long totalSent = 0;
                while (true) {
                    for (int j = 0; j < nunManagedLedgersForThisThread; j++) {
                        if (arguments.testTime > 0) {
                            if (System.currentTimeMillis() - startTime > arguments.testTime) {
                                log.info("------------------- DONE -----------------------");
                                printAggregatedStats();
                                isDone.set(true);
                                Thread.sleep(5000);
                                System.exit(0);
                            }
                        }
                        if (numMessagesForThisThread > 0) {
                            if (totalSent++ >= numMessagesForThisThread) {
                                log.info("------------------- DONE -----------------------");
                                printAggregatedStats();
                                isDone.set(true);
                                Thread.sleep(5000);
                                System.exit(0);
                            }
                        }
                        semaphore.acquire();
                        rateLimiter.acquire();
                        final long sendTime = System.nanoTime();
                        managedLedgersForThisThread.get(j).asyncAddEntry(payloadBuffer, addEntryCallback, sendTime);
                    }
                }
            } catch (Throwable t) {
                log.error("Got error", t);
            }
        });
    }
    // Print report stats
    long oldTime = System.nanoTime();
    Histogram reportHistogram = null;
    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            break;
        }
        if (isDone.get()) {
            break;
        }
        long now = System.nanoTime();
        double elapsed = (now - oldTime) / 1e9;
        double rate = messagesSent.sumThenReset() / elapsed;
        double throughput = bytesSent.sumThenReset() / elapsed / 1024 / 1024 * 8;
        reportHistogram = recorder.getIntervalHistogram(reportHistogram);
        log.info("Throughput produced: {}  msg/s --- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}", throughputFormat.format(rate), throughputFormat.format(throughput), dec.format(reportHistogram.getMean() / 1000.0), dec.format(reportHistogram.getValueAtPercentile(50) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(95) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99.9) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99.99) / 1000.0), dec.format(reportHistogram.getMaxValue() / 1000.0));
        reportHistogram.reset();
        oldTime = now;
    }
    factory.shutdown();
}
Also used : Histogram(org.HdrHistogram.Histogram) ManagedLedgerFactoryConfig(org.apache.bookkeeper.mledger.ManagedLedgerFactoryConfig) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ArrayList(java.util.ArrayList) Semaphore(java.util.concurrent.Semaphore) ByteBuf(io.netty.buffer.ByteBuf) CompletableFuture(java.util.concurrent.CompletableFuture) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) JCommander(com.beust.jcommander.JCommander) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ParameterException(com.beust.jcommander.ParameterException) ArrayList(java.util.ArrayList) List(java.util.List) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ManagedLedgerFactoryImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerFactoryImpl) Position(org.apache.bookkeeper.mledger.Position) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) RateLimiter(com.google.common.util.concurrent.RateLimiter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) ClientConfiguration(org.apache.bookkeeper.conf.ClientConfiguration)

Aggregations

ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)140 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)61 IOException (java.io.IOException)31 Test (org.junit.Test)30 File (java.io.File)17 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)15 ArrayList (java.util.ArrayList)12 ObjectReader (com.fasterxml.jackson.databind.ObjectReader)11 JavaType (com.fasterxml.jackson.databind.JavaType)10 JsonNode (com.fasterxml.jackson.databind.JsonNode)10 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)7 FileOutputStream (java.io.FileOutputStream)7 OutputStream (java.io.OutputStream)7 StringWriter (java.io.StringWriter)7 Map (java.util.Map)7 JCommander (com.beust.jcommander.JCommander)6 ParameterException (com.beust.jcommander.ParameterException)6 SimpleFilterProvider (com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider)6 RateLimiter (com.google.common.util.concurrent.RateLimiter)6 FileInputStream (java.io.FileInputStream)6