Search in sources :

Example 36 with ObjectWriter

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

the class PerformanceReader method main.

public static void main(String[] args) throws Exception {
    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-reader");
    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);
    }
    if (arguments.topic.size() != 1) {
        System.out.println("Only one topic name is allowed");
        jc.usage();
        System.exit(-1);
    }
    if (arguments.confFile != null) {
        Properties prop = new Properties(System.getProperties());
        prop.load(new FileInputStream(arguments.confFile));
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("brokerServiceUrl");
        }
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("webServiceUrl");
        }
        // fallback to previous-version serviceUrl property to maintain backward-compatibility
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("serviceUrl", "http://localhost:8080/");
        }
        if (arguments.authPluginClassName == null) {
            arguments.authPluginClassName = prop.getProperty("authPlugin", null);
        }
        if (arguments.authParams == null) {
            arguments.authParams = prop.getProperty("authParams", null);
        }
        if (arguments.useTls == false) {
            arguments.useTls = Boolean.parseBoolean(prop.getProperty("useTls"));
        }
        if (isBlank(arguments.tlsTrustCertsFilePath)) {
            arguments.tlsTrustCertsFilePath = prop.getProperty("tlsTrustCertsFilePath", "");
        }
    }
    // Dump config variables
    ObjectMapper m = new ObjectMapper();
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    log.info("Starting Pulsar performance reader with config: {}", w.writeValueAsString(arguments));
    final TopicName prefixTopicName = TopicName.get(arguments.topic.get(0));
    final RateLimiter limiter = arguments.rate > 0 ? RateLimiter.create(arguments.rate) : null;
    ReaderListener<byte[]> listener = (reader, msg) -> {
        messagesReceived.increment();
        bytesReceived.add(msg.getData().length);
        if (limiter != null) {
            limiter.acquire();
        }
    };
    ClientBuilder clientBuilder = // 
    PulsarClient.builder().serviceUrl(// 
    arguments.serviceURL).connectionsPerBroker(// 
    arguments.maxConnections).statsInterval(arguments.statsIntervalSeconds, // 
    TimeUnit.SECONDS).ioThreads(// 
    Runtime.getRuntime().availableProcessors()).enableTls(// 
    arguments.useTls).tlsTrustCertsFilePath(arguments.tlsTrustCertsFilePath);
    if (isNotBlank(arguments.authPluginClassName)) {
        clientBuilder.authentication(arguments.authPluginClassName, arguments.authParams);
    }
    PulsarClient pulsarClient = clientBuilder.build();
    List<CompletableFuture<Reader<byte[]>>> futures = Lists.newArrayList();
    MessageId startMessageId;
    if ("earliest".equals(arguments.startMessageId)) {
        startMessageId = MessageId.earliest;
    } else if ("latest".equals(arguments.startMessageId)) {
        startMessageId = MessageId.latest;
    } else {
        String[] parts = arguments.startMessageId.split(":");
        startMessageId = new MessageIdImpl(Long.parseLong(parts[0]), Long.parseLong(parts[1]), -1);
    }
    ReaderBuilder<byte[]> readerBuilder = // 
    pulsarClient.newReader().readerListener(// 
    listener).receiverQueueSize(// 
    arguments.receiverQueueSize).startMessageId(startMessageId);
    for (int i = 0; i < arguments.numTopics; i++) {
        final TopicName topicName = (arguments.numTopics == 1) ? prefixTopicName : TopicName.get(String.format("%s-%d", prefixTopicName, i));
        futures.add(readerBuilder.clone().topic(topicName.toString()).createAsync());
    }
    FutureUtil.waitForAll(futures).get();
    log.info("Start reading from {} topics", arguments.numTopics);
    long oldTime = System.nanoTime();
    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            break;
        }
        long now = System.nanoTime();
        double elapsed = (now - oldTime) / 1e9;
        double rate = messagesReceived.sumThenReset() / elapsed;
        double throughput = bytesReceived.sumThenReset() / elapsed * 8 / 1024 / 1024;
        log.info("Read throughput: {}  msg/s -- {} Mbit/s", dec.format(rate), dec.format(throughput));
        oldTime = now;
    }
    pulsarClient.close();
}
Also used : LongAdder(java.util.concurrent.atomic.LongAdder) TopicName(org.apache.pulsar.common.naming.TopicName) ParameterException(com.beust.jcommander.ParameterException) Parameter(com.beust.jcommander.Parameter) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) RateLimiter(com.google.common.util.concurrent.RateLimiter) ReaderListener(org.apache.pulsar.client.api.ReaderListener) Lists(com.google.common.collect.Lists) PulsarClient(org.apache.pulsar.client.api.PulsarClient) Properties(java.util.Properties) Logger(org.slf4j.Logger) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) DecimalFormat(java.text.DecimalFormat) JCommander(com.beust.jcommander.JCommander) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Reader(org.apache.pulsar.client.api.Reader) FileInputStream(java.io.FileInputStream) TimeUnit(java.util.concurrent.TimeUnit) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) List(java.util.List) FutureUtil(org.apache.pulsar.common.util.FutureUtil) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) MessageId(org.apache.pulsar.client.api.MessageId) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) ClientBuilder(org.apache.pulsar.client.api.ClientBuilder) ReaderBuilder(org.apache.pulsar.client.api.ReaderBuilder) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) RateLimiter(com.google.common.util.concurrent.RateLimiter) TopicName(org.apache.pulsar.common.naming.TopicName) CompletableFuture(java.util.concurrent.CompletableFuture) JCommander(com.beust.jcommander.JCommander) ParameterException(com.beust.jcommander.ParameterException) PulsarClient(org.apache.pulsar.client.api.PulsarClient) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ClientBuilder(org.apache.pulsar.client.api.ClientBuilder) MessageId(org.apache.pulsar.client.api.MessageId)

