method2testcases
stringlengths
118
3.08k
### Question: SetHttpHeader extends SetHeader { @Override public void process(final Exchange exchange) throws Exception { super.process(exchange); SyndesisHeaderStrategy.whitelist(exchange, headerName); } SetHttpHeader(final String headerName, final String headerValue); @Override void process(final Exchange exchange); }### Answer: @Test public void shouldSetHeaderAndWhitelist() throws Exception { final Exchange exchange = new DefaultExchange(new DefaultCamelContext()); new SetHttpHeader("name", "value").process(exchange); assertThat(exchange.getIn().getHeader("name")).isEqualTo("value"); assertThat(SyndesisHeaderStrategy.isWhitelisted(exchange, "name")).isTrue(); }
### Question: LogStepHandler implements IntegrationStepHandler { @Override public Optional<ProcessorDefinition<?>> handle(Step step, ProcessorDefinition<?> route, IntegrationRouteBuilder builder, String flowIndex, String stepIndex) { final String message = createMessage(step); if (message.isEmpty()) { return Optional.empty(); } if (step.getId().isPresent()) { String stepId = step.getId().get(); return Optional.of(route.log(LoggingLevel.INFO, (String) null, stepId, message)); } return Optional.of(route.log(LoggingLevel.INFO, message)); } @Override boolean canHandle(Step step); @Override Optional<ProcessorDefinition<?>> handle(Step step, ProcessorDefinition<?> route, IntegrationRouteBuilder builder, String flowIndex, String stepIndex); }### Answer: @Test public void shouldAddLogProcessorWithCustomMessage() { final Step step = new Step.Builder().putConfiguredProperty("customText", "Log me baby one more time").build(); assertThat(handler.handle(step, route, NOT_USED, "1", "2")).contains(route); verify(route).log(LoggingLevel.INFO, "Log me baby one more time"); } @Test public void shouldAddLogProcessorWithCustomMessageAndStepId() { final Step step = new Step.Builder().id("step-id") .putConfiguredProperty("customText", "Log me baby one more time").build(); assertThat(handler.handle(step, route, NOT_USED, "1", "2")).contains(route); verify(route).log(LoggingLevel.INFO, (String) null, "step-id", "Log me baby one more time"); } @Test public void shouldNotAddLogProcessorWhenNotingIsSpecifiedToLog() { final Step step = new Step.Builder().build(); assertThat(handler.handle(step, route, NOT_USED, "1", "2")).isEmpty(); verifyZeroInteractions(route); }
### Question: KeyStoreHelper { public KeyStoreHelper store() { try { KeyStore keyStore = CertificateUtil.createKeyStore(certificate, alias); tempFile = Files.createTempFile(alias, ".ks", PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); password = generatePassword(); try (OutputStream stream = new FileOutputStream(tempFile.toFile())) { keyStore.store(stream, password.toCharArray()); } } catch (GeneralSecurityException | IOException e) { throw new IllegalArgumentException(String.format("Error creating key store %s: %s", alias, e.getMessage()), e); } return this; } KeyStoreHelper(String certificate, String alias); String getKeyStorePath(); String getPassword(); KeyStoreHelper store(); boolean clean(); static KeyStore defaultKeyStore(); static KeyStore createKeyStoreWithCustomCertificate(String alias, String certContent); }### Answer: @Test public void testStore() throws Exception { final KeyStoreHelper helper = new KeyStoreHelper(CertificateUtilTest.TEST_CERT, "test-cert"); helper.store(); assertThat(helper.getKeyStorePath()).isNotEmpty(); assertThat(helper.getPassword()).isNotEmpty(); }
### Question: ConnectorOptions { public static String extractOption(Map<String, ?> options, String key, String defaultValue) { if (options == null) { return defaultValue; } return Optional.ofNullable(options.get(key)) .map(Object::toString) .filter(v -> v.length() > 0) .orElse(defaultValue); } private ConnectorOptions(); static String extractOption(Map<String, ?> options, String key, String defaultValue); static String extractOption(Map<String, ?> options, String key); static String popOption(Map<String, ?> options, String key); static T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn, T defaultValue); static T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn); static void extractOptionAndConsume(Map<String, ?> options, String key, Consumer<String> consumer); static T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass, T defaultValue); static T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass); }### Answer: @Test public void testStringValue() { put(key, value); assertEquals(value, ConnectorOptions.extractOption(parameters, key)); assertNull(ConnectorOptions.extractOption(parameters, missingKey)); } @Test public void testStringValueWithDefault() { String defaultValue = "defaultValue"; put(key, value); assertEquals(value, ConnectorOptions.extractOption(parameters, key, defaultValue)); assertEquals(defaultValue, ConnectorOptions.extractOption(parameters, missingKey, defaultValue)); }
### Question: ConnectorOptions { public static void extractOptionAndConsume(Map<String, ?> options, String key, Consumer<String> consumer) { if (options == null) { return; } try { Optional.ofNullable(options.get(key)) .map(Object::toString) .ifPresent(consumer); } catch (Exception ex) { LOG.error("Evaluation of option '" + key + "' failed.", ex); } } private ConnectorOptions(); static String extractOption(Map<String, ?> options, String key, String defaultValue); static String extractOption(Map<String, ?> options, String key); static String popOption(Map<String, ?> options, String key); static T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn, T defaultValue); static T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn); static void extractOptionAndConsume(Map<String, ?> options, String key, Consumer<String> consumer); static T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass, T defaultValue); static T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass); }### Answer: @Test public void testValueAndConsumer() { put(key, value); final int[] cRun = new int[1]; final int[] success = new int[1]; Consumer<String> c = (String v) -> { cRun[0] = 1; if (v.equals(value)) { success[0] = 1; } }; cRun[0] = 0; success[0] = 0; ConnectorOptions.extractOptionAndConsume(parameters, key, c); assertEquals(1, cRun[0]); assertEquals(1, success[0]); cRun[0] = 0; success[0] = 0; ConnectorOptions.extractOptionAndConsume(parameters, missingKey, c); assertEquals(0, cRun[0]); assertEquals(0, success[0]); }
### Question: ConnectorOptions { public static <T> T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass, T defaultValue) { if (options == null) { return defaultValue; } return Optional.ofNullable(options.get(key)) .filter(requiredClass::isInstance) .map(requiredClass::cast) .orElse(defaultValue); } private ConnectorOptions(); static String extractOption(Map<String, ?> options, String key, String defaultValue); static String extractOption(Map<String, ?> options, String key); static String popOption(Map<String, ?> options, String key); static T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn, T defaultValue); static T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn); static void extractOptionAndConsume(Map<String, ?> options, String key, Consumer<String> consumer); static T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass, T defaultValue); static T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass); }### Answer: @Test public void testTypedValue() { Colours redValue = Colours.RED; put(key, redValue); assertEquals(redValue, ConnectorOptions.extractOptionAsType(parameters, key, Colours.class)); assertNull(ConnectorOptions.extractOptionAsType(parameters, missingKey, Colours.class)); }
### Question: CertificateUtil { public static KeyManager[] createKeyManagers(String clientCertificate, String alias) throws GeneralSecurityException, IOException { final KeyStore clientKs = createKeyStore(clientCertificate, alias); KeyManagerFactory kmFactory = KeyManagerFactory.getInstance("PKIX"); kmFactory.init(clientKs, null); return kmFactory.getKeyManagers(); } private CertificateUtil(); static KeyManager[] createKeyManagers(String clientCertificate, String alias); static TrustManager[] createTrustAllTrustManagers(); static TrustManager[] createTrustManagers(String brokerCertificate, String alias); static KeyStore createKeyStore(String certificate, String alias); static String getMultilineCertificate(String certificate); }### Answer: @Test public void testCreateKeyManagers() throws Exception { final KeyManager[] keyManagers = CertificateUtil.createKeyManagers(TEST_CERT, "test-cert"); assertThat(keyManagers).isNotNull().isNotEmpty(); }
### Question: LogStepHandler implements IntegrationStepHandler { static String createMessage(Step l) { StringBuilder sb = new StringBuilder(128); String customText = getCustomText(l.getConfiguredProperties()); boolean isContextLoggingEnabled = isContextLoggingEnabled(l.getConfiguredProperties()); boolean isBodyLoggingEnabled = isBodyLoggingEnabled(l.getConfiguredProperties()); if (isContextLoggingEnabled) { sb.append("Message Context: [${in.headers}] "); } if (isBodyLoggingEnabled) { sb.append("Body: [${bean:bodyLogger}] "); } if (customText != null && !customText.isEmpty() && !customText.equals("null")) { sb.append(customText); } return sb.toString(); } @Override boolean canHandle(Step step); @Override Optional<ProcessorDefinition<?>> handle(Step step, ProcessorDefinition<?> route, IntegrationRouteBuilder builder, String flowIndex, String stepIndex); }### Answer: @Test public void shouldGenerateMessages() { final Step step = new Step.Builder().putConfiguredProperty("customText", "Log me baby one more time").build(); assertThat(LogStepHandler.createMessage(step)).isEqualTo("Log me baby one more time"); final Step withContext = new Step.Builder().createFrom(step) .putConfiguredProperty("contextLoggingEnabled", "true").build(); assertThat(LogStepHandler.createMessage(withContext)) .isEqualTo("Message Context: [${in.headers}] Log me baby one more time"); final Step withBody = new Step.Builder().createFrom(step).putConfiguredProperty("bodyLoggingEnabled", "true") .build(); assertThat(LogStepHandler.createMessage(withBody)).isEqualTo("Body: [${bean:bodyLogger}] Log me baby one more time"); final Step withContextAndBody = new Step.Builder().createFrom(step) .putConfiguredProperty("contextLoggingEnabled", "true").putConfiguredProperty("bodyLoggingEnabled", "true") .build(); assertThat(LogStepHandler.createMessage(withContextAndBody)) .isEqualTo("Message Context: [${in.headers}] Body: [${bean:bodyLogger}] Log me baby one more time"); }
### Question: CertificateUtil { public static TrustManager[] createTrustManagers(String brokerCertificate, String alias) throws GeneralSecurityException, IOException { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509"); trustManagerFactory.init(createKeyStore(brokerCertificate, alias)); return trustManagerFactory.getTrustManagers(); } private CertificateUtil(); static KeyManager[] createKeyManagers(String clientCertificate, String alias); static TrustManager[] createTrustAllTrustManagers(); static TrustManager[] createTrustManagers(String brokerCertificate, String alias); static KeyStore createKeyStore(String certificate, String alias); static String getMultilineCertificate(String certificate); }### Answer: @Test public void testCreateTrustManagers() throws Exception { final TrustManager[] trustManagers = CertificateUtil.createTrustManagers(TEST_CERT, "test-cert"); assertThat(trustManagers).isNotNull().isNotEmpty(); }
### Question: ErrorMapper { public static Map<String, Integer> jsonToMap(String property) { try { if (ObjectHelper.isEmpty(property)) { return Collections.emptyMap(); } return JsonUtils.reader().forType(STRING_MAP_TYPE).readValue(property); } catch (IOException e) { LOG.warn(String.format("Failed to read error code mapping property %s: %s", property, e.getMessage()), e); return Collections.emptyMap(); } } private ErrorMapper(); static Map<String, Integer> jsonToMap(String property); static ErrorStatusInfo mapError(final Exception exception, final Map<String, Integer> httpResponseCodeMappings, final Integer defaultResponseCode); }### Answer: @Test public void testJsonToMap() { assertThat(errorResponseCodeMappings.size()).isEqualTo(4); assertThat(errorResponseCodeMappings.containsKey("SQL_CONNECTOR_ERROR")).isTrue(); }
### Question: ExcludeFilter implements ArtifactsFilter { @Override public Set<Artifact> filter(final Set<Artifact> artifacts) throws ArtifactFilterException { final Set<Artifact> included = new HashSet<>(); for (final Artifact given : artifacts) { if (isArtifactIncluded(given)) { included.add(given); } } return included; } ExcludeFilter(final String excludedGroupId, final String excludedArtifactId); @Override Set<Artifact> filter(final Set<Artifact> artifacts); @Override boolean isArtifactIncluded(final Artifact artifact); }### Answer: @Test public void shouldPerformFiltering() throws ArtifactFilterException { final Set<Artifact> given = new HashSet<>(); given.add(included1); given.add(excluded); given.add(included2); assertThat(filter.filter(given)).containsOnly(included1, included2); }
### Question: PaginationFilter implements Function<ListResult<T>, ListResult<T>> { @Override public ListResult<T> apply(ListResult<T> result) { List<T> list = result.getItems(); if (startIndex >= list.size()) { list = Collections.emptyList(); } else { list = list.subList(startIndex, Math.min(list.size(), endIndex)); } return new ListResult.Builder<T>().createFrom(result).items(list).build(); } PaginationFilter(PaginationOptions options); @Override ListResult<T> apply(ListResult<T> result); }### Answer: @Test public void apply() throws Exception { try { ListResult<Integer> filtered = new PaginationFilter<Integer>(new PaginationOptions() { @Override public int getPage() { return PaginationFilterTest.this.parameter.page; } @Override public int getPerPage() { return PaginationFilterTest.this.parameter.perPage; } }).apply(new ListResult.Builder<Integer>().items(parameter.inputList).totalCount(parameter.inputList.size()).build()); assertEquals(parameter.outputList, filtered.getItems()); assertEquals(parameter.inputList.size(), filtered.getTotalCount()); } catch (Exception e) { if (parameter.expectedException == null) { throw e; } assertEquals(parameter.expectedException, e.getClass()); return; } if (parameter.expectedException != null) { fail("Expected exception " + parameter.expectedException); } }
### Question: ClientSideState { @SuppressWarnings("JdkObsolete") public NewCookie persist(final String key, final String path, final Object value) { final Date expiry = Date.from(ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(timeout).toInstant()); return new NewCookie(key, protect(value), path, null, Cookie.DEFAULT_VERSION, null, timeout, expiry, true, false); } ClientSideState(final Edition edition); ClientSideState(final Edition edition, final int timeout); ClientSideState(final Edition edition, final LongSupplier timeSource, final int timeout); ClientSideState(final Edition edition, final LongSupplier timeSource, final Supplier<byte[]> ivSource, final Function<Object, byte[]> serialization, final BiFunction<Class<?>, byte[], Object> deserialization, final int timeout); @SuppressWarnings("JdkObsolete") NewCookie persist(final String key, final String path, final Object value); Set<T> restoreFrom(final Collection<Cookie> cookies, final Class<T> type); T restoreFrom(final Cookie cookie, final Class<T> type); static final int DEFAULT_TIMEOUT; }### Answer: @Test public void shouldPersistAsInRfcErrata() { final ClientSideState clientSideState = new ClientSideState(RFC_EDITION, ClientSideStateTest::rfcTime, ClientSideStateTest::rfcIV, ClientSideStateTest::serialize, ClientSideStateTest::deserialize, ClientSideState.DEFAULT_TIMEOUT); final NewCookie cookie = clientSideState.persist("id", "/path", "a state string"); assertThat(cookie).isNotNull(); assertThat(cookie.getName()).isEqualTo("id"); assertThat(cookie.getValue()) .isEqualTo("pzSOjcNui9-HWS_Qk1Pwpg|MTM0NzI2NTk1NQ|dGlk|tL3lJPf2nUSFMN6dtVXJTw|uea1fgC67RmOxfpNz8gMbnPWfDA"); assertThat(cookie.getPath()).isEqualTo("/path"); assertThat(cookie.isHttpOnly()).isFalse(); assertThat(cookie.isSecure()).isTrue(); }
### Question: ErrorMap { public static String from(String rawMsg) { if (rawMsg.matches("^\\s*\\<.*")) { return parseWith(rawMsg, new XmlMapper()); } if (rawMsg.matches("^\\s*\\{.*")) { return parseWith(rawMsg, new ObjectMapper()); } return rawMsg; } private ErrorMap(); static String from(String rawMsg); }### Answer: @Test public void testUnmarshalXML() { String rawMsg = read("/HttpClientErrorException.xml"); assertThat(ErrorMap.from(rawMsg)).isEqualTo("Desktop applications only support the oauth_callback value 'oob'"); } @Test public void testUnmarshalJSON() { String rawMsg = read("/HttpClientErrorException.json"); assertThat(ErrorMap.from(rawMsg)).isEqualTo("Could not authenticate you."); } @Test public void testUnmarshalJSONVaryingFormats() { assertThat(ErrorMap.from("{\"error\": \"some error\"}")).isEqualTo("some error"); assertThat(ErrorMap.from("{\"message\": \"some message\"}")).isEqualTo("some message"); } @Test public void testUnmarshalImpossible() { String rawMsg = "This is just some other error format"; assertThat(ErrorMap.from(rawMsg)).isEqualTo(rawMsg); }
### Question: ErrorMap { static Optional<String> tryLookingUp(final JsonNode node, final String... pathElements) { JsonNode current = node; for (String pathElement : pathElements) { current = current.get(pathElement); if (current != null && current.isArray() && current.iterator().hasNext()) { current = current.iterator().next(); } if (current == null) { return Optional.empty(); } } if (current.isObject()) { return Optional.of(current.toString()); } return Optional.of(current.asText()); } private ErrorMap(); static String from(String rawMsg); }### Answer: @Test public void shouldTryToLookupInJson() { final JsonNodeFactory factory = JsonNodeFactory.instance; final ObjectNode obj = factory.objectNode(); obj.set("a", factory.arrayNode().add("b").add("c")); obj.set("x", factory.objectNode().set("y", factory.objectNode().put("z", "!"))); assertThat(ErrorMap.tryLookingUp(obj, "a")).contains("b"); assertThat(ErrorMap.tryLookingUp(obj, "a", "b")).isEmpty(); assertThat(ErrorMap.tryLookingUp(obj, "x", "y")).contains("{\"z\":\"!\"}"); assertThat(ErrorMap.tryLookingUp(obj, "x", "y", "z")).contains("!"); }
### Question: ConnectorPropertiesHandler { @POST @Produces(MediaType.APPLICATION_JSON) public DynamicConnectionPropertiesMetadata dynamicConnectionProperties(@PathParam("id") final String connectorId) { final HystrixExecutable<DynamicConnectionPropertiesMetadata> meta = createMetadataConnectionPropertiesCommand(connectorId); return meta.execute(); } ConnectorPropertiesHandler(final MetadataConfigurationProperties config); @POST @Produces(MediaType.APPLICATION_JSON) DynamicConnectionPropertiesMetadata dynamicConnectionProperties(@PathParam("id") final String connectorId); }### Answer: @Test public void shouldSendRequestsToMeta() { final MetadataConfigurationProperties config = new MetadataConfigurationProperties(); config.setService("syndesis-meta"); final Client client = mock(Client.class); final ConnectorPropertiesHandler handler = new ConnectorPropertiesHandler(config) { @Override protected HystrixExecutable<DynamicConnectionPropertiesMetadata> createMetadataConnectionPropertiesCommand(final String connectorId) { return new MetadataConnectionPropertiesCommand(config, connectorId, Collections.emptyMap()){ @Override protected Client createClient() { return client; } }; } }; final ArgumentCaptor<String> url = ArgumentCaptor.forClass(String.class); final WebTarget target = mock(WebTarget.class); when(client.target(url.capture())).thenReturn(target); final Invocation.Builder builder = mock(Invocation.Builder.class); when(target.request(MediaType.APPLICATION_JSON)).thenReturn(builder); final Map<String, Object> properties = Collections.emptyMap(); final Map<String, List<WithDynamicProperties.ActionPropertySuggestion>> dynamicProperties = buildProperties(); final DynamicConnectionPropertiesMetadata dynamicConnectionPropertiesMetadata = new DynamicConnectionPropertiesMetadata.Builder() .properties(dynamicProperties) .build(); when(builder.post(Entity.entity(properties, MediaType.APPLICATION_JSON_TYPE),DynamicConnectionPropertiesMetadata.class)) .thenReturn(dynamicConnectionPropertiesMetadata); final DynamicConnectionPropertiesMetadata received = handler.dynamicConnectionProperties("connectorId"); assertThat(received).isSameAs(dynamicConnectionPropertiesMetadata); assertThat(url.getValue()).isEqualTo("http: }
### Question: KeyGenerator { public static long getKeyTimeMillis(String key) throws IOException { byte[] decoded = Base64.decode(stripPreAndSuffix(key), Base64.ORDERED); if (decoded.length != 15) { throw new IOException("Invalid key: size is incorrect."); } ByteBuffer buffer = ByteBuffer.allocate(8); buffer.position(2); buffer.put(decoded, 0 ,6); buffer.flip(); return buffer.getLong(); } private KeyGenerator(); static String createKey(); static long getKeyTimeMillis(String key); static String recreateKey(long timestamp, int random1, long random2); }### Answer: @Test public void testGetKeyTimeMillis() throws IOException { long t1 = System.currentTimeMillis(); String key = KeyGenerator.createKey(); long t2 = KeyGenerator.getKeyTimeMillis(key); assertThat(t2).isCloseTo(t1, Offset.offset(500L)); }
### Question: IntegrationIdFilter implements Function<ListResult<IntegrationDeployment>, ListResult<IntegrationDeployment>> { @Override public ListResult<IntegrationDeployment> apply(final ListResult<IntegrationDeployment> list) { if (integrationId == null) { return list; } final List<IntegrationDeployment> filtered = list.getItems().stream() .filter(i -> i.getSpec().idEquals(integrationId)).collect(Collectors.toList()); return ListResult.of(filtered); } IntegrationIdFilter(final String integrationId); @Override ListResult<IntegrationDeployment> apply(final ListResult<IntegrationDeployment> list); }### Answer: @Test public void shouldFilterEmptyResults() { assertThat(filter.apply(ListResult.of(emptyList()))).isEmpty(); } @Test public void shouldFilterOutTrivialWantedDeployments() { assertThat(filter.apply(ListResult.of(wanted))).containsOnly(wanted); } @Test public void shouldFilterOutWantedDeployments() { assertThat(filter.apply(ListResult.of(unwanted, wanted, unwanted))).containsOnly(wanted); } @Test public void shouldFilterOutWantedDeploymentsNotFinding() { assertThat(filter.apply(ListResult.of(unwanted, unwanted, unwanted))).isEmpty(); }
### Question: OAuthConnectorFilter implements Function<ListResult<Connector>, ListResult<Connector>> { @Override public ListResult<Connector> apply(final ListResult<Connector> result) { final List<Connector> oauthConnectors = result.getItems().stream() .filter(c -> c.propertyEntryTaggedWith(Credentials.CLIENT_ID_TAG).isPresent()).collect(Collectors.toList()); return ListResult.of(oauthConnectors); } private OAuthConnectorFilter(); @Override ListResult<Connector> apply(final ListResult<Connector> result); static final Function<ListResult<Connector>, ListResult<Connector>> INSTANCE; }### Answer: @Test public void shouldFilterOutNonOAuthConnectors() { final Connector connector1 = new Connector.Builder().build(); final Connector connector2 = new Connector.Builder() .putProperty("clientId", new ConfigurationProperty.Builder().addTag(Credentials.CLIENT_ID_TAG).build()) .putConfiguredProperty("clientId", "my-client-id").build(); final Connector connector3 = new Connector.Builder() .putProperty("clientId", new ConfigurationProperty.Builder().addTag(Credentials.CLIENT_ID_TAG).build()).build(); final ListResult<Connector> result = ListResult.of(connector1, connector2, connector3); assertThat(OAuthConnectorFilter.INSTANCE.apply(result)).containsOnly(connector2, connector3); }
### Question: DeploymentStateMonitorController implements Runnable, Closeable, DeploymentStateMonitor { @PostConstruct @SuppressWarnings("FutureReturnValueIgnored") public void open() { LOGGER.info("Starting deployment state monitor."); scheduler.scheduleWithFixedDelay(this, configuration.getInitialDelay(), configuration.getPeriod(), TimeUnit.SECONDS); } @Autowired DeploymentStateMonitorController(MonitoringConfiguration configuration, DataManager dataManager); @PostConstruct @SuppressWarnings("FutureReturnValueIgnored") void open(); @Override void close(); @Override void run(); @Override void register(IntegrationDeploymentState state, StateHandler stateHandler); }### Answer: @Test public void testMonitoringController() throws IOException { final MonitoringConfiguration configuration = new MonitoringConfiguration(); configuration.setInitialDelay(5); configuration.setPeriod(5); try (DeploymentStateMonitorController controller = new DeploymentStateMonitorController(configuration, dataManager)) { new PublishingStateMonitor(controller, client, dataManager) { @Override protected Pod getPod(String podName) { final Pod pod; switch (podName) { case BUILD_POD_NAME: pod = buildPod; break; case DEPLOYER_POD_NAME: pod = deployerPod; break; default: pod = null; } return pod; } @Override protected Optional<Build> getBuild(String integrationId, String version) { return Optional.ofNullable(build); } @Override protected Optional<ReplicationController> getReplicationController(String integrationId, String version) { return Optional.ofNullable(replicationController); } @Override protected PodList getDeploymentPodList(String integrationId, String version) { final PodListBuilder builder = new PodListBuilder(); return deploymentPod == null ? builder.build() : builder.addToItems(deploymentPod).build(); } }; controller.open(); given().await() .atMost(Duration.ofSeconds(20)) .pollInterval(Duration.ofSeconds(5)) .untilAsserted(() -> assertEquals(expectedDetails, dataManager.fetch(IntegrationDeploymentStateDetails.class, DEPLOYMENT_ID))); } }
### Question: JsonUtils { public static boolean isJson(String value) { if (value == null) { return false; } return isJsonObject(value) || isJsonArray(value); } private JsonUtils(); static ObjectReader reader(); static T readFromStream(final InputStream stream, final Class<T> type); static ObjectWriter writer(); static ObjectMapper copyObjectMapperConfiguration(); static Map<String, Object> map(Object... values); static T convertValue(final Object fromValue, final Class<T> toValueType); static boolean isJson(String value); static boolean isJsonObject(String value); static boolean isJsonArray(String value); static List<String> arrayToJsonBeans(JsonNode json); static String jsonBeansToArray(List<?> jsonBeans); static String toPrettyString(Object value); static String toString(Object value); }### Answer: @Test public void isJson() { assertThat(JsonUtils.isJson(null)).isFalse(); assertThat(JsonUtils.isJson("")).isFalse(); assertThat(JsonUtils.isJson("{}")).isTrue(); assertThat(JsonUtils.isJson("{\"foo\": \"bar\"}")).isTrue(); assertThat(JsonUtils.isJson(" {\"foo\": \"bar\"} ")).isTrue(); assertThat(JsonUtils.isJson("\n{\"foo\": \"bar\"}\n")).isTrue(); assertThat(JsonUtils.isJson("[]")).isTrue(); assertThat(JsonUtils.isJson("[{\"foo\": \"bar\"}]")).isTrue(); assertThat(JsonUtils.isJson(" [{\"foo\": \"bar\"}] ")).isTrue(); assertThat(JsonUtils.isJson("\n[{\"foo\": \"bar\"}]\n")).isTrue(); }
### Question: DependenciesCustomizer implements CamelKIntegrationCustomizer { public DependenciesCustomizer(VersionService versionService, IntegrationResourceManager resourceManager) { this.versionService = versionService; this.resourceManager = resourceManager; } DependenciesCustomizer(VersionService versionService, IntegrationResourceManager resourceManager); @Override Integration customize(IntegrationDeployment deployment, Integration integration, EnumSet<Exposure> exposure); }### Answer: @Test public void testDependenciesCustomizer() { VersionService versionService = new VersionService(); TestResourceManager manager = new TestResourceManager(); Integration integration = manager.newIntegration( new Step.Builder() .addDependencies(Dependency.maven("io.syndesis.connector:syndesis-connector-api-provider")) .build() ); IntegrationDeployment deployment = new IntegrationDeployment.Builder() .userId("user") .id("idId") .spec(integration) .build(); CamelKIntegrationCustomizer customizer = new DependenciesCustomizer(versionService, manager); io.syndesis.server.controller.integration.camelk.crd.Integration i = customizer.customize( deployment, new io.syndesis.server.controller.integration.camelk.crd.Integration(), EnumSet.noneOf(Exposure.class) ); assertThat(i.getSpec().getDependencies()).anyMatch(s -> s.startsWith("bom:io.syndesis.integration/integration-bom-camel-k/pom/")); assertThat(i.getSpec().getDependencies()).anyMatch(s -> s.startsWith("mvn:io.syndesis.integration/integration-runtime-camelk")); assertThat(i.getSpec().getDependencies()).anyMatch(s -> s.startsWith("mvn:io.syndesis.connector/syndesis-connector-api-provider")); }
### Question: CamelVersionCustomizer extends AbstractTraitCustomizer { public CamelVersionCustomizer(VersionService versionService) { this.versionService = versionService; } CamelVersionCustomizer(VersionService versionService); }### Answer: @Test public void testCamelVersionCustomizer() { VersionService versionService = new VersionService(); TestResourceManager manager = new TestResourceManager(); Integration integration = manager.newIntegration(); IntegrationDeployment deployment = new IntegrationDeployment.Builder() .userId("user") .id("idId") .spec(integration) .build(); CamelKIntegrationCustomizer customizer = new CamelVersionCustomizer(versionService); io.syndesis.server.controller.integration.camelk.crd.Integration i = customizer.customize( deployment, new io.syndesis.server.controller.integration.camelk.crd.Integration(), EnumSet.of(Exposure.SERVICE) ); assertThat(i.getSpec().getTraits()).containsKey("camel"); assertThat(i.getSpec().getTraits().get("camel").getConfiguration()).containsOnly( entry("version", versionService.getCamelVersion()), entry("runtime-version", versionService.getCamelkRuntimeVersion()) ); }
### Question: JsonUtils { public static boolean isJsonObject(String value) { if (Strings.isEmptyOrBlank(value)) { return false; } final String trimmed = value.trim(); return trimmed.charAt(0) == '{' && trimmed.charAt(trimmed.length() - 1) == '}'; } private JsonUtils(); static ObjectReader reader(); static T readFromStream(final InputStream stream, final Class<T> type); static ObjectWriter writer(); static ObjectMapper copyObjectMapperConfiguration(); static Map<String, Object> map(Object... values); static T convertValue(final Object fromValue, final Class<T> toValueType); static boolean isJson(String value); static boolean isJsonObject(String value); static boolean isJsonArray(String value); static List<String> arrayToJsonBeans(JsonNode json); static String jsonBeansToArray(List<?> jsonBeans); static String toPrettyString(Object value); static String toString(Object value); }### Answer: @Test public void isJsonObject() { assertThat(JsonUtils.isJsonObject(null)).isFalse(); assertThat(JsonUtils.isJsonObject("")).isFalse(); assertThat(JsonUtils.isJsonObject("{}")).isTrue(); assertThat(JsonUtils.isJsonObject("{\"foo\": \"bar\"}")).isTrue(); assertThat(JsonUtils.isJsonObject(" {\"foo\": \"bar\"} ")).isTrue(); assertThat(JsonUtils.isJsonObject("\n{\"foo\": \"bar\"}\n")).isTrue(); assertThat(JsonUtils.isJsonObject("[]")).isFalse(); }
### Question: JsonRecordSupport { public static String toLexSortableString(long value) { return toLexSortableString(Long.toString(value)); } private JsonRecordSupport(); static void jsonStreamToRecords(Set<String> indexes, String dbPath, InputStream is, Consumer<JsonRecord> consumer); static String convertToDBPath(String base); static String validateKey(String key); static void jsonStreamToRecords(Set<String> indexes, JsonParser jp, String path, Consumer<JsonRecord> consumer); static String toLexSortableString(long value); static String toLexSortableString(int value); @SuppressWarnings("PMD.NPathComplexity") static String toLexSortableString(final String value); static final Pattern INTEGER_PATTERN; static final Pattern INDEX_EXTRACTOR_PATTERN; static final char NULL_VALUE_PREFIX; static final char FALSE_VALUE_PREFIX; static final char TRUE_VALUE_PREFIX; static final char NUMBER_VALUE_PREFIX; static final char NEG_NUMBER_VALUE_PREFIX; static final char STRING_VALUE_PREFIX; static final char ARRAY_VALUE_PREFIX; }### Answer: @Test @SuppressWarnings("unchecked") public void testSmallValues() { String last=null; for (int i = -1000; i < 1000; i++) { String next = toLexSortableString(i); if( last != null ) { assertThat((Comparable)last).isLessThan(next); } last = next; } } @Test @SuppressWarnings("unchecked") public void testFloatsValues() { assertThat(toLexSortableString("1.01")).isEqualTo("[101-"); assertThat(toLexSortableString("-100.5")).isEqualTo("--68994["); String last=null; for (int i = 0; i < 9000; i++) { String value = rtrim(String.format("23.%04d",i),"0"); String next = toLexSortableString(value); if( last != null ) { assertThat((Comparable)last).isLessThan(next); } last = next; } }
### Question: SimpleEventBus implements EventBus { @Override public void send(String subscriberId, String event, String data) { Subscription sub = subscriptions.get(subscriberId); if( sub!=null ) { sub.onEvent(event, data); } } @Override Subscription subscribe(String subscriberId, Subscription handler); @Override Subscription unsubscribe(String subscriberId); @Override void broadcast(String event, String data); @Override void send(String subscriberId, String event, String data); }### Answer: @Test public void testSend() throws InterruptedException { CountDownLatch done = new CountDownLatch(1); String sub1[] = new String[2]; EventBus eventBus = createEventBus(); eventBus.subscribe("a", (event, data) -> { sub1[0] = event; sub1[1] = data; done.countDown(); }); eventBus.send("a", "text", "data"); done.await(5, TimeUnit.SECONDS); assertEquals("text", sub1[0]); assertEquals("data", sub1[1]); }
### Question: SimpleEventBus implements EventBus { @Override public void broadcast(String event, String data) { for (Map.Entry<String, Subscription> entry : subscriptions.entrySet()) { entry.getValue().onEvent(event, data); } } @Override Subscription subscribe(String subscriberId, Subscription handler); @Override Subscription unsubscribe(String subscriberId); @Override void broadcast(String event, String data); @Override void send(String subscriberId, String event, String data); }### Answer: @Test public void testBroadcast() throws InterruptedException { CountDownLatch done = new CountDownLatch(2); String sub1[] = new String[2]; String sub2[] = new String[2]; EventBus eventBus = createEventBus(); eventBus.subscribe("a", (event, data) -> { sub1[0] = event; sub1[1] = data; done.countDown(); }); eventBus.subscribe("b", (event, data) -> { sub2[0] = event; sub2[1] = data; done.countDown(); }); eventBus.broadcast("text", "data"); done.await(5, TimeUnit.SECONDS); assertEquals("text", sub1[0]); assertEquals("data", sub1[1]); assertEquals("text", sub2[0]); assertEquals("data", sub2[1]); }
### Question: ModelConverter extends ModelResolver { @Override protected boolean ignore(final Annotated member, final XmlAccessorType xmlAccessorTypeAnnotation, final String propName, final Set<String> propertiesToIgnore) { final JsonIgnore ignore = member.getAnnotation(JsonIgnore.class); if (ignore != null && !ignore.value()) { return false; } return super.ignore(member, xmlAccessorTypeAnnotation, propName, propertiesToIgnore); } ModelConverter(); }### Answer: @Test public void shouldIgnoreMethodsAnnotatedWithJsonIgnore() throws NoSuchMethodException { final AnnotatedMethod method = method("shouldBeIgnored"); assertThat(converter.ignore(method, null, "property", Collections.emptySet())).isTrue(); } @Test public void shouldNotIgnoreMethodsAnnotatedWithJsonIgnoreValueOfFalse() throws NoSuchMethodException { final AnnotatedMethod method = method("notToBeIgnored"); assertThat(converter.ignore(method, null, "property", Collections.emptySet())).isFalse(); }
### Question: IconGenerator { public static String generate(final String template, final String name) { Mustache mustache; try { mustache = MUSTACHE_FACTORY.compile("/icon-generator/" + template + ".svg.mustache"); } catch (final MustacheNotFoundException e) { LOG.warn("Unable to load icon template for: `{}`, will use default template", template); LOG.debug("Unable to load icon template for: {}", template, e); mustache = MUSTACHE_FACTORY.compile("/icon-generator/default.svg.mustache"); } final Map<String, String> data = new HashMap<>(); final String color = COLORS[(int) (Math.random() * COLORS.length)]; data.put("color", color); data.put("letter", LETTERS.get(Character.toUpperCase(name.charAt(0)))); try (StringWriter icon = new StringWriter()) { mustache.execute(icon, data).flush(); final String trimmed = trimXml(icon.toString()); return "data:image/svg+xml," + ESCAPER.escape(trimmed); } catch (final IOException e) { throw new SyndesisServerException("Unable to generate icon from template `" + template + "`, for name: " + name, e); } } private IconGenerator(); static String generate(final String template, final String name); }### Answer: @Test public void shouldGenerateIcon() { for (int letter = 'A'; letter <= 'Z'; letter++) { final String letterString = String.valueOf((char) letter); final String icon = IconGenerator.generate("swagger-connector-template", letterString); assertThat(icon).startsWith(PREFIX); assertThat(icon).matches(".*circle.*%20style%3D%22fill%3A%23fff.*"); assertThat(icon).matches(".*path.*%20style%3D%22fill%3A%23fff.*"); } }
### Question: ActionComparator implements Comparator<ConnectorAction> { private static String name(final ConnectorAction action) { return trimToNull(action.getName()); } private ActionComparator(); @Override int compare(final ConnectorAction left, final ConnectorAction right); static final Comparator<ConnectorAction> INSTANCE; }### Answer: @Test public void shouldOrderActionsBasedOnTagsAndName() { final ConnectorAction a = new ConnectorAction.Builder().name("a").addTag("a").build(); final ConnectorAction b = new ConnectorAction.Builder().name("b").addTag("b").build(); final ConnectorAction c = new ConnectorAction.Builder().name("c").addTag("b").build(); final ConnectorAction noTagsA = new ConnectorAction.Builder().name("a").build(); final ConnectorAction noTagsB = new ConnectorAction.Builder().name("b").build(); final ConnectorAction noTagsNoName = new ConnectorAction.Builder().build(); final List<ConnectorAction> actions = new ArrayList<>(Arrays.asList(c, noTagsA, a, noTagsB, b, noTagsNoName)); Collections.shuffle(actions); actions.sort(ActionComparator.INSTANCE); assertThat(actions).containsExactly(a, b, c, noTagsA, noTagsB, noTagsNoName); }
### Question: OasModelHelper { public static Stream<String> sanitizeTags(final List<String> list) { if (list == null || list.isEmpty()) { return Stream.empty(); } return list.stream().map(OasModelHelper::sanitizeTag).filter(Objects::nonNull).distinct(); } private OasModelHelper(); static OperationDescription operationDescriptionOf(final OasDocument openApiDoc, final OasOperation operation, final BiFunction<String, String, String> consumer); static List<OasPathItem> getPathItems(OasPaths paths); static List<OasParameter> getParameters(final OasOperation operation); static List<OasParameter> getParameters(final OasPathItem pathItem); static String sanitizeTag(final String tag); static Stream<String> sanitizeTags(final List<String> list); static Map<String, OasOperation> getOperationMap(OasPathItem pathItem); static Map<String, T> getOperationMap(OasPathItem pathItem, Class<T> type); static String getReferenceName(String reference); static boolean isArrayType(OasSchema schema); static boolean isReferenceType(OasSchema schema); static boolean isReferenceType(OasParameter parameter); static boolean isBody(OasParameter parameter); static String getPropertyName(OasSchema schema); static String getPropertyName(OasSchema schema, String defaultName); static boolean isSerializable(OasParameter parameter); static boolean schemaIsNotSpecified(final OasSchema schema); static URI specificationUriFrom(final OasDocument openApiDoc); static final String URL_EXTENSION; }### Answer: @Test public void shouldSanitizeListOfTags() { assertThat(OasModelHelper.sanitizeTags(Arrays.asList("tag", "wag ", " bag", ".]t%a$g#[/"))) .containsExactly("tag", "wag", "bag"); }
### Question: JsonUtils { public static boolean isJsonArray(String value) { if (Strings.isEmptyOrBlank(value)) { return false; } final String trimmed = value.trim(); return trimmed.charAt(0) == '[' && trimmed.charAt(trimmed.length() - 1) == ']'; } private JsonUtils(); static ObjectReader reader(); static T readFromStream(final InputStream stream, final Class<T> type); static ObjectWriter writer(); static ObjectMapper copyObjectMapperConfiguration(); static Map<String, Object> map(Object... values); static T convertValue(final Object fromValue, final Class<T> toValueType); static boolean isJson(String value); static boolean isJsonObject(String value); static boolean isJsonArray(String value); static List<String> arrayToJsonBeans(JsonNode json); static String jsonBeansToArray(List<?> jsonBeans); static String toPrettyString(Object value); static String toString(Object value); }### Answer: @Test public void isJsonArray() { assertThat(JsonUtils.isJsonArray(null)).isFalse(); assertThat(JsonUtils.isJsonArray("")).isFalse(); assertThat(JsonUtils.isJsonArray("{}")).isFalse(); assertThat(JsonUtils.isJsonArray("[]")).isTrue(); assertThat(JsonUtils.isJsonArray("[{\"foo\": \"bar\"}]")).isTrue(); assertThat(JsonUtils.isJsonArray(" [{\"foo\": \"bar\"}] ")).isTrue(); assertThat(JsonUtils.isJsonArray("\n[{\"foo\": \"bar\"}]\n")).isTrue(); }
### Question: XmlSchemaHelper { public static String toXsdType(final String type) { switch (type) { case "boolean": return XML_SCHEMA_PREFIX + ":boolean"; case "number": return XML_SCHEMA_PREFIX + ":decimal"; case "string": return XML_SCHEMA_PREFIX + ":string"; case "integer": return XML_SCHEMA_PREFIX + ":integer"; default: throw new IllegalArgumentException("Unexpected type `" + type + "` given to convert to XSD type"); } } private XmlSchemaHelper(); static Element addElement(final Element parent, final String name); static Element addElement(final Element parent, final String... names); static boolean isAttribute(final OasSchema property); static boolean isElement(final OasSchema property); static String nameOf(final OasSchema property); static String nameOrDefault(final OasSchema property, final String name); static Element newXmlSchema(final String targetNamespace); static String serialize(final Document document); static String toXsdType(final String type); static String xmlNameOrDefault(final OasXML xml, final String defaultName); static String xmlTargetNamespaceOrNull(final OasSchema property); static final String XML_SCHEMA_NS; static final String XML_SCHEMA_PREFIX; }### Answer: @Test public void shouldConvertJsonSchemaToXsdTypes() { assertThat(XmlSchemaHelper.toXsdType("boolean")).isEqualTo(XmlSchemaHelper.XML_SCHEMA_PREFIX + ":boolean"); assertThat(XmlSchemaHelper.toXsdType("number")).isEqualTo(XmlSchemaHelper.XML_SCHEMA_PREFIX + ":decimal"); assertThat(XmlSchemaHelper.toXsdType("string")).isEqualTo(XmlSchemaHelper.XML_SCHEMA_PREFIX + ":string"); assertThat(XmlSchemaHelper.toXsdType("integer")).isEqualTo(XmlSchemaHelper.XML_SCHEMA_PREFIX + ":integer"); }
### Question: JsonUtils { public static List<String> arrayToJsonBeans(JsonNode json) throws JsonProcessingException { List<String> jsonBeans = new ArrayList<>(); if (json.isArray()) { Iterator<JsonNode> it = json.elements(); while (it.hasNext()) { jsonBeans.add(writer().writeValueAsString(it.next())); } return jsonBeans; } return jsonBeans; } private JsonUtils(); static ObjectReader reader(); static T readFromStream(final InputStream stream, final Class<T> type); static ObjectWriter writer(); static ObjectMapper copyObjectMapperConfiguration(); static Map<String, Object> map(Object... values); static T convertValue(final Object fromValue, final Class<T> toValueType); static boolean isJson(String value); static boolean isJsonObject(String value); static boolean isJsonArray(String value); static List<String> arrayToJsonBeans(JsonNode json); static String jsonBeansToArray(List<?> jsonBeans); static String toPrettyString(Object value); static String toString(Object value); }### Answer: @Test public void arrayToJsonBeans() throws IOException { ObjectReader reader = JsonUtils.reader(); assertThat(JsonUtils.arrayToJsonBeans(reader.readTree("{}"))).isEqualTo(Collections.emptyList()); assertThat(JsonUtils.arrayToJsonBeans(reader.readTree("{\"foo\": \"bar\"}"))).isEqualTo(Collections.emptyList()); assertThat(JsonUtils.arrayToJsonBeans(reader.readTree("[]"))).isEqualTo(Collections.emptyList()); assertThat(JsonUtils.arrayToJsonBeans(reader.readTree("[{\"foo\": \"bar\"}]"))).isEqualTo(Collections.singletonList("{\"foo\":\"bar\"}")); assertThat(JsonUtils.arrayToJsonBeans(reader.readTree("[{\"foo1\": \"bar1\"}, {\"foo2\": \"bar2\"}]"))).isEqualTo(Arrays.asList("{\"foo1\":\"bar1\"}", "{\"foo2\":\"bar2\"}")); }
### Question: OpenApiPropertyGenerator { public static String createHostUri(final String scheme, final String host, final int port) { try { if (port == -1) { return new URI(scheme, host, null, null).toString(); } return new URI(scheme, null, host, port, null, null, null).toString(); } catch (final URISyntaxException e) { throw new IllegalArgumentException(e); } } protected OpenApiPropertyGenerator(); Optional<ConfigurationProperty> createProperty(final String propertyName, final OpenApiModelInfo info, final ConfigurationProperty template, final ConnectorSettings connectorSettings); PropertyGenerator forProperty(String propertyName); static String createHostUri(final String scheme, final String host, final int port); String determineHost(final OpenApiModelInfo info); Optional<S> securityDefinition(final OpenApiModelInfo info, final ConnectorSettings connectorSettings, final OpenApiSecurityScheme type); }### Answer: @Test public void shouldCreateHostUri() { assertThat(createHostUri("scheme", "host", -1)).isEqualTo("scheme: assertThat(createHostUri("scheme", "host", 8080)).isEqualTo("scheme: }
### Question: JsonUtils { public static String jsonBeansToArray(List<?> jsonBeans) { final StringJoiner joiner = new StringJoiner(",", "[", "]"); for (Object jsonBean : jsonBeans) { joiner.add(String.valueOf(jsonBean)); } return joiner.toString(); } private JsonUtils(); static ObjectReader reader(); static T readFromStream(final InputStream stream, final Class<T> type); static ObjectWriter writer(); static ObjectMapper copyObjectMapperConfiguration(); static Map<String, Object> map(Object... values); static T convertValue(final Object fromValue, final Class<T> toValueType); static boolean isJson(String value); static boolean isJsonObject(String value); static boolean isJsonArray(String value); static List<String> arrayToJsonBeans(JsonNode json); static String jsonBeansToArray(List<?> jsonBeans); static String toPrettyString(Object value); static String toString(Object value); }### Answer: @Test public void jsonBeansToArray() { assertThat(JsonUtils.jsonBeansToArray(Collections.emptyList())).isEqualTo("[]"); assertThat(JsonUtils.jsonBeansToArray(Collections.singletonList("{\"foo\": \"bar\"}"))).isEqualTo("[{\"foo\": \"bar\"}]"); assertThat(JsonUtils.jsonBeansToArray(Arrays.asList("{\"foo1\": \"bar1\"}", "{\"foo2\": \"bar2\"}"))).isEqualTo("[{\"foo1\": \"bar1\"},{\"foo2\": \"bar2\"}]"); }
### Question: UnifiedDataShapeGenerator implements DataShapeGenerator<Oas30Document, Oas30Operation> { static boolean supports(final String mime, final Set<String> mimes) { if (mimes != null && !mimes.isEmpty()) { return mimes.contains(mime); } return false; } @Override DataShape createShapeFromRequest(final ObjectNode json, final Oas30Document openApiDoc, final Oas30Operation operation); @Override DataShape createShapeFromResponse(final ObjectNode json, final Oas30Document openApiDoc, final Oas30Operation operation); @Override List<OasResponse> resolveResponses(Oas30Document openApiDoc, List<OasResponse> operationResponses); }### Answer: @Test public void shouldDetermineSupportedMimes() { assertThat(supports(mime, mimes)).isEqualTo(outcome); }
### Question: Oas30ParameterGenerator extends OpenApiParameterGenerator<Oas30Document> { static String javaTypeFor(final Oas30Schema schema) { if (OasModelHelper.isArrayType(schema)) { final Oas30Schema items = (Oas30Schema) schema.items; final String elementType = items.type; final String elementFormat = items.format; return JsonSchemaHelper.javaTypeFor(elementType, elementFormat) + "[]"; } final String format = schema.format; return JsonSchemaHelper.javaTypeFor(schema.type, format); } }### Answer: @Test public void shouldCreatePropertyParametersFromPetstoreSwagger() throws IOException { final String specification = resource("/openapi/v3/petstore.json"); final Oas30Document openApiDoc = (Oas30Document) Library.readDocumentFromJSONString(specification); final Oas30Parameter petIdPathParameter = (Oas30Parameter) openApiDoc.paths.getPathItem("/pet/{petId}").get.getParameters().get(0); final Oas30Schema petIdSchema = Oas30ModelHelper.getSchema(petIdPathParameter).orElseThrow(IllegalStateException::new); final ConfigurationProperty configurationProperty = Oas30ParameterGenerator.createPropertyFromParameter(petIdPathParameter, petIdSchema.type, Oas30ParameterGenerator.javaTypeFor(petIdSchema), petIdSchema.default_, petIdSchema.enum_); final ConfigurationProperty expected = new ConfigurationProperty.Builder() .componentProperty(false) .deprecated(false) .description("ID of pet to return") .displayName("petId") .group("producer") .javaType(Long.class.getName()) .kind("property") .required(true) .secret(false) .type("integer") .build(); assertThat(configurationProperty).isEqualTo(expected); }
### Question: Oas30ModelHelper { static String getBasePath(Oas30Document openApiDoc) { if (openApiDoc.servers == null || openApiDoc.servers.isEmpty()) { return "/"; } return getBasePath(openApiDoc.servers.get(0)); } private Oas30ModelHelper(); static final String HTTP; }### Answer: @Test public void shouldGetBasePathFromServerDefinition() { Assertions.assertThat(Oas30ModelHelper.getBasePath(getOpenApiDocWithUrl(null))).isEqualTo("/"); Assertions.assertThat(Oas30ModelHelper.getBasePath(getOpenApiDocWithUrl(""))).isEqualTo("/"); Assertions.assertThat(Oas30ModelHelper.getBasePath(getOpenApiDocWithUrl("http: Assertions.assertThat(Oas30ModelHelper.getBasePath(getOpenApiDocWithUrl("http: Assertions.assertThat(Oas30ModelHelper.getBasePath(getOpenApiDocWithUrl("http: Assertions.assertThat(Oas30ModelHelper.getBasePath(getOpenApiDocWithUrl("https: Assertions.assertThat(Oas30ModelHelper.getBasePath(getOpenApiDocWithUrl("/v1"))).isEqualTo("/v1"); Assertions.assertThat(Oas30ModelHelper.getBasePath(getOpenApiDocWithUrl("http is awesome!"))).isEqualTo("/"); Assertions.assertThat(Oas30ModelHelper.getBasePath(getOpenApiDocWithUrl("{scheme}: variable("scheme", "http", "https"), variable("basePath", "v1", "v2")))).isEqualTo("/v1"); }
### Question: Labels { public static boolean isValid(String name) { return name.matches(VALID_VALUE_REGEX) && name.length() <= MAXIMUM_NAME_LENGTH; } private Labels(); static String sanitize(String name); static boolean isValid(String name); static String validate(String name); }### Answer: @Test public void testValid() { assertThat(Labels.isValid("abcdefghijklmnopqrstyvwxyz0123456789")).isTrue(); assertThat(Labels.isValid("012345678901234567890123456789012345678901234567890123456789123")).isTrue(); } @Test public void testInvalid() { assertThat(Labels.isValid("-abcdefghijklmnopqrstyvwxyz0123456789")).isFalse(); assertThat(Labels.isValid("abcdefghijklmnopqrstyvwxyz0123456789-")).isFalse(); assertThat(Labels.isValid("01234567890123456789012345678901234567890123456789012345678912345")).isFalse(); } @Test public void testValidateGeneratedKeys() { for (int i = 0; i < 1000; i++) { assertThat(Labels.isValid(KeyGenerator.createKey())).isTrue(); } }
### Question: Oas30ModelHelper { static String getScheme(Server server) { String serverUrl = resolveUrl(server); if (serverUrl.startsWith(HTTP)) { try { return new URL(serverUrl).getProtocol(); } catch (MalformedURLException e) { LOG.warn(String.format("Unable to determine base path from server URL: %s", serverUrl)); } } return HTTP; } private Oas30ModelHelper(); static final String HTTP; }### Answer: @Test public void shouldGetURLSchemeFromServerDefinition() { Assertions.assertThat(Oas30ModelHelper.getScheme(getServerWithUrl(null))).isEqualTo("http"); Assertions.assertThat(Oas30ModelHelper.getScheme(getServerWithUrl(""))).isEqualTo("http"); Assertions.assertThat(Oas30ModelHelper.getScheme(getServerWithUrl("http: Assertions.assertThat(Oas30ModelHelper.getScheme(getServerWithUrl("http: Assertions.assertThat(Oas30ModelHelper.getScheme(getServerWithUrl("https: Assertions.assertThat(Oas30ModelHelper.getScheme(getServerWithUrl("/v1"))).isEqualTo("http"); Assertions.assertThat(Oas30ModelHelper.getScheme(getServerWithUrl("http is awesome!"))).isEqualTo("http"); Assertions.assertThat(Oas30ModelHelper.getScheme(getServerWithUrl("Something completely different"))).isEqualTo("http"); Assertions.assertThat(Oas30ModelHelper.getScheme(getServerWithUrl("{scheme}: Assertions.assertThat(Oas30ModelHelper.getScheme(getServerWithUrl("{scheme}: }
### Question: Oas30ModelHelper { static String getHost(Oas30Document openApiDoc) { if (openApiDoc.servers == null || openApiDoc.servers.isEmpty()) { return null; } String serverUrl = resolveUrl(openApiDoc.servers.get(0)); if (serverUrl.startsWith(HTTP)) { try { return new URL(serverUrl).getHost(); } catch (MalformedURLException e) { LOG.warn(String.format("Unable to determine base path from server URL: %s", serverUrl)); } } return null; } private Oas30ModelHelper(); static final String HTTP; }### Answer: @Test public void shouldGetHostFromServerDefinition() { Assertions.assertThat(Oas30ModelHelper.getHost(getOpenApiDocWithUrl(null))).isNull(); Assertions.assertThat(Oas30ModelHelper.getHost(getOpenApiDocWithUrl(""))).isNull(); Assertions.assertThat(Oas30ModelHelper.getHost(getOpenApiDocWithUrl("http: Assertions.assertThat(Oas30ModelHelper.getHost(getOpenApiDocWithUrl("http: Assertions.assertThat(Oas30ModelHelper.getHost(getOpenApiDocWithUrl("https: Assertions.assertThat(Oas30ModelHelper.getHost(getOpenApiDocWithUrl("/v1"))).isNull(); Assertions.assertThat(Oas30ModelHelper.getHost(getOpenApiDocWithUrl("http is awesome!"))).isNull(); Assertions.assertThat(Oas30ModelHelper.getHost(getOpenApiDocWithUrl("Something completely different"))).isNull(); Assertions.assertThat(Oas30ModelHelper.getHost(getOpenApiDocWithUrl("{scheme}: Assertions.assertThat(Oas30ModelHelper.getHost(getOpenApiDocWithUrl("{scheme}: variable("scheme", "http", "https"), variable("host", "syndesis.io"), variable("basePath", "v1", "v2")))).isEqualTo("syndesis.io"); }
### Question: UnifiedDataShapeGenerator implements DataShapeGenerator<Oas20Document, Oas20Operation> { static boolean supports(final String mime, final List<String> defaultMimes, final List<String> mimes) { boolean supports = false; if (mimes != null && !mimes.isEmpty()) { supports = mimes.contains(mime); } if (defaultMimes != null && !defaultMimes.isEmpty()) { supports |= defaultMimes.contains(mime); } return supports; } @Override DataShape createShapeFromRequest(final ObjectNode json, final Oas20Document openApiDoc, final Oas20Operation operation); @Override DataShape createShapeFromResponse(final ObjectNode json, final Oas20Document openApiDoc, final Oas20Operation operation); }### Answer: @Test public void shouldDetermineSupportedMimes() { assertThat(supports(mime, defaultMimes, mimes)).isEqualTo(outcome); }
### Question: OpenApiConnectorGenerator extends ConnectorGenerator { @Override protected final String determineConnectorDescription(final ConnectorTemplate connectorTemplate, final ConnectorSettings connectorSettings) { final OasDocument openApiDoc = parseSpecification(connectorSettings, APIValidationContext.NONE).getModel(); final Info info = openApiDoc.info; if (info == null) { return super.determineConnectorDescription(connectorTemplate, connectorSettings); } final String description = info.description; if (description == null) { return super.determineConnectorDescription(connectorTemplate, connectorSettings); } return description; } OpenApiConnectorGenerator(final Connector baseConnector, final Supplier<String> operationIdGenerator); OpenApiConnectorGenerator(final Connector baseConnector); @Override final Connector generate(final ConnectorTemplate connectorTemplate, final ConnectorSettings connectorSettings); @Override final APISummary info(final ConnectorTemplate connectorTemplate, final ConnectorSettings connectorSettings); static final String SPECIFICATION; }### Answer: @Test public void shouldDetermineConnectorDescription() { final Oas20Document openApiDoc = new Oas20Document(); assertThat(generator.determineConnectorDescription(ApiConnectorTemplate.SWAGGER_TEMPLATE, createSettingsFrom(openApiDoc))) .isEqualTo("unspecified"); final Oas20Info info = (Oas20Info) openApiDoc.createInfo(); openApiDoc.info = info; assertThat(generator.determineConnectorDescription(ApiConnectorTemplate.SWAGGER_TEMPLATE, createSettingsFrom(openApiDoc))) .isEqualTo("unspecified"); info.description = "description"; assertThat(generator.determineConnectorDescription(ApiConnectorTemplate.SWAGGER_TEMPLATE, createSettingsFrom(openApiDoc))) .isEqualTo("description"); }
### Question: OpenApiConnectorGenerator extends ConnectorGenerator { @Override protected final String determineConnectorName(final ConnectorTemplate connectorTemplate, final ConnectorSettings connectorSettings) { final OpenApiModelInfo modelInfo = parseSpecification(connectorSettings, APIValidationContext.NONE); if (!modelInfo.getErrors().isEmpty()) { throw new IllegalArgumentException("Given OpenAPI specification contains errors: " + modelInfo); } final OasDocument openApiDoc = modelInfo.getModel(); final Info info = openApiDoc.info; if (info == null) { return super.determineConnectorName(connectorTemplate, connectorSettings); } final String title = info.title; if (title == null) { return super.determineConnectorName(connectorTemplate, connectorSettings); } return title; } OpenApiConnectorGenerator(final Connector baseConnector, final Supplier<String> operationIdGenerator); OpenApiConnectorGenerator(final Connector baseConnector); @Override final Connector generate(final ConnectorTemplate connectorTemplate, final ConnectorSettings connectorSettings); @Override final APISummary info(final ConnectorTemplate connectorTemplate, final ConnectorSettings connectorSettings); static final String SPECIFICATION; }### Answer: @Test public void shouldDetermineConnectorName() { final Oas20Document openApiDoc = new Oas20Document(); assertThat(generator.determineConnectorName(ApiConnectorTemplate.SWAGGER_TEMPLATE, createSettingsFrom(openApiDoc))).isEqualTo("unspecified"); final Oas20Info info = (Oas20Info) openApiDoc.createInfo(); openApiDoc.info = info; assertThat(generator.determineConnectorName(ApiConnectorTemplate.SWAGGER_TEMPLATE, createSettingsFrom(openApiDoc))).isEqualTo("unspecified"); info.title = "title"; assertThat(generator.determineConnectorName(ApiConnectorTemplate.SWAGGER_TEMPLATE, createSettingsFrom(openApiDoc))).isEqualTo("title"); }
### Question: Strings { public static boolean isEmptyOrBlank(final String given) { if (given == null || given.isEmpty()) { return true; } final int len = given.length(); for (int i = 0; i < len; i++) { final char ch = given.charAt(i); if (!Character.isWhitespace(ch)) { return false; } } return true; } private Strings(); static boolean isEmptyOrBlank(final String given); static String truncate(final String name, final int max); static String utf8(final byte[] data); }### Answer: @Test public void shouldFindBlankStringsAsEmpty() { assertThat(Strings.isEmptyOrBlank(" \t\r\n")).isTrue(); } @Test public void shouldFindEmptyStringsAsEmpty() { assertThat(Strings.isEmptyOrBlank("")).isTrue(); } @Test public void shouldFindNonEmptyStringsAsNonEmpty() { assertThat(Strings.isEmptyOrBlank("a")).isFalse(); } @Test public void shouldFindNonEmptyStringsWithWhitespaceAsNonEmpty() { assertThat(Strings.isEmptyOrBlank(" \na\t")).isFalse(); } @Test public void shouldFindNullStringsAsEmpty() { assertThat(Strings.isEmptyOrBlank(null)).isTrue(); }
### Question: OpenApiConnectorGenerator extends ConnectorGenerator { static OpenApiModelInfo parseSpecification(final ConnectorSettings connectorSettings, final APIValidationContext validationContext) { final String specification = requiredSpecification(connectorSettings); return OpenApiModelParser.parse(specification, validationContext); } OpenApiConnectorGenerator(final Connector baseConnector, final Supplier<String> operationIdGenerator); OpenApiConnectorGenerator(final Connector baseConnector); @Override final Connector generate(final ConnectorTemplate connectorTemplate, final ConnectorSettings connectorSettings); @Override final APISummary info(final ConnectorTemplate connectorTemplate, final ConnectorSettings connectorSettings); static final String SPECIFICATION; }### Answer: @Test public void shouldParseSpecificationWithSecurityRequirements() { final OpenApiModelInfo info = OpenApiConnectorGenerator.parseSpecification(new ConnectorSettings.Builder() .putConfiguredProperty("specification", "{\"swagger\":\"2.0\",\"paths\":{\"/api\":{\"get\":{\"security\":[{\"secured\":[]}]}}}}") .build(), APIValidationContext.CONSUMED_API); final Oas20Document model = info.getV2Model(); assertThat(model.paths.getPathItem("/api").get.security).hasSize(1); assertThat(model.paths.getPathItem("/api").get.security.get(0).getSecurityRequirementNames()).containsExactly("secured"); assertThat(model.paths.getPathItem("/api").get.security.get(0).getScopes("secured")).isEmpty(); final String resolvedSpecification = info.getResolvedSpecification(); assertThatJson(resolvedSpecification).isEqualTo("{\"swagger\":\"2.0\",\"paths\":{\"/api\":{\"get\":{\"security\":[{\"secured\":[]}]}}}}"); final ObjectNode resolvedJsonGraph = info.getResolvedJsonGraph(); final JsonNode securityRequirement = resolvedJsonGraph.get("paths").get("/api").get("get").get("security"); assertThat(securityRequirement).hasSize(1); assertThat(securityRequirement.get(0).get("secured")).isEmpty(); }
### Question: UniquePropertyValidator implements ConstraintValidator<UniqueProperty, WithId<?>> { @Override public boolean isValid(final WithId<?> value, final ConstraintValidatorContext context) { if (value == null) { return true; } final PropertyAccessor bean = new BeanWrapperImpl(value); final String propertyValue = String.valueOf(bean.getPropertyValue(property)); @SuppressWarnings({"rawtypes", "unchecked"}) final Class<WithId> modelClass = (Class) value.getKind().modelClass; @SuppressWarnings("unchecked") final Set<String> ids = dataManager.fetchIdsByPropertyValue(modelClass, property, propertyValue); final boolean isUnique = ids.isEmpty() || value.getId().map(id -> ids.contains(id)).orElse(false); if (!isUnique) { context.disableDefaultConstraintViolation(); context.unwrap(HibernateConstraintValidatorContext.class).addExpressionVariable("nonUnique", propertyValue) .buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()) .addPropertyNode(property).addConstraintViolation(); } return isUnique; } @Override void initialize(final UniqueProperty uniqueProperty); @Override boolean isValid(final WithId<?> value, final ConstraintValidatorContext context); }### Answer: @Test public void shouldAscertainPropertyUniqueness() { final HibernateConstraintValidatorContext context = mock(HibernateConstraintValidatorContext.class); when(context.unwrap(HibernateConstraintValidatorContext.class)).thenReturn(context); when(context.addExpressionVariable(eq("nonUnique"), anyString())).thenReturn(context); when(context.getDefaultConstraintMessageTemplate()).thenReturn("template"); final ConstraintViolationBuilder builder = mock(ConstraintViolationBuilder.class); when(context.buildConstraintViolationWithTemplate("template")).thenReturn(builder); when(builder.addPropertyNode(anyString())).thenReturn(mock(NodeBuilderCustomizableContext.class)); assertThat(validator.isValid(connection, context)).isEqualTo(validity); }
### Question: RelativeUriValidator implements ConstraintValidator<RelativeUri, URI> { @Override public boolean isValid(final URI value, final ConstraintValidatorContext context) { return value != null && !value.isAbsolute(); } @Override void initialize(final RelativeUri constraintAnnotation); @Override boolean isValid(final URI value, final ConstraintValidatorContext context); }### Answer: @Test public void nullUrisShouldBeInvalid() { assertThat(validator.isValid(null, null)).isFalse(); } @Test public void shouldAllowRelativeUris() { assertThat(validator.isValid(URI.create("/relative"), null)).isTrue(); } @Test public void shouldNotAllowNonRelativeUris() { assertThat(validator.isValid(URI.create("scheme:/absolute"), null)).isFalse(); }
### Question: CredentialFlowStateHelper { static javax.ws.rs.core.Cookie toJaxRsCookie(final Cookie cookie) { return new javax.ws.rs.core.Cookie(cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getDomain()); } private CredentialFlowStateHelper(); }### Answer: @Test public void shouldConvertServletCookieToJaxRsCookie() { final Cookie given = new Cookie("myCookie", "myValue"); given.setDomain("example.com"); given.setPath("/path"); given.setMaxAge(1800); given.setHttpOnly(true); given.setSecure(true); final javax.ws.rs.core.Cookie expected = new javax.ws.rs.core.Cookie("myCookie", "myValue", "/path", "example.com"); assertThat(CredentialFlowStateHelper.toJaxRsCookie(given)).isEqualTo(expected); }
### Question: OAuth1CredentialProvider extends BaseCredentialProvider { @Override public AcquisitionMethod acquisitionMethod() { return new AcquisitionMethod.Builder() .label(labelFor(id)) .icon(iconFor(id)) .type(Type.OAUTH1) .description(descriptionFor(id)) .configured(configured) .build(); } OAuth1CredentialProvider(final String id); OAuth1CredentialProvider(final String id, final OAuth1ConnectionFactory<A> connectionFactory, final Applicator<OAuthToken> applicator); private OAuth1CredentialProvider(final String id, final OAuth1ConnectionFactory<A> connectionFactory, final Applicator<OAuthToken> applicator, final boolean configured); @Override AcquisitionMethod acquisitionMethod(); @Override Connection applyTo(final Connection connection, final CredentialFlowState givenFlowState); @Override CredentialFlowState finish(final CredentialFlowState givenFlowState, final URI baseUrl); @Override String id(); @Override CredentialFlowState prepare(final String connectorId, final URI baseUrl, final URI returnUrl); }### Answer: @Test public void shouldCreateAcquisitionMethod() { @SuppressWarnings("unchecked") final OAuth1CredentialProvider<?> oauth1 = new OAuth1CredentialProvider<>("provider1", mock(OAuth1ConnectionFactory.class), mock(Applicator.class)); final AcquisitionMethod method1 = new AcquisitionMethod.Builder() .description("provider1") .label("provider1") .icon("provider1") .type(Type.OAUTH1) .configured(true) .build(); assertThat(oauth1.acquisitionMethod()).isEqualTo(method1); }
### Question: BaseCredentialProvider implements CredentialProvider { protected static String callbackUrlFor(final URI baseUrl, final MultiValueMap<String, String> additionalParams) { final String path = baseUrl.getPath(); final String callbackPath = path + "credentials/callback"; try { final URI base = new URI(baseUrl.getScheme(), null, baseUrl.getHost(), baseUrl.getPort(), callbackPath, null, null); return UriComponentsBuilder.fromUri(base).queryParams(additionalParams).build().toUriString(); } catch (final URISyntaxException e) { throw new IllegalStateException("Unable to generate callback URI", e); } } }### Answer: @Test public void shouldGenerateCallbackUrlWithoutParameters() { assertThat(BaseCredentialProvider.callbackUrlFor(URI.create("https: .as("The computed callback URL is not as expected") .isEqualTo("https: } @Test public void shouldGenerateCallbackUrlWithParameters() { final MultiValueMap<String, String> some = new LinkedMultiValueMap<>(); some.set("param1", "value1"); some.set("param2", "value2"); assertThat(BaseCredentialProvider.callbackUrlFor(URI.create("https: .as("The computed callback URL is not as expected") .isEqualTo("https: }
### Question: OAuth2CredentialProvider extends BaseCredentialProvider { @Override public AcquisitionMethod acquisitionMethod() { return new AcquisitionMethod.Builder() .label(labelFor(id)) .icon(iconFor(id)) .type(Type.OAUTH2) .description(descriptionFor(id)) .configured(configured) .build(); } OAuth2CredentialProvider(final String id); OAuth2CredentialProvider(final String id, final OAuth2ConnectionFactory<S> connectionFactory, final Applicator<AccessGrant> applicator, final Map<String, String> additionalQueryParameters); private OAuth2CredentialProvider(final String id, final OAuth2ConnectionFactory<S> connectionFactory, final Applicator<AccessGrant> applicator, final Map<String, String> additionalQueryParameters, final boolean configured); @Override AcquisitionMethod acquisitionMethod(); @Override Connection applyTo(final Connection connection, final CredentialFlowState givenFlowState); @Override CredentialFlowState finish(final CredentialFlowState givenFlowState, final URI baseUrl); @Override String id(); @Override CredentialFlowState prepare(final String connectorId, final URI baseUrl, final URI returnUrl); }### Answer: @Test public void shouldCreateAcquisitionMethod() { @SuppressWarnings("unchecked") final OAuth2CredentialProvider<?> oauth2 = new OAuth2CredentialProvider<>("provider2", mock(OAuth2ConnectionFactory.class), mock(Applicator.class), Collections.emptyMap()); final AcquisitionMethod method2 = new AcquisitionMethod.Builder() .description("provider2") .label("provider2") .icon("provider2") .type(Type.OAUTH2) .configured(true) .build(); assertThat(oauth2.acquisitionMethod()).isEqualTo(method2); }
### Question: StaticResourceClassInspector extends DataMapperBaseInspector<Void> { @Override protected String fetchJsonFor(final String fullyQualifiedName, final Context<Void> context) throws IOException { final String path = PREFIX + fullyQualifiedName + SUFFIX; final Resource[] resources = resolver.getResources(path); if (resources.length == 0) { throw new FileNotFoundException(path); } final Resource resource = resources[0]; try (InputStream in = resource.getInputStream()) { return IOUtils.toString(in, StandardCharsets.UTF_8); } } @Autowired StaticResourceClassInspector(final ResourceLoader loader); }### Answer: @Test public void shouldFetchFromStaticResource() throws Exception { final String json = new StaticResourceClassInspector(new DefaultResourceLoader()).fetchJsonFor("twitter4j.Status", null); assertThat(json).isNotEmpty(); }
### Question: JsonSchemaInspector implements Inspector { static void fetchPaths(final String context, final List<String> paths, final Map<String, JsonSchema> properties) { for (final Map.Entry<String, JsonSchema> entry : properties.entrySet()) { final JsonSchema subschema = entry.getValue(); String path; final String key = entry.getKey(); if (context == null) { path = key; } else { path = context + "." + key; } if (subschema.isValueTypeSchema()) { paths.add(path); } else if (subschema.isObjectSchema()) { fetchPaths(path, paths, subschema.asObjectSchema().getProperties()); } else if (subschema.isArraySchema()) { COLLECTION_PATHS.stream().map(p -> path + "." + p).forEach(paths::add); ObjectSchema itemSchema = getItemSchema(subschema.asArraySchema()); if (itemSchema != null) { fetchPaths(path + ARRAY_CONTEXT, paths, itemSchema.getProperties()); } } } } @Override List<String> getPaths(final String kind, final String type, final String specification, final Optional<byte[]> exemplar); @Override boolean supports(final String kind, final String type, final String specification, final Optional<byte[]> exemplar); }### Answer: @Test public void shouldFetchPathsFromJsonSchema() throws IOException { final ObjectSchema schema = mapper.readValue(getSalesForceContactSchema(), ObjectSchema.class); final List<String> paths = new ArrayList<>(); JsonSchemaInspector.fetchPaths(null, paths, schema.getProperties()); assertSalesforceContactProperties(paths); } @Test public void shouldFetchPathsWithNestedArraySchema() throws IOException { final ObjectSchema schema = mapper.readValue(getSchemaWithNestedArray(), ObjectSchema.class); final List<String> paths = new ArrayList<>(); JsonSchemaInspector.fetchPaths(null, paths, schema.getProperties()); assertThat(paths).hasSize(4); assertThat(paths).containsAll(Arrays.asList("Id", "PhoneNumbers.size()", "PhoneNumbers[].Name", "PhoneNumbers[].Number")); }
### Question: SpecificationClassInspector extends DataMapperBaseInspector<JsonNode> { @Override protected String fetchJsonFor(final String fullyQualifiedName, final Context<JsonNode> context) throws IOException { final JsonNode classNode = findClassNode(fullyQualifiedName, context.getState()); final JsonNode javaClass = JsonNodeFactory.instance.objectNode().set("JavaClass", classNode); return JsonUtils.writer().writeValueAsString(javaClass); } @Autowired SpecificationClassInspector(); }### Answer: @Test public void shouldFindNestedClassesWithinFullJson() throws IOException { final SpecificationClassInspector inspector = new SpecificationClassInspector(); final String specification = read("/twitter4j.Status.full.json"); final Context<JsonNode> context = new Context<>(JsonUtils.reader().readTree(specification)); final String json = inspector.fetchJsonFor("twitter4j.GeoLocation", context); assertThatJson(json).isEqualTo(read("/twitter4j.GeoLocation.json")); }
### Question: UsageUpdateHandler implements ResourceUpdateHandler { void processInternal(final ChangeEvent event) { LOG.debug("Processing event: {}", event); final ListResult<Integration> integrationsResult = dataManager.fetchAll(Integration.class); final List<Integration> integrations = integrationsResult.getItems(); updateUsageFor(Connection.class, integrations, Integration::getConnectionIds, Functions.compose(Optional::get, Connection::getId), UsageUpdateHandler::withUpdatedUsage); updateUsageFor(Extension.class, integrations, Integration::getExtensionIds, Extension::getExtensionId, UsageUpdateHandler::withUpdatedUsage); } UsageUpdateHandler(final DataManager dataManager); @Override boolean canHandle(final ChangeEvent event); @Override void process(final ChangeEvent event); }### Answer: @Test public void unusedConnectionsShouldHaveUseOfZero() { final Integration emptyIntegration = new Integration.Builder().build(); when(dataManager.fetchAll(Integration.class)).thenReturn(ListResult.of(emptyIntegration, emptyIntegration)); handler.processInternal(NOT_USED); verify(dataManager).fetchAll(Integration.class); verify(dataManager).fetchAll(Connection.class); verify(dataManager).fetchAll(Extension.class); verifyNoMoreInteractions(dataManager); } @Test public void withNoIntegrationsConnectionUsageShouldBeZero() { when(dataManager.fetchAll(Integration.class)).thenReturn(ListResult.of(emptyList())); handler.processInternal(NOT_USED); verify(dataManager).fetchAll(Integration.class); verify(dataManager).fetchAll(Connection.class); verify(dataManager).fetchAll(Extension.class); verifyNoMoreInteractions(dataManager); }
### Question: ResourceUpdateController { CompletableFuture<Void> onEventInternal(final String event, final String data) { if (!running.get()) { return CompletableFuture.completedFuture(null); } if (!Objects.equals(event, EventBus.Type.CHANGE_EVENT)) { return CompletableFuture.completedFuture(null); } final ChangeEvent changeEvent; try { changeEvent = JsonUtils.reader().forType(ChangeEvent.class).readValue(data); } catch (final IOException e) { LOGGER.error("Error while processing change-event {}", data, e); final CompletableFuture<Void> errored = new CompletableFuture<>(); errored.completeExceptionally(e); return errored; } final CompletableFuture<Void> done = new CompletableFuture<>(); if (changeEvent != null) { scheduler.execute(() -> run(changeEvent, done)); } return done; } @Autowired ResourceUpdateController(final ResourceUpdateConfiguration configuration, final EventBus eventBus, final List<ResourceUpdateHandler> handlers); void start(); void stop(); }### Answer: @Test public void shouldProcessEvents() throws InterruptedException, ExecutionException, TimeoutException { reset(handlers); for (final ResourceUpdateHandler handler : handlers) { when(handler.canHandle(event)).thenReturn(true); } final CompletableFuture<Void> processed = controller.onEventInternal(EventBus.Type.CHANGE_EVENT, JsonUtils.toString(event)); processed.get(1, TimeUnit.SECONDS); for (final ResourceUpdateHandler handler : handlers) { verify(handler).process(event); } }
### Question: Threads { public static ThreadFactory newThreadFactory(final String groupName) { return new ThreadFactory() { @SuppressWarnings("PMD.AvoidThreadGroup") final ThreadGroup initialization = new ThreadGroup(groupName); final AtomicInteger threadNumber = new AtomicInteger(-1); @Override public Thread newThread(final Runnable task) { final Thread thread = new Thread(initialization, task); thread.setName(groupName + "-" + threadNumber.incrementAndGet()); final Logger log = LoggerFactory.getLogger(task.getClass()); thread.setUncaughtExceptionHandler(new Logging(log)); return thread; } }; } private Threads(); static ThreadFactory newThreadFactory(final String groupName); }### Answer: @Test public void shouldCreateThreadFactories() { final ThreadFactory newThreadFactory = Threads.newThreadFactory("test name"); final Thread thread = newThreadFactory.newThread(System::gc); assertThat(thread.getThreadGroup().getName()).isEqualTo("test name"); assertThat(thread.getName()).isEqualTo("test name-0"); }
### Question: LRUCacheManager implements CacheManager { @SuppressWarnings("unchecked") @Override public <K, V> Cache<K, V> getCache(final String name, boolean soft) { Cache<K, V> cache = (Cache<K, V>) caches.computeIfAbsent(name, n -> this.newCache(soft)); if ((soft && !(cache instanceof LRUSoftCache)) || (!soft && (cache instanceof LRUSoftCache))) { LOG.warn("Cache {} is being used in mixed 'soft' and 'hard' mode", name); } return cache; } LRUCacheManager(final int maxElements); @Override void evictAll(); @SuppressWarnings("unchecked") @Override Cache<K, V> getCache(final String name, boolean soft); }### Answer: @Test public void testEviction() { CacheManager manager = new LRUCacheManager(2); Cache<String, Object> cache = manager.getCache("cache", this.soft); String one = "1"; String two = "2"; String three = "3"; cache.put(one, one); cache.put(two, two); cache.put(three, three); assertThat(cache.size()).isEqualTo(2); assertThat(cache.get(one)).isNull(); assertThat(cache.get(two)).isNotNull(); assertThat(cache.get(three)).isNotNull(); } @Test public void testIdentity() { CacheManager manager = new LRUCacheManager(2); Cache<String, String> cache1 = manager.getCache("cache", this.soft); Cache<String, String> cache2 = manager.getCache("cache", this.soft); Cache<String, String> cache3 = manager.getCache("cache", !this.soft); assertThat(cache1).isEqualTo(cache2); assertThat(cache1).isEqualTo(cache3); }
### Question: FilterUtil { public static List<String> extractParameters(String filter) { List<String> result = new ArrayList<>(); Matcher matcher = PARAM_PATTERN.matcher(filter); while (matcher.find()) { String param = matcher.group(); result.add(param.substring(2)); } return result; } private FilterUtil(); static List<String> extractParameters(String filter); static boolean hasAnyParameter(String filter); static String merge(String filter, String jsonMessage); }### Answer: @Test public void verifySimpleFilterInputParameterExtraction() { String filterExpression = "{test: :#test, test2: \":#someParam\", test3: /:#regexParam/}"; List<String> result = FilterUtil.extractParameters(filterExpression); Assertions.assertThat(result).containsExactly("test", "someParam", "regexParam"); } @Test public void verifyComplexFilterInputParameterExtraction() { String filterExpression = "{ '$or' => [ {a => :#p1 }, { b => :#p2 } ] }"; List<String> result = FilterUtil.extractParameters(filterExpression); Assertions.assertThat(result).containsExactly("p1", "p2"); }
### Question: IntegrationRouteLoader implements SourceLoader { public IntegrationRouteLoader() { } IntegrationRouteLoader(); IntegrationRouteLoader(ActivityTracker activityTracker, Set<IntegrationStepHandler> integrationStepHandlers, Tracer tracer); @Override List<String> getSupportedLanguages(); @Override Result load(Runtime runtime, Source source); }### Answer: @Test public void integrationRouteLoaderTest() throws Exception { IntegrationRouteLoader irl = new IntegrationRouteLoader(); TestRuntime runtime = new TestRuntime(); irl.load(runtime, Sources.fromURI("classpath:/syndesis/integration/integration.syndesis?language=syndesis")); assertThat(runtime.builders).hasSize(1); final RoutesBuilder routeBuilder = runtime.builders.get(0); assertThat(routeBuilder).isInstanceOf(RouteBuilder.class); RouteBuilder rb = (RouteBuilder) routeBuilder; rb.configure(); final RoutesDefinition routeCollection = rb.getRouteCollection(); final List<RouteDefinition> routes = routeCollection.getRoutes(); assertThat(routes).hasSize(1); final RouteDefinition route = routes.get(0); final FromDefinition input = route.getInput(); assertThat(input).isNotNull(); assertThat(input.getEndpointUri()).isEqualTo("direct:expression"); }
### Question: DebeziumConsumerCustomizer implements ComponentProxyCustomizer, CamelContextAware { @Override public void customize(final ComponentProxyComponent component, final Map<String, Object> options) { kafkaConnectionCustomizer.customize(component, options); component.setBeforeConsumer(DebeziumConsumerCustomizer::convertToDebeziumFormat); } DebeziumConsumerCustomizer(CamelContext context); @Override CamelContext getCamelContext(); @Override final void setCamelContext(CamelContext camelContext); @Override void customize(final ComponentProxyComponent component, final Map<String, Object> options); static final String DEBEZIUM_OPERATION; }### Answer: @Test public void shouldIncludeKafkaCustomizerOptions() { ComponentProxyComponent mockComponent = mock(ComponentProxyComponent.class); DebeziumConsumerCustomizer debeziumCustomizer = new DebeziumConsumerCustomizer(new DefaultCamelContext()); Map<String, Object> userOptions = new HashMap<>(); userOptions.put("brokers","1.2.3.4:9093"); userOptions.put("transportProtocol","TSL"); userOptions.put("brokerCertificate",SAMPLE_CERTIFICATE); debeziumCustomizer.customize(mockComponent, userOptions); assertThat(userOptions.get("configuration")).isNotNull(); }
### Question: DebeziumMySQLDatashapeStrategy implements DebeziumDatashapeStrategy { static String buildJsonSchema(final String tableName, final List<String> properties) { final StringBuilder jsonSchemaBuilder = new StringBuilder("{\"$schema\": \"http: .append(tableName) .append("\",\"type\": \"object\",\"properties\": {"); final StringJoiner joiner = new StringJoiner(","); for (final String property : properties) { joiner.add(property); } return jsonSchemaBuilder.append(joiner.toString()) .append("}}") .toString(); } @Override DataShape getDatashape(Map<String, Object> params); }### Answer: @Test public void shouldBuildJsonSchema() { final String generated = DebeziumMySQLDatashapeStrategy.buildJsonSchema("table", Arrays.asList("\"prop1\":{\"type\":\"string\"}", "\"prop2\":{\"type\":\"string\"}", "\"prop3\":{\"type\":\"string\"}")); final String expected = "{\n" + " \"$schema\":\"http: " \"title\":\"table\",\n" + " \"type\":\"object\",\n" + " \"properties\":{\n" + " \"prop1\":{\n" + " \"type\":\"string\"\n" + " },\n" + " \"prop2\":{\n" + " \"type\":\"string\"\n" + " },\n" + " \"prop3\":{\n" + " \"type\":\"string\"\n" + " }\n" + " }\n" + "}"; assertThatJson(generated).isEqualTo(expected); }
### Question: SyndesisHeaderStrategy extends HttpHeaderFilterStrategy { @Override public boolean applyFilterToCamelHeaders(final String headerName, final Object headerValue, final Exchange exchange) { if (isWhitelisted(exchange, headerName)) { return false; } return super.applyFilterToCamelHeaders(headerName, headerValue, exchange); } @Override boolean applyFilterToCamelHeaders(final String headerName, final Object headerValue, final Exchange exchange); static boolean isWhitelisted(final Exchange exchange, String headerName); static void whitelist(final Exchange exchange, final Collection<String> headerNames); static void whitelist(final Exchange exchange, final String headerName); static final SyndesisHeaderStrategy INSTANCE; static final String WHITELISTED_HEADERS; }### Answer: @Test public void shouldFilterOutEverythingButInwardContentTypeHeader() { final SyndesisHeaderStrategy headerStrategy = new SyndesisHeaderStrategy(); assertThat(headerStrategy.applyFilterToCamelHeaders("Content-Type", "", exchange)).isTrue(); assertThat(headerStrategy.applyFilterToExternalHeaders("Content-Type", "", exchange)).isFalse(); assertThat(headerStrategy.applyFilterToCamelHeaders("Host", "", exchange)).isTrue(); assertThat(headerStrategy.applyFilterToExternalHeaders("Host", "", exchange)).isTrue(); assertThat(headerStrategy.applyFilterToCamelHeaders("Forward", "", exchange)).isTrue(); assertThat(headerStrategy.applyFilterToExternalHeaders("Forward", "", exchange)).isTrue(); }
### Question: GoogleCalendarEventsCustomizer implements ComponentProxyCustomizer { static void beforeConsumer(Exchange exchange) { final Message in = exchange.getIn(); final Event event = exchange.getIn().getBody(Event.class); GoogleCalendarEventModel model = GoogleCalendarEventModel.newFrom(event); in.setBody(model); } @Override void customize(ComponentProxyComponent component, Map<String, Object> options); }### Answer: @Test public void shouldConvertGoogleEventToConnectorEventModel() { DefaultCamelContext cc = new DefaultCamelContext(); Exchange exchange = new DefaultExchange(cc); Message in = new DefaultMessage(cc); in.setBody(new Event()); exchange.setIn(in); GoogleCalendarEventsCustomizer.beforeConsumer(exchange); Object body = in.getBody(); assertThat(body).isInstanceOf(GoogleCalendarEventModel.class); }
### Question: GoogleCalendarUtils { static String formatAtendees(final List<EventAttendee> attendees) { if (attendees == null || attendees.isEmpty()) { return null; } return attendees.stream() .map(EventAttendee::getEmail) .collect(Collectors.joining(",")); } private GoogleCalendarUtils(); }### Answer: @Test public void shouldFormatEmptyAtendees() { assertThat(GoogleCalendarUtils.formatAtendees(Collections.emptyList())).isNull(); } @Test public void shouldFormatNullAtendees() { assertThat(GoogleCalendarUtils.formatAtendees(null)).isNull(); }
### Question: GoogleCalendarUtils { static List<EventAttendee> parseAtendees(final String attendeesString) { if (ObjectHelper.isEmpty(attendeesString)) { return Collections.emptyList(); } return Splitter.on(',').trimResults().splitToList(attendeesString) .stream() .map(GoogleCalendarUtils::attendee) .collect(Collectors.toList()); } private GoogleCalendarUtils(); }### Answer: @Test public void shouldParseBlankAtendees() { assertThat(GoogleCalendarUtils.parseAtendees(" ")).isEmpty(); } @Test public void shouldParseEmptyAtendees() { assertThat(GoogleCalendarUtils.parseAtendees("")).isEmpty(); } @Test public void shouldParseNullAtendees() { assertThat(GoogleCalendarUtils.parseAtendees(null)).isEmpty(); }
### Question: JsonSimplePredicate implements Predicate { @SuppressWarnings("JdkObsolete") static String convertSimpleToOGNLForMaps(final String simple) { final Matcher matcher = SIMPLE_EXPRESSION.matcher(simple); final StringBuffer ognl = new StringBuffer(simple.length() + 5); while (matcher.find()) { final String expression = toOgnl(matcher); matcher.appendReplacement(ognl, "\\$\\{" + expression + "\\}"); } matcher.appendTail(ognl); return ognl.toString(); } JsonSimplePredicate(final String expression, final CamelContext context); @Override @SuppressFBWarnings({"NP_LOAD_OF_KNOWN_NULL_VALUE", "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"}) // https://github.com/spotbugs/spotbugs/issues/868 though this code is fishy (TODO) boolean matches(final Exchange exchange); }### Answer: @Test @Parameters({"2 == 1, 2 == 1", "${body.prop} == 1, ${body[prop]} == 1", "${body.prop} == 1 OR ${body.fr_op.gl$op.ml0op[3]} == '2.4', ${body[prop]} == 1 OR ${body[fr_op][gl$op][ml0op][3]} == '2.4'"}) public void shouldConvertSimpleExpressionsToOgnl(final String simple, final String ognl) { assertThat(convertSimpleToOGNLForMaps(simple)).isEqualTo(ognl); }
### Question: GoogleCalendarEventModel { public static GoogleCalendarEventModel newFrom(final Event event) { final GoogleCalendarEventModel model = new GoogleCalendarEventModel(); if (event == null) { return model; } model.title = StringHelper.trimToNull(event.getSummary()); model.description = StringHelper.trimToNull(event.getDescription()); model.attendees = formatAtendees(event.getAttendees()); model.setStart(event.getStart()); model.setEnd(event.getEnd()); model.location = StringHelper.trimToNull(event.getLocation()); model.eventId = StringHelper.trimToNull(event.getId()); return model; } String getTitle(); void setTitle(String title); String getDescription(); void setDescription(String description); String getAttendees(); void setAttendees(String attendees); String getStartDate(); void setStartDate(String startDate); String getStartTime(); void setStartTime(String startTime); String getEndDate(); void setEndDate(String endDate); String getEndTime(); void setEndTime(String endTime); String getLocation(); void setLocation(String location); String getEventId(); void setEventId(String eventId); @Override String toString(); static GoogleCalendarEventModel newFrom(final Event event); }### Answer: @Test public void createsConnectorModelFromTrivialGoogleModel() { final Event googleModel = new Event(); final GoogleCalendarEventModel eventModel = GoogleCalendarEventModel.newFrom(googleModel); assertThat(eventModel).isEqualToComparingFieldByField(new GoogleCalendarEventModel()); } @Test public void newModelFromNullIsValid() { final GoogleCalendarEventModel eventModel = GoogleCalendarEventModel.newFrom(null); assertThat(eventModel).isEqualToComparingFieldByField(new GoogleCalendarEventModel()); }
### Question: JSONBeanUtil { @SuppressWarnings("unchecked") public static String toJSONBean(final List<Object> list) { String json = null; if (list.size() == 1) { final Map<String, Object> map = (Map<String, Object>) list.get(0); json = JSONBeanUtil.toJSONBean(map); } else if (list.size() > 1) { final StringBuilder stringBuilder = new StringBuilder("["); for (int i = 0; i < list.size(); i++) { final Map<String, Object> map = (Map<String, Object>) list.get(i); stringBuilder.append(JSONBeanUtil.toJSONBean(map)); if (i < list.size() - 1) { stringBuilder.append(','); } } stringBuilder.append(']'); json = stringBuilder.toString(); } return json; } private JSONBeanUtil(); static Properties parsePropertiesFromJSONBean(final String json); static Map<String, SqlParameterValue> parseSqlParametersFromJSONBean(final String json, final Map<String, Integer> jdbcTypeMap); @SuppressWarnings("unchecked") static String toJSONBean(final List<Object> list); static String toJSONBean(final Map<String, Object> map); static List<String> toJSONBeans(Message in); static List<String> toJSONBeansFromHeader(Message in, String autoIncrementColumnName); }### Answer: @Test public void mapToJsonBeanTest() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); final SimpleOutputBean bean = new SimpleOutputBean(); bean.setC(50); final String jsonBeanExpected = mapper.writeValueAsString(bean); final Map<String, Object> map = new HashMap<>(); map.put("c", 50); map.put("#update-count-1", 0); final String jsonBeanActual = JSONBeanUtil.toJSONBean(map); Assert.assertEquals(jsonBeanExpected, jsonBeanActual); }
### Question: JSONBeanUtil { public static Properties parsePropertiesFromJSONBean(final String json) { final Map<String, String> parsed; try { parsed = MAPPER.readerFor(STRING_STRING_MAP).readValue(json); } catch (final IOException e) { throw new IllegalArgumentException("Unable to parse given JSON", e); } final Properties ret = new Properties(); if (parsed != null) { parsed.entrySet().stream() .filter(e -> e.getKey() != null && e.getValue() != null) .forEach(e -> ret.put(e.getKey(), e.getValue())); } return ret; } private JSONBeanUtil(); static Properties parsePropertiesFromJSONBean(final String json); static Map<String, SqlParameterValue> parseSqlParametersFromJSONBean(final String json, final Map<String, Integer> jdbcTypeMap); @SuppressWarnings("unchecked") static String toJSONBean(final List<Object> list); static String toJSONBean(final Map<String, Object> map); static List<String> toJSONBeans(Message in); static List<String> toJSONBeansFromHeader(Message in, String autoIncrementColumnName); }### Answer: @Test public void parsePropertiesFromJSONBeanTest() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); final SimpleInputBean bean = new SimpleInputBean(); bean.setA(20); bean.setB(30); final String jsonBean = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean); final Properties properties = JSONBeanUtil.parsePropertiesFromJSONBean(jsonBean); Assert.assertTrue(properties.containsKey("a")); Assert.assertEquals("20", properties.get("a")); Assert.assertTrue(properties.containsKey("b")); Assert.assertEquals("30", properties.get("b")); }
### Question: JsonSimplePredicate implements Predicate { static String toOgnl(final Matcher matcher) { final String expression = matcher.group(1); if (!(expression.startsWith("body.") || expression.startsWith("body[")) || isCollectionPath(expression)) { return expression; } final StringBuilder ognl = new StringBuilder(expression.length() + 5); final char[] chars = expression.toCharArray(); boolean start = true; for (final char ch : chars) { if (ch == '.' || ch == '[') { if (!start) { ognl.append(']'); } start = false; ognl.append('['); } else if (ch == '$') { ognl.append("\\$"); } else if (ch != ']') { ognl.append(ch); } } if (!start) { ognl.append(']'); } return ognl.toString(); } JsonSimplePredicate(final String expression, final CamelContext context); @Override @SuppressFBWarnings({"NP_LOAD_OF_KNOWN_NULL_VALUE", "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"}) // https://github.com/spotbugs/spotbugs/issues/868 though this code is fishy (TODO) boolean matches(final Exchange exchange); }### Answer: @Test @Parameters({"body.prop, body[prop]", "body.size(), body.size()", "body[3], body[3]", "body[3].prop, body[3][prop]", "body.fr_op.gl$op.ml0op[3], body[fr_op][gl\\$op][ml0op][3]"}) public void shouldConvertSimpleToOgnl(final String simple, final String ognl) { final Matcher matcher = Pattern.compile("(.*)").matcher(simple); matcher.find(); assertThat(JsonSimplePredicate.toOgnl(matcher)).isEqualTo(ognl); }
### Question: And extends LTLFormula { @Override public LTLType getLTLType(){ return LTLType.AND; } And(ArrayList<LTLFormula> children); @Override LTLType getLTLType(); @Override LTLFormula copy(); @Override LinkedHashSet<LinkedHashSet<LTLFormula>> toSetForm(); @Override ATransition d(HashMap<LTLFormula, ATransition> D); static void main(String args[]); }### Answer: @Test public void testType() { assertEquals(LTLType.AND, a_and_b.getLTLType()); assertEquals(LTLType.AND, a_and_c.getLTLType()); }
### Question: Or extends LTLFormula { public LTLFormula copy() { ArrayList<LTLFormula> copiedChildren = new ArrayList<LTLFormula>(children.size()); for(LTLFormula child : children){ copiedChildren.add(child.copy()); } return new Or(copiedChildren); } Or(ArrayList<LTLFormula> children); LTLType getLTLType(); LTLFormula copy(); LinkedHashSet<LinkedHashSet<LTLFormula>> toSetForm(); ATransition d(HashMap<LTLFormula, ATransition> D); static void main(String args[]); }### Answer: @Test public void testCopy() { assertEquals(a_or_b, a_or_b.copy()); assertEquals(a_or_c, a_or_c.copy()); }
### Question: XOr extends LTLFormula { @Override public LTLType getLTLType(){ return LTLType.XOR; } XOr(ArrayList<LTLFormula> children); @Override LTLType getLTLType(); @Override LTLFormula normalize(); @Override LTLFormula copy(); static void main(String[] args); }### Answer: @Test public void testType() { assertEquals(LTLType.XOR, a_xor_b.getLTLType()); assertEquals(LTLType.XOR, a_xor_c.getLTLType()); }
### Question: XOr extends LTLFormula { @Override protected LTLFormula lower(){ for(int i = 0; i < children.size(); ++i){ children.set(i,children.get(i).lower()); } ArrayList<LTLFormula> nextChildren; LTLFormula left = children.get(0); for(int i = 1; i < children.size(); ++i){ nextChildren = new ArrayList<LTLFormula>(2); LTLFormula right = children.get(i); nextChildren.add(new Negation(left.copy())); nextChildren.add(right.copy()); LTLFormula And1 = new And(nextChildren); nextChildren = new ArrayList<LTLFormula>(2); nextChildren.add(left); nextChildren.add(new Negation(right)); LTLFormula And2 = new And(nextChildren); nextChildren = new ArrayList<LTLFormula>(2); nextChildren.add(And1); nextChildren.add(And2); left = new Or(nextChildren); } return left; } XOr(ArrayList<LTLFormula> children); @Override LTLType getLTLType(); @Override LTLFormula normalize(); @Override LTLFormula copy(); static void main(String[] args); }### Answer: @Test public void testLower() { LTLFormula expected = OrTest.makeOr(AndTest.makeAnd(new Negation(a), b), AndTest.makeAnd(a, new Negation(b))); assertEquals(expected, a_xor_b.simplify()); }
### Question: XOr extends LTLFormula { @Override public LTLFormula copy() { ArrayList<LTLFormula> copiedChildren = new ArrayList<LTLFormula>(children.size()); for(LTLFormula child : children){ copiedChildren.add(child.copy()); } return new XOr(copiedChildren); } XOr(ArrayList<LTLFormula> children); @Override LTLType getLTLType(); @Override LTLFormula normalize(); @Override LTLFormula copy(); static void main(String[] args); }### Answer: @Test public void testCopy() { assertEquals(a_xor_b, a_xor_b.copy()); assertEquals(a_xor_c, a_xor_c.copy()); }
### Question: Repeat { public static ERE get(ERE child, int num) { if(num < 1) { return Empty.get(); } else if(num == 1) { return child; } else { ERE ret = Concat.get(child, child); for(int i = 2; i < num; ++i) { ret = Concat.get(child, ret); } return ret; } } static ERE get(ERE child, int num); }### Answer: @Test public void equalityTest() { ERE a_x5_again = Repeat.get(a, 5); assertEquals(a_x5, a_x5_again); assertEquals(0, a_x5.compareTo(a_x5_again)); } @Test public void inequalityTest() { ERE a_x10 = Repeat.get(a, 10); Symbol b = Symbol.get("b"); ERE b_x5 = Repeat.get(b, 5); assertFalse(a_x5.equals(a_x10)); assertFalse(0 == a_x5.compareTo(a_x10)); assertFalse(a_x5.equals(b_x5)); assertFalse(0 == a_x5.compareTo(b_x5)); } @Test public void deriveTest() { Symbol a = Symbol.get("a"); Epsilon epsilon = Epsilon.get(); assertEquals(epsilon, a_x3.derive(a).derive(a).derive(a)); Empty empty = Empty.get(); assertEquals(empty, a_x3.derive(a).derive(a).derive(a).derive(a)); Symbol b = Symbol.get("b"); assertEquals(empty, a_x3.derive(b)); }
### Question: Concat extends ERE { public static ERE get(ERE left, ERE right) { Concat cat = new Concat(left, right); ERE ret = cat.simplify(); return ret; } private Concat(ERE left, ERE right); static ERE get(ERE left, ERE right); @Override EREType getEREType(); @Override String toString(); @Override ERE copy(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testEquality() { ERE one = Concat.get(a, b); ERE two = Concat.get(a, b); assertEquals(one, two); assertEquals(0, one.compareTo(two)); } @Test public void testInequality() { ERE one = Concat.get(a, b); ERE two = Concat.get(a, c); assertFalse(one.equals(two)); assertFalse(0 == one.compareTo(two)); assertFalse(one.equals(a)); assertFalse(0 == one.compareTo(a)); }
### Question: Concat extends ERE { @Override public boolean containsEpsilon() { for(ERE child : children) { if(!child.containsEpsilon()) { return false; } } return true; } private Concat(ERE left, ERE right); static ERE get(ERE left, ERE right); @Override EREType getEREType(); @Override String toString(); @Override ERE copy(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testContainsEpsilon() { Epsilon epsilon = Epsilon.get(); assertFalse(Concat.get(a, b).containsEpsilon()); assertFalse(Concat.get(a, epsilon).containsEpsilon()); assertFalse(Concat.get(epsilon, b).containsEpsilon()); assertTrue(Concat.get(epsilon, epsilon).containsEpsilon()); }
### Question: And extends LTLFormula { @Override protected LTLFormula normalize(boolean b) { if(b) { flatten(); for(int i = 0; i < children.size(); ++i){ children.set(i, getNegation(i, true)); } return new Or(children); } else { for(int i = 0; i < children.size(); ++i){ children.set(i, getNegation(i, false)); } return this; } } And(ArrayList<LTLFormula> children); @Override LTLType getLTLType(); @Override LTLFormula copy(); @Override LinkedHashSet<LinkedHashSet<LTLFormula>> toSetForm(); @Override ATransition d(HashMap<LTLFormula, ATransition> D); static void main(String args[]); }### Answer: @Test public void testNormalize() { { ArrayList<LTLFormula> orElements = new ArrayList<LTLFormula>( Arrays.asList(new Negation(a), new Negation(b))); Collections.sort(orElements); Or expected = new Or(orElements); assertEquals(expected, a_and_b.copy().normalize(true)); } assertEquals(makeAnd(a, c), a_and_c.normalize(false)); }
### Question: Concat extends ERE { private ERE simplify(){ if(children.get(0) == Empty.get()) { return Empty.get(); } else if(children.get(1) == Empty.get()) { return Empty.get(); } else if(children.get(0) == Epsilon.get()) { return children.get(1); } else if(children.get(1) == Epsilon.get()) { return children.get(0); } return this; } private Concat(ERE left, ERE right); static ERE get(ERE left, ERE right); @Override EREType getEREType(); @Override String toString(); @Override ERE copy(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testSimplify() { Epsilon epsilon = Epsilon.get(); Empty empty = Empty.get(); assertEquals(empty, Concat.get(a, empty)); assertEquals(empty, Concat.get(empty, a)); assertEquals(a, Concat.get(a, epsilon)); assertEquals(a, Concat.get(epsilon, a)); assertEquals(empty, Concat.get(epsilon, empty)); assertEquals(empty, Concat.get(empty, epsilon)); }
### Question: Concat extends ERE { @Override public ERE copy() { return new Concat(children.get(0).copy(), children.get(1).copy()); } private Concat(ERE left, ERE right); static ERE get(ERE left, ERE right); @Override EREType getEREType(); @Override String toString(); @Override ERE copy(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testCopy() { ERE concat = Concat.get(a, b); ERE copy = concat.copy(); assertEquals(concat, copy); }
### Question: Concat extends ERE { @Override public ERE derive(Symbol s){ ERE left = children.get(0); ERE right = children.get(1); if(left.containsEpsilon()) { ArrayList<ERE> orChildren = new ArrayList<ERE>(2); orChildren.add(Concat.get(left.derive(s), right.copy())); orChildren.add(right.derive(s)); return Or.get(orChildren); } return Concat.get(left.derive(s), right.copy()); } private Concat(ERE left, ERE right); static ERE get(ERE left, ERE right); @Override EREType getEREType(); @Override String toString(); @Override ERE copy(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testDerive() { Epsilon epsilon = Epsilon.get(); Empty empty = Empty.get(); ERE ab = Concat.get(a, b); assertEquals(b, ab.derive(a)); assertEquals(empty, ab.derive(b)); ERE aStar = Kleene.get(a); ERE aStarb = Concat.get(aStar, b); assertEquals(aStarb, aStarb.derive(a)); assertEquals(epsilon, aStarb.derive(b)); assertEquals(empty, aStarb.derive(c)); }
### Question: FSM { static public FSM get(ERE input, Symbol[] events) { return new FSM(input, events); } private FSM(ERE input, Symbol[] events); static FSM get(ERE input, Symbol[] events); void print(PrintStream p); public LinkedHashMap<ERE, LinkedHashMap<Symbol, ERE>> contents; public LinkedHashSet<ERE> match; }### Answer: @Test public void testConcat() { ERE ab = Concat.get(a, b); String fsm = "s0 [" + NEWLINE + " a -> s1" + NEWLINE + "]" + NEWLINE + "s1 [" + NEWLINE + " b -> s2" + NEWLINE + "]" + NEWLINE + "s2 [" + NEWLINE + "]" + NEWLINE + "alias match = s2 " + NEWLINE; assertEquals(fsm, printFSM(ab, a, b)); } @Test public void testOr() { ERE or = Or.get(new ArrayList<ERE>(Arrays.asList(a, b))); String fsm = "s0 [" + NEWLINE + " a -> s1" + NEWLINE + " b -> s1" + NEWLINE + "]" + NEWLINE + "s1 [" + NEWLINE + "]" + NEWLINE + "alias match = s1 " + NEWLINE; assertEquals(fsm, printFSM(or, a, b)); } @Test public void testKleene() { ERE aStar = Kleene.get(a); String fsm = "s0 [" + NEWLINE + " a -> s0" + NEWLINE + "]" + NEWLINE + "alias match = s0 " + NEWLINE; assertEquals(fsm, printFSM(aStar, a)); }
### Question: Negation extends ERE { public static ERE get(ERE child) { if(child.getEREType() == EREType.NEG) return child.children.get(0); return new Negation(child); } private Negation(ERE child); static ERE get(ERE child); @Override EREType getEREType(); @Override String toString(); @Override ERE copy(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testEquality() { ERE one = Negation.get(symbol); ERE one_again = Negation.get(symbol); assertEquals(one, one_again); assertEquals(0, one.compareTo(one_again)); } @Test public void testInequality() { Epsilon epsilon = Epsilon.get(); ERE one = Negation.get(symbol); ERE two = Negation.get(epsilon); assertFalse(one.equals(two)); assertFalse(0 == one.compareTo(two)); } @Test public void testSimplification() { ERE negation = Negation.get(symbol); ERE doubleNegation = Negation.get(negation); assertEquals(symbol, doubleNegation); }
### Question: Negation extends ERE { @Override public boolean containsEpsilon() { return !(children.get(0).containsEpsilon()); } private Negation(ERE child); static ERE get(ERE child); @Override EREType getEREType(); @Override String toString(); @Override ERE copy(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testContainsEpsilon() { ERE negateEmpty = Negation.get(empty); ERE negateEpsilon = Negation.get(epsilon); assertTrue(negateEmpty.containsEpsilon()); assertFalse(negateEpsilon.containsEpsilon()); }
### Question: Negation extends ERE { @Override public ERE derive(Symbol s) { return Negation.get(children.get(0).derive(s)); } private Negation(ERE child); static ERE get(ERE child); @Override EREType getEREType(); @Override String toString(); @Override ERE copy(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testDerive() { ERE negateEmpty = Negation.get(empty); ERE negateEpsilon = Negation.get(epsilon); ERE derived = negateEpsilon.derive(Symbol.get("test")); assertEquals(negateEmpty, derived); }
### Question: Negation extends ERE { @Override public ERE copy() { return new Negation(children.get(0).copy()); } private Negation(ERE child); static ERE get(ERE child); @Override EREType getEREType(); @Override String toString(); @Override ERE copy(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testCopy() { ERE negation = Negation.get(empty); ERE copy = negation.copy(); assertEquals(negation, copy); }
### Question: Symbol extends ERE { @Override public ERE copy() { return this; } private Symbol(); static Symbol get(String name); @Override EREType getEREType(); @Override boolean equals(Object o); @Override int compareTo(Object o); @Override ERE copy(); @Override String toString(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testCopy() { ERE copy = one.copy(); assertEquals(one, copy); }
### Question: Symbol extends ERE { @Override public EREType getEREType() { return EREType.S; } private Symbol(); static Symbol get(String name); @Override EREType getEREType(); @Override boolean equals(Object o); @Override int compareTo(Object o); @Override ERE copy(); @Override String toString(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testEREType() { EREType type = one.getEREType(); assertEquals(EREType.S, type); }
### Question: Symbol extends ERE { @Override public boolean containsEpsilon() { return false; } private Symbol(); static Symbol get(String name); @Override EREType getEREType(); @Override boolean equals(Object o); @Override int compareTo(Object o); @Override ERE copy(); @Override String toString(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testContainsEpsilon() { assertFalse(one.containsEpsilon()); }
### Question: Symbol extends ERE { @Override public ERE derive(Symbol s) { if(this == s) { return Epsilon.get(); } return Empty.get(); } private Symbol(); static Symbol get(String name); @Override EREType getEREType(); @Override boolean equals(Object o); @Override int compareTo(Object o); @Override ERE copy(); @Override String toString(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testDerive() { Empty empty = Empty.get(); Epsilon epsilon = Epsilon.get(); assertEquals(epsilon, one.derive(one)); assertEquals(empty, one.derive(two)); assertEquals(epsilon, two.derive(two)); assertEquals(empty, two.derive(one)); }
### Question: Symbol extends ERE { @Override public String toString() { return refToString.get(this); } private Symbol(); static Symbol get(String name); @Override EREType getEREType(); @Override boolean equals(Object o); @Override int compareTo(Object o); @Override ERE copy(); @Override String toString(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testString() { assertEquals("one", one.toString()); assertEquals("two", two.toString()); }
### Question: Empty extends ERE { @Override public EREType getEREType() { return EREType.EMP; } private Empty(); static Empty get(); @Override EREType getEREType(); @Override boolean equals(Object o); @Override int compareTo(Object o); @Override ERE copy(); @Override String toString(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testType() { assertEquals(empty.getEREType(), EREType.EMP); }
### Question: Empty extends ERE { @Override public String toString() { return "empty"; } private Empty(); static Empty get(); @Override EREType getEREType(); @Override boolean equals(Object o); @Override int compareTo(Object o); @Override ERE copy(); @Override String toString(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testString() { assertEquals("empty", empty.toString()); }
### Question: Empty extends ERE { @Override public ERE derive(Symbol s) { return empty; } private Empty(); static Empty get(); @Override EREType getEREType(); @Override boolean equals(Object o); @Override int compareTo(Object o); @Override ERE copy(); @Override String toString(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testDerive() { ERE derived = empty.derive(Symbol.get("test")); assertEquals(empty, derived); }
### Question: And extends LTLFormula { @Override public LTLFormula copy() { ArrayList<LTLFormula> copiedChildren = new ArrayList<LTLFormula>(children.size()); for(LTLFormula child : children){ copiedChildren.add(child.copy()); } return new And(copiedChildren); } And(ArrayList<LTLFormula> children); @Override LTLType getLTLType(); @Override LTLFormula copy(); @Override LinkedHashSet<LinkedHashSet<LTLFormula>> toSetForm(); @Override ATransition d(HashMap<LTLFormula, ATransition> D); static void main(String args[]); }### Answer: @Test public void testCopy() { assertEquals(a_and_b, a_and_b.copy()); assertEquals(a_and_c, a_and_c.copy()); }
### Question: Empty extends ERE { @Override public boolean containsEpsilon() { return false; } private Empty(); static Empty get(); @Override EREType getEREType(); @Override boolean equals(Object o); @Override int compareTo(Object o); @Override ERE copy(); @Override String toString(); @Override boolean containsEpsilon(); @Override ERE derive(Symbol s); }### Answer: @Test public void testContainsEpsilon() { assertFalse(empty.containsEpsilon()); }