Java Code Examples for io.dropwizard.jackson.Jackson#newObjectMapper()

The following examples show how to use io.dropwizard.jackson.Jackson#newObjectMapper() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DatadogMetricFilterTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
private ScheduledReporter createReporter(String json)
        throws Exception {
    ObjectMapper objectMapper = Jackson.newObjectMapper();
    ReporterFactory reporterFactory = objectMapper.readValue(json, ReporterFactory.class);

    assertTrue(reporterFactory instanceof DatadogExpansionFilteredReporterFactory);
    DatadogExpansionFilteredReporterFactory datadogReporterFactory = (DatadogExpansionFilteredReporterFactory) reporterFactory;

    // Replace the transport with our own mock for testing

    Transport transport = mock(Transport.class);
    when(transport.prepare()).thenReturn(_request);

    AbstractTransportFactory transportFactory = mock(AbstractTransportFactory.class);
    when(transportFactory.build()).thenReturn(transport);

    datadogReporterFactory.setTransport(transportFactory);

    // Build the reporter
    return datadogReporterFactory.build(_metricRegistry);
}
 
Example 2
Source File: MacroBaseConfTest.java    From macrobase with Apache License 2.0 6 votes vote down vote up
@Test
public void testParsing() throws Exception {
    ConfigurationFactory<MacroBaseConf> cfFactory = new YamlConfigurationFactory<>(MacroBaseConf.class,
                                                                               null,
                                                                               Jackson.newObjectMapper(),
                                                                               "");
    MacroBaseConf conf = cfFactory.build(new File("src/test/resources/conf/simple.yaml"));


    assertEquals((Double) 0.1, conf.getDouble("this.is.a.double"));
    assertEquals((Integer) 100, conf.getInt("this.is.an.integer"));
    assertEquals((Long) 10000000000000L, conf.getLong("this.is.a.long"));
    assertEquals("Test", conf.getString("this.is.a.string"));

    List<String> stringList = Lists.newArrayList("T1", "T2", "T3", "T4");
    assertArrayEquals(stringList.toArray(), conf.getStringList("this.is.a.stringList").toArray());
    assertArrayEquals(stringList.toArray(), conf.getStringList("this.is.a.stringList.without.spaces").toArray());
    assertArrayEquals(stringList.toArray(), conf.getStringList("this.is.a.stringList.with.mixed.spaces").toArray());
}
 
Example 3
Source File: AthenaAuditWriterTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
private AthenaAuditWriter createWriter(String s3Path, String prefix, long maxFileSize, Duration maxBatchTime) {

        _auditService = mock(ScheduledExecutorService.class);
        _fileTransferService = mock(ExecutorService.class);

        AthenaAuditWriter writer = new AthenaAuditWriter(_s3, BUCKET, s3Path, maxFileSize,
                maxBatchTime, _tempStagingDir, prefix, Jackson.newObjectMapper(), _clock, true,
                log -> mock(RateLimitedLog.class), mock(MetricRegistry.class), _auditService, _fileTransferService);

        // On start two services should have been submitted: one to poll the audit queue and one to close log files and
        // initiate transfers.  Capture them now.

        ArgumentCaptor<Runnable> processQueuedAudits = ArgumentCaptor.forClass(Runnable.class);
        verify(_auditService).scheduleWithFixedDelay(processQueuedAudits.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS));
        _processQueuedAudits = processQueuedAudits.getValue();

        ArgumentCaptor<Runnable> doLogFileMaintenance = ArgumentCaptor.forClass(Runnable.class);
        verify(_auditService).scheduleAtFixedRate(
                doLogFileMaintenance.capture(),
                longThat(new LessThan<>(maxBatchTime.toMillis()+1)),
                eq(maxBatchTime.toMillis()), eq(TimeUnit.MILLISECONDS));
        _doLogFileMaintenance = doLogFileMaintenance.getValue();

        return writer;
    }
 
