@Test public void testSerialization() throws IOException { final String json = "{" + "\"type\": \"tcp\"," + "\"host\": \"i am a host\"," + "\"port\": \"12345\"," + "\"timeout\": \"5 minutes\"" + "}"; final ObjectMapper mapper = Jackson.newObjectMapper(); mapper.registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES)); final Environment env = mock(Environment.class); when(env.getObjectMapper()).thenReturn(mapper); final InfluxDbTcpWriter.Factory factory = mapper.readValue(json, InfluxDbTcpWriter.Factory.class); assertEquals("expected TCP host", "i am a host", factory.host()); assertEquals("expected TCP port", 12345, factory.port()); assertEquals("expected TCP timeout", Duration.minutes(5), factory.timeout()); }
@Test public void testGetAuthFilters() throws Exception { final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class, Validators.newValidator(), Jackson.newObjectMapper(), "") .build(new File(getClass().getResource("/config1.yml").toURI())); final Optional<List<AuthFilter>> filters = TrellisUtils.getAuthFilters(config); assertTrue(filters.isPresent()); filters.ifPresent(f -> assertEquals(3L, f.size())); config.getAuth().getAnon().setEnabled(false); config.getAuth().getBasic().setEnabled(false); config.getAuth().getJwt().setEnabled(false); assertFalse(TrellisUtils.getAuthFilters(config).isPresent()); }
@Test public void testConfigurationAuth1() throws Exception { final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class, Validators.newValidator(), Jackson.newObjectMapper(), "") .build(new File(getClass().getResource("/config1.yml").toURI())); assertTrue(config.getAuth().getWebac().getEnabled()); assertEquals((Long) 100L, config.getAuth().getWebac().getCacheSize()); assertEquals((Long) 10L, config.getAuth().getWebac().getCacheExpireSeconds()); assertTrue(config.getAuth().getAnon().getEnabled()); assertTrue(config.getAuth().getBasic().getEnabled()); assertEquals("users.auth", config.getAuth().getBasic().getUsersFile()); assertTrue(config.getAuth().getJwt().getEnabled()); assertEquals("secret", config.getAuth().getJwt().getKey()); assertFalse(config.getAuth().getJwt().getBase64Encoded()); }
@Test public void testSingularityTaskIdSerialization() throws Exception { ObjectMapper om = Jackson.newObjectMapper() .setSerializationInclusion(Include.NON_NULL) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .registerModule(new ProtobufModule()); SingularityTaskId taskId = new SingularityTaskId("rid", "did", 100, 1, "host", "rack"); String id = taskId.getId(); SingularityTaskId fromId = SingularityTaskId.valueOf(id); SingularityTaskId fromJson = om.readValue(om.writeValueAsBytes(taskId), SingularityTaskId.class); assertEquals(taskId, fromId); assertEquals(taskId, fromJson); assertEquals(fromId, fromJson); }
@Override public RestlerConfig getConfiguration() { ObjectMapper objectMapper = Jackson.newObjectMapper(); ValidatorFactory validatorFactory = Validation .byProvider(HibernateValidator.class) .configure() .addValidatedValueHandler(new OptionalValidatedValueUnwrapper()) .buildValidatorFactory(); final ConfigurationFactory<RestlerConfig> configurationFactory = new DefaultConfigurationFactoryFactory<RestlerConfig>().create(RestlerConfig.class, validatorFactory.getValidator(), objectMapper, "dw"); try { return configurationFactory.build(new FileConfigurationSourceProvider(), TEST_CONFIG_FILE); } catch (Exception e) { throw new RuntimeException("Cannot get test configuration", e); } }
@Test public void getRecordByKey() throws JSONException, IOException { Response response = register.getRequest(address, "/record/6789.json"); assertThat(response.getStatus(), equalTo(200)); assertThat(response.getHeaderString("Link"), equalTo("</record/6789/entries>; rel=\"version-history\"")); JsonNode res = Jackson.newObjectMapper().readValue(response.readEntity(String.class), JsonNode.class).get("6789"); assertThat(res.get("entry-number").textValue(), equalTo("2")); assertThat(res.get("key").textValue(), equalTo("6789")); assertTrue(res.get("entry-timestamp").textValue().matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$")); ArrayNode items = (ArrayNode)res.get("item"); assertThat(items.size(), is(1)); JsonNode itemMap = items.get(0); assertThat(itemMap.get("street").asText(), is("presley")); assertThat(itemMap.get("address").asText(), is("6789")); }
@Test public void getRecords() throws IOException { Response response = register.getRequest(address, "/records.json"); assertThat(response.getStatus(), equalTo(200)); JsonNode res = Jackson.newObjectMapper().readValue(response.readEntity(String.class), JsonNode.class); JsonNode firstRecord = res.get("145678"); assertThat(firstRecord.get("entry-number").textValue(), equalTo("3")); assertThat(firstRecord.get("index-entry-number").textValue(), equalTo("3")); assertTrue(firstRecord.get("entry-timestamp").textValue().matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$")); assertThat(firstRecord.get("item").size(), equalTo(1)); JsonNode secondRecord = res.get("6789"); assertThat(secondRecord.get("entry-number").textValue(), equalTo("2")); assertThat(secondRecord.get("index-entry-number").textValue(), equalTo("2")); assertTrue(secondRecord.get("entry-timestamp").textValue().matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$")); assertThat(secondRecord.get("item").size(), equalTo(1)); }
@Test public void historyResource_returnsHistoryOfARecord() throws IOException { Response response = register.getRequest(address, "/record/6789/entries.json"); assertThat(response.getStatus(), equalTo(200)); JsonNode res = Jackson.newObjectMapper().readValue(response.readEntity(String.class), JsonNode.class); assertThat(res.isArray(), equalTo(true)); JsonNode firstEntry = res.get(0); assertThat(firstEntry.get("index-entry-number").textValue(), equalTo("1")); assertThat(firstEntry.get("entry-number").textValue(), equalTo("1")); assertThat(firstEntry.get("item-hash").get(0).textValue(), equalTo("sha-256:9432331d3343a7ceaaee46308069d01836460294c672223b236727a790acf786" )); assertTrue(firstEntry.get("entry-timestamp").textValue().matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$")); JsonNode secondEntry = res.get(1); assertThat(secondEntry.get("index-entry-number").textValue(), equalTo("2")); assertThat(secondEntry.get("entry-number").textValue(), equalTo("2")); assertThat(secondEntry.get("item-hash").get(0).textValue(), equalTo("sha-256:bd239db51960376826b937a615f0f3397485f00611d35bb7e951e357bf73b934" )); assertTrue(secondEntry.get("entry-timestamp").textValue().matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$")); }
private RecordsView getRecordsView() throws IOException, JSONException { final ObjectMapper objectMapper = Jackson.newObjectMapper(); final Instant t1 = Instant.parse("2016-03-29T08:59:25Z"); final Instant t2 = Instant.parse("2016-03-28T09:49:26Z"); final Entry entry1 = new Entry(1, new HashValue(HashingAlgorithm.SHA256, "ab"), t1, "123", EntryType.user); final Entry entry2 = new Entry(2, new HashValue(HashingAlgorithm.SHA256, "cd"), t2, "456", EntryType.user); final Item item1 = new Item(new HashValue(HashingAlgorithm.SHA256, "ab"), objectMapper.readTree("{\"address\":\"123\",\"street\":\"foo\"}")); final Item item2 = new Item(new HashValue(HashingAlgorithm.SHA256, "cd"), objectMapper.readTree("{\"address\":\"456\",\"street\":\"bar\"}")); final Record record1 = new Record(entry1, Collections.singletonList(item1)); final Record record2 = new Record(entry2, Collections.singletonList(item2)); final ItemConverter itemConverter = mock(ItemConverter.class); final Map<String, Field> fieldsByName = mock(Map.class); when(itemConverter.convertItem(item1, fieldsByName)).thenReturn(ImmutableMap.of("address", new StringValue("123"), "street", new StringValue("foo"))); when(itemConverter.convertItem(item2, fieldsByName)).thenReturn(ImmutableMap.of("address", new StringValue("456"), "street", new StringValue("bar"))); return new RecordsView(Arrays.asList(record1, record2), fieldsByName, itemConverter, false, false); }
@Before public void beforeAll() throws Exception { server = new TestingServer(); server.start(); Capabilities mockCapabilities = Mockito.mock(Capabilities.class); when(mockCapabilities.supportsNamedVips()).thenReturn(true); taskFactory = new CassandraDaemonTask.Factory(mockCapabilities); configurationFactory = new ConfigurationFactory<>( MutableSchedulerConfiguration.class, BaseValidator.newValidator(), Jackson.newObjectMapper() .registerModule(new GuavaModule()) .registerModule(new Jdk8Module()), "dw"); connectString = server.getConnectString(); }
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); }
@Test public void testJsonSerializeNoDeserialization() throws Exception { LazyJsonMap map = new LazyJsonMap("{\"k1\":\"v1\",\"k2\":\"v2\"}"); map.put("k2", "v22"); map.put("k3", "v3"); ObjectMapper objectMapper = Jackson.newObjectMapper(); objectMapper.registerModule(new LazyJsonModule()); // Write to JSON, then read back String asJson = objectMapper.writeValueAsString(map); Map<String, Object> actual = objectMapper.readValue(asJson, new TypeReference<Map<String, Object>>() {}); Map<String, Object> expected = ImmutableMap.of("k1", "v1", "k2", "v22", "k3", "v3"); assertEquals(actual, expected); // Serialization should not have forced deserialize assertFalse(map.isDeserialized()); }
@Test public void testJsonSerializeAfterDeserialization() throws Exception { LazyJsonMap map = new LazyJsonMap("{\"k1\":\"v1\",\"k2\":\"v2\"}"); map.put("k2", "v22"); map.put("k3", "v3"); // Perform a size call which should force the map to deserialize map.size(); assertTrue(map.isDeserialized()); ObjectMapper objectMapper = Jackson.newObjectMapper(); objectMapper.registerModule(new LazyJsonModule()); // Write to JSON, then read back String asJson = objectMapper.writeValueAsString(map); Map<String, Object> actual = objectMapper.readValue(asJson, new TypeReference<Map<String, Object>>() {}); Map<String, Object> expected = ImmutableMap.of("k1", "v1", "k2", "v22", "k3", "v3"); assertEquals(actual, expected); }
@Test public void should_make_a_copy_of_iterable_properties_without_empty_values() throws JsonProcessingException { ObjectMapper mapper = Jackson.newObjectMapper(); // Iterable properties IterableValorisation.IterableValorisationItem itemIterable2 = new IterableValorisation.IterableValorisationItem("blockOfProperties", Sets.newHashSet(new KeyValueValorisation("name3", "value"), new KeyValueValorisation("name0", ""))); IterableValorisation iterableValorisation2 = new IterableValorisation("iterable2", Lists.newArrayList(itemIterable2)); IterableValorisation.IterableValorisationItem item = new IterableValorisation.IterableValorisationItem("blockOfProperties", Sets.newHashSet(new KeyValueValorisation("name2", "value"), iterableValorisation2, new KeyValueValorisation("name3", "value3"))); IterableValorisation iterableValorisation = new IterableValorisation("iterable", Lists.newArrayList(item)); Properties properties = new Properties(Sets.newHashSet(), Sets.newHashSet(iterableValorisation)); Properties propertiesCleaned = properties.makeCopyWithoutNullOrEmptyValorisations(); IterableValorisation.IterableValorisationItem itemIterable2C = new IterableValorisation.IterableValorisationItem("blockOfProperties", Sets.newHashSet(new KeyValueValorisation("name3", "value"))); IterableValorisation iterableValorisation2C = new IterableValorisation("iterable2", Lists.newArrayList(itemIterable2C)); IterableValorisation.IterableValorisationItem itemC = new IterableValorisation.IterableValorisationItem("blockOfProperties", Sets.newHashSet(new KeyValueValorisation("name2", "value"), iterableValorisation2C, new KeyValueValorisation("name3", "value3"))); IterableValorisation iterableValorisationC = new IterableValorisation("iterable", Lists.newArrayList(itemC)); String propertiesCleanedJSON = mapper.writeValueAsString(propertiesCleaned); String expectedJSON = mapper.writeValueAsString(new Properties(Sets.newHashSet(), Sets.newHashSet(iterableValorisationC))); assertThat(propertiesCleanedJSON.equals(expectedJSON)).isTrue(); }
@Override public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { File yamlFile = new File(Resources.getResource("keywhiz-test.yaml").getFile()); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); ObjectMapper objectMapper = KeywhizService.customizeObjectMapper(Jackson.newObjectMapper()); KeywhizConfig config = new ConfigurationFactory<>(KeywhizConfig.class, validator, objectMapper, "dw") .build(yamlFile); DataSource dataSource = config.getDataSourceFactory() .build(new MetricRegistry(), "db-migrations"); Flyway flyway = new Flyway(); flyway.setDataSource(dataSource); flyway.setLocations(config.getMigrationsDir()); flyway.clean(); flyway.migrate(); DSLContext dslContext = DSLContexts.databaseAgnostic(dataSource); DbSeedCommand.doImport(dslContext); base.evaluate(); } }; }
@Test public void updateCallsUpdateForSecret() throws Exception { updateActionConfig.name = secret.getDisplayName(); updateActionConfig.expiry = "2006-01-02T15:04:05Z"; updateActionConfig.contentProvided = true; byte[] content = base64Decoder.decode(secret.getSecret()); updateAction.stream = new ByteArrayInputStream(content); when(keywhizClient.getSanitizedSecretByName(secret.getName())) .thenThrow(new NotFoundException()); // Call checks for existence. when(keywhizClient.updateSecret(secret.getName(), false, "", true, content, false, updateActionConfig.getMetadata(Jackson.newObjectMapper()), true, 1136214245)) .thenReturn(secretDetailResponse); updateAction.run(); verify(keywhizClient, times(1)).updateSecret(secret.getName(), false, "", true, content, false, updateActionConfig.getMetadata(Jackson.newObjectMapper()), true, 1136214245); }
@Test public void updateWithMetadata() throws Exception { updateActionConfig.name = secret.getDisplayName(); updateActionConfig.description = "metadata test"; updateActionConfig.json = "{\"owner\":\"example-name\", \"group\":\"example-group\"}"; updateActionConfig.contentProvided = true; byte[] content = base64Decoder.decode(secret.getSecret()); updateAction.stream = new ByteArrayInputStream(content); when(keywhizClient.getSanitizedSecretByName(secret.getName())) .thenThrow(new NotFoundException()); // Call checks for existence. when(keywhizClient.updateSecret(secret.getName(), true, "metadata test", true, content, true, updateActionConfig.getMetadata(Jackson.newObjectMapper()), false, 0)) .thenReturn(secretDetailResponse); updateAction.run(); verify(keywhizClient, times(1)).updateSecret(secret.getName(), true, "metadata test", true, content, true, updateActionConfig.getMetadata(Jackson.newObjectMapper()), false, 0); }
@Test public void updateWithContentPipedInButNoContentFlag() throws Exception { updateActionConfig.name = secret.getDisplayName(); updateActionConfig.description = "content test"; updateActionConfig.json = "{\"owner\":\"example-name\", \"group\":\"example-group\"}"; updateActionConfig.contentProvided = false; byte[] content = base64Decoder.decode(secret.getSecret()); updateAction.stream = new ByteArrayInputStream(content); when(keywhizClient.getSanitizedSecretByName(secret.getName())) .thenThrow(new NotFoundException()); // Call checks for existence. // If the content flag is not specified, the content should not be sent to Keywhiz when(keywhizClient.updateSecret(secret.getName(), true, "content test", false, new byte[]{}, true, updateActionConfig.getMetadata(Jackson.newObjectMapper()), false, 0)) .thenReturn(secretDetailResponse); updateAction.run(); // Content should not have been sent to Keywhiz, even though it was piped in (warning should also have been printed to stdout) verify(keywhizClient, times(1)).updateSecret(secret.getName(), true, "content test", false, new byte[]{}, true, updateActionConfig.getMetadata(Jackson.newObjectMapper()), false, 0); }
@Test public void testParsing() throws Exception { ConfigurationFactory<MacroBaseConf> cfFactory = new ConfigurationFactory<>(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()); }
/** * Builds a Configuration object from the file path given. It uses the {@link io.dropwizard.configuration.ConfigurationFactory} * to build the configuration. * * @param possibleFilename The path to the configuration. * @return A configuration object loaded form the filename given. */ private Config buildFromFile(String possibleFilename) { File configFile = new File(possibleFilename); Preconditions.checkArgument(configFile.exists(), "File must exist at: " + configFile.getAbsolutePath()); try { return new ConfigurationFactory<>( configClass, Validation.buildDefaultValidatorFactory().getValidator(), Jackson.newObjectMapper(), "graceland") .build(configFile); } catch (Exception e) { String msg = "Unknown exception triggered when attempting to build config from file:" + "\n" + "\t* Configuration Class: " + configClass.getCanonicalName() + "\n" + "\t* File: " + configFile.getAbsolutePath(); throw new RuntimeException(msg, e); } }
public static OregamiConfiguration createConfiguration(String configFilename) { ConfigurationFactory<OregamiConfiguration> factory = new ConfigurationFactory<>( OregamiConfiguration.class, Validation.buildDefaultValidatorFactory().getValidator(), Jackson.newObjectMapper(), "" ); OregamiConfiguration configuration; try { configuration = factory.build(new File(configFilename)); } catch (Exception e) { throw new RuntimeException(e); } System.out.println(ToStringBuilder.reflectionToString(configuration, ToStringStyle.MULTI_LINE_STYLE)); System.out.println(ToStringBuilder.reflectionToString(configuration.getDatabaseConfiguration(), ToStringStyle.MULTI_LINE_STYLE)); return configuration; }
@Test public void shouldNotTransformAuthenticationExceptionIntoMappedException() throws AuthenticationException { when(AuthenticatorApp.getMockAuthenticator().authenticate(any(BasicCredentials.class))).thenThrow(new AuthenticationException("test")); final Client client = new JerseyClientBuilder(new MetricRegistry()) .using(executorService, Jackson.newObjectMapper()) .build("dropwizard-app-rule"); client.register(HttpAuthenticationFeature.basicBuilder() .nonPreemptive() .credentials("user", "stuff") .build()); final Response response = client .target(URI.create("http://localhost:" + RULE.getLocalPort() + "/auth")) .request() .get(Response.class); assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); verify(AuthenticatorApp.getMockAuthenticator(), times(1)).authenticate(any(BasicCredentials.class)); verifyZeroInteractions(AuthenticatorApp.getTenacityContainerExceptionMapper()); verify(AuthenticatorApp.getTenacityExceptionMapper(), times(1)).toResponse(any(HystrixRuntimeException.class)); }
public RestClient (URI baseURI) { ObjectMapper mapper = Jackson.newObjectMapper () .registerModule (new SupernodeModule ()); Validator validator = Validation.buildDefaultValidatorFactory ().getValidator (); ClientConfig cc = new DefaultClientConfig (JsonProcessingExceptionMapper.class); cc.getProperties ().put (ClientConfig.PROPERTY_CONNECT_TIMEOUT, 5000); cc.getProperties ().put (ClientConfig.PROPERTY_READ_TIMEOUT, 5000); cc.getSingletons ().add (new JacksonMessageBodyProvider (mapper, validator)); Client client = Client.create (cc); client.addFilter (new LoggingFilter ()); this.client = client; this.baseURI = baseURI; }
@Test public void canDeserializeCorrectly() throws IOException, ConfigurationException { final HikariDataSourceFactory factory = new YamlConfigurationFactory<>(HikariDataSourceFactory.class, BaseValidator.newValidator(), Jackson.newObjectMapper(), "dw") .build(new ResourceConfigurationSourceProvider(), "config.yaml"); assertThat(factory.getUser()).isEqualTo("nick"); assertThat(factory.getPassword()).isEqualTo("nickss"); assertThat(factory.getDatasourceClassName()).isEqualTo("org.postgresql.ds.PGSimpleDataSource"); assertThat(factory.getProperties()).containsExactly(entry("databaseName", "postgres")); assertThat(factory.getMinSize()).isEqualTo(OptionalInt.empty()); assertThat(factory.getMaxSize()).isEqualTo(12); assertThat(factory.isAutoCommit()).isTrue(); }
@Test public void testGetAssetConfigurations() throws Exception { final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class, Validators.newValidator(), Jackson.newObjectMapper(), "") .build(new File(getClass().getResource("/config1.yml").toURI())); final Map<String, String> assets = TrellisUtils.getAssetConfiguration(config); assertEquals(3L, assets.size()); assertEquals("http://example.org/image.icon", assets.get("icon")); assertEquals("http://example.org/styles1.css,http://example.org/styles2.css", assets.get("css")); assertEquals("http://example.org/scripts1.js,http://example.org/scripts2.js", assets.get("js")); }
@Test public void testGetKafkaProperties() throws Exception { final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class, Validators.newValidator(), Jackson.newObjectMapper(), "") .build(new File(getClass().getResource("/config1.yml").toURI())); final Properties props = TrellisUtils.getKafkaProperties(config); assertEquals("org.apache.kafka.common.serialization.StringSerializer", props.getProperty("key.serializer")); assertEquals("org.apache.kafka.common.serialization.StringSerializer", props.getProperty("value.serializer")); assertEquals("localhost:9092", props.getProperty("bootstrap.servers")); }
@Test public void testGetCurator() throws Exception { final TestingServer zk = new TestingServer(true); final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class, Validators.newValidator(), Jackson.newObjectMapper(), "") .build(new File(getClass().getResource("/config1.yml").toURI())); config.getZookeeper().setEnsembleServers(zk.getConnectString()); final CuratorFramework curator = TrellisUtils.getCuratorClient(config); assertEquals(CuratorFrameworkState.STARTED, curator.getState()); }
@Test public void testConfigurationGeneral1() throws Exception { final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class, Validators.newValidator(), Jackson.newObjectMapper(), "") .build(new File(getClass().getResource("/config1.yml").toURI())); assertTrue(config.getAsync()); assertEquals("Trellis", config.getDefaultName()); assertEquals((Integer) 86400, config.getCacheMaxAge()); assertEquals((Long) 100L, config.getJsonLdCacheSize()); assertEquals((Long) 24L, config.getJsonLdCacheExpireHours()); assertTrue(config.getJsonLdDomainWhitelist().isEmpty()); assertTrue(config.getJsonLdWhitelist().contains("http://example.org/context.json")); }
@Test public void testConfigurationAssets1() throws Exception { final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class, Validators.newValidator(), Jackson.newObjectMapper(), "") .build(new File(getClass().getResource("/config1.yml").toURI())); assertEquals("http://example.org/image.icon", config.getAssets().getIcon()); assertTrue(config.getAssets().getJs().contains("http://example.org/scripts1.js")); assertTrue(config.getAssets().getCss().contains("http://example.org/styles1.css")); }
@Test public void testConfigurationLocations() throws Exception { final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class, Validators.newValidator(), Jackson.newObjectMapper(), "") .build(new File(getClass().getResource("/config1.yml").toURI())); assertEquals("/tmp/trellisData/binaries", config.getBinaries().getPath()); assertEquals("/tmp/trellisData/resources", config.getResources().getPath()); assertEquals("http://localhost:8080/", config.getBaseUrl()); assertEquals((Integer) 4, config.getBinaries().getLevels()); assertEquals((Integer) 2, config.getBinaries().getLength()); }
@Test public void testConfigurationNamespaces1() throws Exception { final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class, Validators.newValidator(), Jackson.newObjectMapper(), "") .build(new File(getClass().getResource("/config1.yml").toURI())); assertEquals("/tmp/trellisData/namespaces.json", config.getNamespaces().getFile()); }
@Test public void testConfigurationCORS1() throws Exception { final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class, Validators.newValidator(), Jackson.newObjectMapper(), "") .build(new File(getClass().getResource("/config1.yml").toURI())); assertTrue(config.getCors().getEnabled()); assertTrue(config.getCors().getAllowOrigin().contains("*")); assertTrue(config.getCors().getAllowHeaders().contains("Link")); assertTrue(config.getCors().getAllowMethods().contains("PATCH")); assertTrue(config.getCors().getExposeHeaders().contains("Location")); assertEquals((Integer) 180, config.getCors().getMaxAge()); assertTrue(config.getCors().getAllowCredentials()); }
@Test public void testConfigurationZookeeper1() throws Exception { final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class, Validators.newValidator(), Jackson.newObjectMapper(), "") .build(new File(getClass().getResource("/config1.yml").toURI())); assertEquals("localhost:2181", config.getZookeeper().getEnsembleServers()); assertEquals((Integer) 100, config.getZookeeper().getTimeout()); assertEquals((Integer) 1000, config.getZookeeper().getRetryMs()); assertEquals((Integer) 10, config.getZookeeper().getRetryMax()); assertEquals((Integer) 50, config.getZookeeper().getRetryMaxMs()); }
@Test public void testConfigurationKafka1() throws Exception { final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class, Validators.newValidator(), Jackson.newObjectMapper(), "") .build(new File(getClass().getResource("/config1.yml").toURI())); assertEquals("localhost:9092", config.getKafka().getBootstrapServers()); final Properties props = config.getKafka().asProperties(); assertEquals("all", props.getProperty("acks")); assertEquals("16384", props.getProperty("batch.size")); assertEquals("otherValue", props.getProperty("otherProperty")); }
protected Pac4jFactory getPac4jFactory( Collection<Pac4jFeatureSupport> featuresSupported, String resourceName) throws Exception { ObjectMapper om = Jackson.newObjectMapper(); Bootstrap<?> b = mock(Bootstrap.class); when(b.getObjectMapper()).thenReturn(om); for (Pac4jFeatureSupport fs : featuresSupported) { fs.setup(b); } return new YamlConfigurationFactory<>(Pac4jFactory.class, Validators.newValidator(), om, "dw").build( new File(Resources.getResource(resourceName).toURI())); }
@Test public void recordResource_returnsMostRecentRecord_whenMultipleEntriesExist() throws IOException { Response response = register.getRequest(address, "/record/6789.json"); JsonNode res = Jackson.newObjectMapper().readValue(response.readEntity(String.class), JsonNode.class); assertThat(res.get("6789").get("item").get(0).get("street").textValue(), equalTo("presley")); }
@Test public void checkMessageIsConsumedAndStoredInDatabase() throws Exception { JsonNode inputItem = canonicalJsonMapper.readFromBytes("{\"register\":\"ft_openregister_test\",\"text\":\"SomeText\"}".getBytes()); Response r = register.mintLines(TestRegister.register, inputItem.toString()); assertThat(r.getStatus(), equalTo(204)); TestDBItem storedItem = testItemDAO.getItems(schema).get(7); assertThat(storedItem.contents, equalTo(inputItem)); assertThat(storedItem.hashValue, equalTo(Item.itemHash(inputItem))); Entry entry = testEntryDAO.getAllEntries(schema).get(0); assertThat(entry, equalTo(new Entry(1, storedItem.hashValue, entry.getTimestamp(), "ft_openregister_test", EntryType.user))); Record record = testRecordDAO.findRecords(Arrays.asList("ft_openregister_test"), IndexNames.RECORD, schema, "entry").get(0); assertThat(record.getEntry().getEntryNumber(), equalTo(1)); assertThat(record.getEntry().getKey(), equalTo("ft_openregister_test")); Response response = register.getRequest(TestRegister.register, "/record/ft_openregister_test.json"); assertThat(response.getStatus(), equalTo(200)); Map actualJson = Jackson.newObjectMapper().convertValue(response.readEntity(JsonNode.class).get("ft_openregister_test"), Map.class); actualJson.remove("entry-timestamp"); // ignore the timestamp as we can't do exact match assertThat(actualJson.get("entry-number"), is("1")); List<Map<String,Object>> itemMaps = (List<Map<String,Object>>)actualJson.get("item"); assertThat(itemMaps.size(), is(1)); Map<String, Object> itemMap = itemMaps.get(0); assertThat(itemMap.get("register"), is("ft_openregister_test")); assertThat(itemMap.get("text"), is("SomeText")); }
@Test public void getEntriesAsJson() throws JSONException, IOException { Response response = register.getRequest(address, "/entries.json"); assertThat(response.getStatus(), equalTo(200)); JsonNode res = Jackson.newObjectMapper().readValue(response.readEntity(String.class), JsonNode.class); assertThat(res.isArray(), equalTo(true)); assertEntryInJsonNode(res.get(0), 1, item1Hash); assertEntryInJsonNode(res.get(1), 2, item2Hash); }
@Test public void getEntryByEntryNumber() throws JSONException, IOException { Response response = register.getRequest(address, "/entry/1.json"); assertThat(response.getStatus(), equalTo(200)); JsonNode res = Jackson.newObjectMapper().readValue(response.readEntity(String.class), JsonNode.class); assertThat(res.size(), equalTo(1)); assertEntryInJsonNode(res.get(0), 1, item1Hash); }