Example 37 with ObjectWriter

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter in project azure-gradle-plugins by lenala.

the class PackageTask method packageFunction.

@TaskAction
void packageFunction() {
    try {
        final AnnotationHandler handler = getAnnotationHandler();
        final Set<Method> methods = findAnnotatedMethods(handler);
        final Map<String, FunctionConfiguration> configMap = getFunctionConfigurations(handler, methods);
        validateFunctionConfigurations(configMap);
        final ObjectWriter objectWriter = getObjectWriter();
        writeEmptyHostJsonFile(objectWriter);
        copyLocalSettingsJson();
        writeFunctionJsonFiles(objectWriter, configMap);
        copyJarsToStageDirectory();
        getLogger().quiet(BUILD_SUCCESS);
    } catch (Exception ex) {
        throw new TaskExecutionException(this, ex);
    }
}
Also used : TaskExecutionException(org.gradle.api.tasks.TaskExecutionException) FunctionConfiguration(com.microsoft.azure.gradle.functions.configuration.FunctionConfiguration) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) AnnotationHandler(com.microsoft.azure.gradle.functions.handlers.AnnotationHandler) Method(java.lang.reflect.Method) TaskExecutionException(org.gradle.api.tasks.TaskExecutionException) IOException(java.io.IOException) TaskAction(org.gradle.api.tasks.TaskAction)

Example 38 with ObjectWriter

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

the class GenerateMetadataMojo method saveExtensionMetaData.