Example 4
Source File: SecretRetrievalCursor.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Nullable public static String toString(@Nullable SecretRetrievalCursor cursor)
    throws JsonProcessingException {
  if (cursor == null) {
    return null;
  }
  ObjectMapper mapper = Jackson.newObjectMapper();
  return mapper.writeValueAsString(cursor);
}
 
Example 5
Source File: ClientExample.java    From alchemy with MIT License 5 votes vote down vote up
private static AlchemyClient buildClient(String configurationFile) throws Exception {
    final Validator validator = BaseValidator.newValidator();
    final ObjectMapper mapper = Jackson.newObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    final ConfigurationFactory<AlchemyClientConfiguration> configurationFactory =
        new DefaultConfigurationFactoryFactory<AlchemyClientConfiguration>().create(
            AlchemyClientConfiguration.class,
            validator,
            mapper,
            "");

    return new AlchemyClient(
        configurationFactory.build(new File(configurationFile))
    );
}
 
Example 6
Source File: CloudWatchReporterFactoryTest.java    From dropwizard-metrics-cloudwatch with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyConfigurable() throws Exception {
    ObjectMapper mapper = Jackson.newObjectMapper();

    // dropwizard 0.9.1 changed the validation wiring a bit..
    Class<ValidatedValueUnwrapper> optValidatorClazz = (Class<ValidatedValueUnwrapper>) Class
            .forName("io.dropwizard.validation.valuehandling.OptionalValidatedValueUnwrapper");

    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    if (optValidatorClazz != null) {
        validator = Validation.byProvider(HibernateValidator.class).configure()
                .addValidatedValueHandler(optValidatorClazz.newInstance())
                .buildValidatorFactory().getValidator();
    }

    ConfigurationFactory<CloudWatchReporterFactory> configFactory =
            new ConfigurationFactory<>(CloudWatchReporterFactory.class,
                    validator, mapper, "dw");
    CloudWatchReporterFactory f = configFactory.build(new File(Resources.getResource("cw.yml").getFile()));

    assertEquals("[env=default]", f.getGlobalDimensions().toString());
    assertEquals("us-east-1", f.getAwsRegion());
    assertEquals("a.b", f.getNamespace());
    assertEquals("XXXXX", f.getAwsSecretKey());
    assertEquals("11111", f.getAwsAccessKeyId());
    assertEquals("p.neustar.biz", f.getAwsClientConfiguration().getProxyHost());
    assertNull(f.getAwsClientConfiguration().getProxyUsername());
}
 
Example 7
Source File: HK2LinkerTest.java    From dropwizard-guicier with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    ObjectMapper objectMapper = Jackson.newObjectMapper();
    Environment environment = new Environment("test env", objectMapper, null, new MetricRegistry(), null);
    GuiceBundle guiceBundle = GuiceBundle.defaultBuilder(Configuration.class)
        .modules(new TestModule())
        .build();
    Bootstrap bootstrap = mock(Bootstrap.class);
    when(bootstrap.getObjectMapper()).thenReturn(objectMapper);
    guiceBundle.initialize(bootstrap);
    guiceBundle.run(new Configuration(), environment);

    injector = guiceBundle.getInjector();
    serviceLocator = injector.getInstance(ServiceLocator.class);
}
 
Example 8
Source File: AlchemyClient.java    From alchemy with MIT License 5 votes vote down vote up
/**
 * Constructs a client with reasonable multi-threading defaults
 */
public AlchemyClient(AlchemyClientConfiguration configuration) {
    final ObjectMapper mapper = Jackson.newObjectMapper();
    final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    this.client = clientBuilder
        .using(executorService, mapper)
        .using(configuration)
        .build(CLIENT_NAME);
    this.configuration = configuration;
    configureObjectMapper(configuration, mapper);
}
 
Example 9
Source File: AssetsBundleTest.java    From dropwizard-configurable-assets-bundle with Apache License 2.0 5 votes vote down vote up
@Test
public void deserialzeAssetsConfiguration() throws IOException {
  ObjectMapper mapper = Jackson.newObjectMapper(new YAMLFactory());
  FileInputStream inputStream = new FileInputStream("src/test/resources/assets/config.yml");
  AssetsConfiguration assets = mapper.readValue(inputStream, AssetsConfiguration.class);
  assertEquals(assets.getCacheSpec(), "abc");
  assertEquals(assets.getResourcePathToUriMappings(), ImmutableMap.of("/assets/","/dashboard/"));
  assertEquals(assets.getMimeTypes(), ImmutableMap.of("woff", "application/font-woff"));
  assertEquals(assets.getOverrides(), ImmutableMap.of("/","../example-app/build/src"));
  assertNull(assets.getCacheControlHeader());
}
 
Example 10
Source File: CliModule.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Provides public ObjectMapper generalMapper() {
  /**
   * Customizes ObjectMapper for common settings.
   *
   * @param objectMapper to be customized
   * @return customized input factory
   */
  ObjectMapper objectMapper = Jackson.newObjectMapper();
  objectMapper.registerModule(new Jdk8Module());
  objectMapper.registerModules(new JavaTimeModule());
  objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  return objectMapper;
}
 
Example 11
Source File: SparseFieldSetFilterTest.java    From alchemy with MIT License 5 votes vote down vote up
@Before
public void setUp() {
    request = mock(ContainerRequestContext.class);
    response = mock(ContainerResponseContext.class);
    mapper = Jackson.newObjectMapper();
    filter = new SparseFieldSetFilter(mapper);
}
 
Example 12
Source File: SecretRetrievalCursor.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Nullable public static String toUrlEncodedString(@Nullable SecretRetrievalCursor cursor)
    throws JsonProcessingException {
  if (cursor == null) {
    return null;
  }
  ObjectMapper mapper = Jackson.newObjectMapper();
  // URL-encode the JSON value
  return URLEncoder.encode(mapper.writeValueAsString(cursor), UTF_8);
}
 
Example 13
Source File: SecretRetrievalCursor.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Nullable public static SecretRetrievalCursor fromUrlEncodedString(@Nullable String encodedJson) {
  if (encodedJson == null) {
    return null;
  }
  String jsonDecoded = URLDecoder.decode(encodedJson, UTF_8);
  ObjectMapper mapper = Jackson.newObjectMapper();
  try {
    return mapper.readValue(jsonDecoded, SecretRetrievalCursor.class);
  } catch (Exception e) {
    return null;
  }
}
 
Example 14
Source File: UpgradeCommand.java    From irontest with Apache License 2.0 5 votes vote down vote up
private IronTestConfiguration getIronTestConfiguration(String ironTestHome) throws IOException, ConfigurationException {
    Path configYmlFilePath = Paths.get(ironTestHome, "config.yml");
    ObjectMapper objectMapper = Jackson.newObjectMapper();
    Validator validator = Validators.newValidator();
    YamlConfigurationFactory<IronTestConfiguration> factory =
            new YamlConfigurationFactory<>(IronTestConfiguration.class, validator, objectMapper, "dw");
    IronTestConfiguration configuration = factory.build(configYmlFilePath.toFile());
    return configuration;
}
 
Example 15
Source File: ServiceMain.java    From helios with Apache License 2.0 5 votes vote down vote up
protected static Environment createEnvironment(final String name) {
  final Validator validator = Validation
      .byProvider(HibernateValidator.class)
      .configure()
      .addValidatedValueHandler(new OptionalValidatedValueUnwrapper())
      .buildValidatorFactory()
      .getValidator();
  return new Environment(name,
      Jackson.newObjectMapper(),
      validator,
      new MetricRegistry(),
      Thread.currentThread().getContextClassLoader());
}
 