protected void saveExtensionMetaData(Extension jsonObject) throws MojoExecutionException {
    File targetFile = new File(metadataDestination);
    if (!targetFile.getParentFile().exists() && !targetFile.getParentFile().mkdirs()) {
        throw new MojoExecutionException("Cannot create directory " + targetFile.getParentFile());
    }
    try {
        JsonNode tree = ExtensionConverter.getDefault().toPublicExtension(jsonObject);
        ObjectWriter writer = Json.writer();
        writer.with(writer.getConfig().getDefaultPrettyPrinter()).writeValue(targetFile, tree);
        getLog().info("Created file " + targetFile.getAbsolutePath());
    } catch (IOException e) {
        throw new MojoExecutionException("Cannot write to file: " + metadataDestination, e);
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) File(java.io.File)

Example 39 with ObjectWriter

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

the class SqlMetadataAdapterTest method adaptForSqlStoredTest.

@Test
public void adaptForSqlStoredTest() throws IOException, JSONException {
    CamelContext camelContext = new DefaultCamelContext();
    SqlStoredConnectorMetaDataExtension ext = new SqlStoredConnectorMetaDataExtension(camelContext);
    Map<String, Object> parameters = new HashMap<>();
    for (final String name : properties.stringPropertyNames()) {
        parameters.put(name.substring(name.indexOf(".") + 1), properties.getProperty(name));
    }
    Optional<MetaData> metadata = ext.meta(parameters);
    SqlMetadataRetrieval adapter = new SqlMetadataRetrieval();
    SyndesisMetadata syndesisMetaData = adapter.adapt(camelContext, "sql", "sql-stored-connector", parameters, metadata.get());
    String expectedListOfProcedures = IOUtils.toString(this.getClass().getResource("/sql/stored_procedure_list.json"), StandardCharsets.UTF_8).trim();
    ObjectWriter writer = Json.writer();
    String actualListOfProcedures = writer.with(writer.getConfig().getDefaultPrettyPrinter()).writeValueAsString(syndesisMetaData);
    assertEquals(expectedListOfProcedures, actualListOfProcedures, JSONCompareMode.STRICT);
    parameters.put(SqlMetadataRetrieval.PATTERN, SqlMetadataRetrieval.FROM_PATTERN);
    String expectedListOfStartProcedures = IOUtils.toString(this.getClass().getResource("/sql/stored_procedure_list.json"), StandardCharsets.UTF_8).trim();
    String actualListOfStartProcedures = writer.with(writer.getConfig().getDefaultPrettyPrinter()).writeValueAsString(syndesisMetaData);
    assertEquals(expectedListOfStartProcedures, actualListOfStartProcedures, JSONCompareMode.STRICT);
    parameters.put("procedureName", "DEMO_ADD");
    SyndesisMetadata syndesisMetaData2 = adapter.adapt(camelContext, "sql", "sql-stored-connector", parameters, metadata.get());
    String expectedMetadata = IOUtils.toString(this.getClass().getResource("/sql/demo_add_metadata.json"), StandardCharsets.UTF_8).trim();
    String actualMetadata = writer.with(writer.getConfig().getDefaultPrettyPrinter()).writeValueAsString(syndesisMetaData2);
    assertEquals(expectedMetadata, actualMetadata, JSONCompareMode.STRICT);
}
Also used : DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) CamelContext(org.apache.camel.CamelContext) SyndesisMetadata(io.syndesis.connector.support.verifier.api.SyndesisMetadata) SqlStoredConnectorMetaDataExtension(io.syndesis.connector.sql.stored.SqlStoredConnectorMetaDataExtension) HashMap(java.util.HashMap) MetaData(org.apache.camel.component.extension.MetaDataExtension.MetaData) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) Test(org.junit.Test)

Example 40 with ObjectWriter

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

the class ExtensionSerializationTest method testSerializeDeserialize.

@Test
public void testSerializeDeserialize() throws IOException {
    final ObjectReader reader = Json.reader();
    final ObjectWriter writer = Json.writer();
    try (InputStream source = getClass().getResourceAsStream("syndesis-extension-definition.json")) {
        try {
            reader.forType(Extension.class).readValue(writer.writeValueAsString(new Extension.Builder().createFrom(reader.forType(Extension.class).readValue(source)).build()));
        } catch (IOException e) {
            fail("Should not throw an exception");
        }
    }
}
Also used : InputStream(java.io.InputStream) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) IOException(java.io.IOException) Test(org.junit.Test)

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