Example 16
Source File: UpdateActionTest.java    From keywhiz with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
  updateActionConfig = new UpdateActionConfig();
  updateAction = new UpdateAction(updateActionConfig, keywhizClient, Jackson.newObjectMapper());
}
 
Example 17
Source File: AddActionTest.java    From keywhiz with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
  addActionConfig = new AddActionConfig();
  addAction = new AddAction(addActionConfig, keywhizClient, Jackson.newObjectMapper());
}
 
Example 18
Source File: SlowQueryLogTest.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Test
public void testSlowQueryLog() throws Exception {
    File logFile = File.createTempFile("slow-query", ".log");
    try {
        ObjectMapper objectMapper = Jackson.newObjectMapper();
        SlowQueryLogConfiguration config = objectMapper.readValue(
                "{" +
                    "\"tooManyDeltasThreshold\": 20," +
                    "\"file\": {" +
                        "\"type\": \"file\"," +
                        "\"currentLogFilename\": \"" + logFile.getAbsolutePath() + "\"," +
                        "\"archive\": false" +
                    "}" +
                "}",
                SlowQueryLogConfiguration.class);

        SlowQueryLog log = new LogbackSlowQueryLogProvider(config, new MetricRegistry()).get();

        Expanded expanded = mock(Expanded.class);
        when(expanded.getNumPersistentDeltas()).thenReturn(100);
        when(expanded.getNumDeletedDeltas()).thenReturn(2L);

        log.log("test:table", "test-key", expanded);

        // Logging is asynchronous; allow up to 10 seconds for the message to be logged
        Stopwatch stopwatch = Stopwatch.createStarted();
        while (logFile.length() == 0 && stopwatch.elapsed(TimeUnit.SECONDS) < 10) {
            Thread.sleep(100);
        }

        String line = Files.readFirstLine(logFile, Charsets.UTF_8);
        assertNotNull(line);
        assertTrue(line.endsWith("Too many deltas: 100 2 test:table test-key"));
    } finally {
        //noinspection ResultOfMethodCallIgnored
        logFile.delete();

        // Reset everything so future tests that use slow query logging don't log to the file
        new LogbackSlowQueryLogProvider(new SlowQueryLogConfiguration(), new MetricRegistry()).get();
    }
}
 
Example 19
Source File: QueueStressTest.java    From emodb with Apache License 2.0 4 votes vote down vote up
public static void main(String... args) throws Exception {
    final String DROPWIZARD_PROPERTY_PREFIX = "dw";

    // Load the config.yaml file specified as the first argument.
    ConfigurationFactory<EmoConfiguration> configFactory = new ConfigurationFactory(
            EmoConfiguration.class, Validation.buildDefaultValidatorFactory().getValidator(), Jackson.newObjectMapper(), DROPWIZARD_PROPERTY_PREFIX);
    EmoConfiguration configuration = configFactory.build(new File(args[0]));
    int numWriterThreads = Integer.parseInt(args[1]);
    int numReaderThreads = Integer.parseInt(args[2]);
    String adminApiKey = configuration.getAuthorizationConfiguration().getAdminApiKey();

    MetricRegistry metricRegistry = new MetricRegistry();
    new LoggingFactory().configure(metricRegistry, "stress");

    CuratorFramework curator = configuration.getZooKeeperConfiguration().newCurator();
    curator.start();

    QueueClientFactory queueFactory = QueueClientFactory.forClusterAndHttpConfiguration(
            configuration.getCluster(), configuration.getHttpClientConfiguration(), metricRegistry);
    AuthQueueService authQueueService = ServicePoolBuilder.create(AuthQueueService.class)
            .withServiceFactory(queueFactory)
            .withHostDiscovery(new ZooKeeperHostDiscovery(curator, queueFactory.getServiceName(), metricRegistry))
            .withMetricRegistry(metricRegistry)
            .withCachingPolicy(ServiceCachingPolicyBuilder.getMultiThreadedClientPolicy())
            .buildProxy(new ExponentialBackoffRetry(5, 50, 1000, TimeUnit.MILLISECONDS));
    QueueService queueService = QueueServiceAuthenticator.proxied(authQueueService)
            .usingCredentials(adminApiKey);

    final QueueStressTest stressTest = new QueueStressTest(queueService);

    ThreadFactory writerFactory = new ThreadFactoryBuilder().setNameFormat("Writer-%d").build();
    for (int i = 0; i < numWriterThreads; i++) {
        writerFactory.newThread(new Runnable() {
            @Override
            public void run() {
                stressTest.write();
            }
        }).start();
    }

    ThreadFactory readerFactory = new ThreadFactoryBuilder().setNameFormat("Reader-%d").build();
    for (int i = 0; i < numReaderThreads; i++) {
        readerFactory.newThread(new Runnable() {
            @Override
            public void run() {
                stressTest.read();
            }
        }).start();
    }

    ThreadFactory reportFactory = new ThreadFactoryBuilder().setNameFormat("Report-%d").build();
    Executors.newScheduledThreadPool(1, reportFactory).scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            stressTest.report();
        }
    }, 1, 1, TimeUnit.SECONDS);

    // Run forever
}
 
Example 20
Source File: ScanUploadTest.java    From emodb with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {
    ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    // Load the config.yaml file specified as the first argument.
    ConfigurationFactory<EmoConfiguration> configFactory = new ConfigurationFactory<>(
            EmoConfiguration.class, validatorFactory.getValidator(), Jackson.newObjectMapper(),
            "dw");
    File configFile = new File(args[0]);
    EmoConfiguration configuration = configFactory.build(configFile);
    String ddlFilePath = args[1];
    File scanUploadDir = new File(args[2]);

    checkArgument(scanUploadDir.isDirectory(), "Not a valid directory: %s", scanUploadDir);
    checkArgument(configuration.getServiceMode() == EmoServiceMode.SCANNER,
            "Not configured for scanner: %s", configuration.getServiceMode());

    // To prevent conflicting with EmoDB running on this same server adjust the host and admin ports.
    updatePortsToAvoidCollision(configuration.getServerFactory());

    HostAndPort hostAndPort = new SelfHostAndPortModule().provideSelfHostAndPort(configuration.getServerFactory());
    MetricRegistry metricRegistry = new MetricRegistry();
    configuration.getLoggingFactory().configure(metricRegistry, "scan");

    DataStore dataStore = null;

    try (CuratorFramework curator = configuration.getZooKeeperConfiguration().newCurator()) {
        curator.start();

        DataStoreClientFactory dataStoreFactory = DataStoreClientFactory.forClusterAndHttpConfiguration(
                configuration.getCluster(), configuration.getHttpClientConfiguration(), metricRegistry);
        dataStore = ServicePoolBuilder.create(DataStore.class)
                .withServiceFactory(dataStoreFactory.usingCredentials(configuration.getScanner().get().getScannerApiKey().get()))
                .withHostDiscovery(new ZooKeeperHostDiscovery(curator, dataStoreFactory.getServiceName(), metricRegistry))
                .withCachingPolicy(ServiceCachingPolicyBuilder.getMultiThreadedClientPolicy())
                .withMetricRegistry(metricRegistry)
                .buildProxy(new ExponentialBackoffRetry(5, 50, 1000, TimeUnit.MILLISECONDS));

        ScanUploadTest test = new ScanUploadTest(dataStore);
        test.createAndPopulateTestTables();
        test.scanToDirectory(configuration, ddlFilePath, configFile, scanUploadDir, hostAndPort, validatorFactory, metricRegistry);
        test.validateScanResults(scanUploadDir);
    } finally {
        if (dataStore != null) {
            ServicePoolProxies.close(dataStore);
        }
    }
}