method2testcases
stringlengths
118
6.63k
### Question: IntegrationRouteBuilder extends RouteBuilder { public IntegrationRouteBuilder(String configurationUri) { this(configurationUri, Resources.loadServices(IntegrationStepHandler.class)); } IntegrationRouteBuilder(String configurationUri); IntegrationRouteBuilder(String configurationUri, Collection<IntegrationStepHandler> handlers); IntegrationRouteBuilder(String configurationUri, Collection<IntegrationStepHandler> handlers, List<ActivityTrackingPolicyFactory> activityTrackingPolicyFactories); IntegrationRouteBuilder(SourceProvider sourceProvider, Collection<IntegrationStepHandler> handlers, List<ActivityTrackingPolicyFactory> activityTrackingPolicyFactories); @Override ModelCamelContext getContext(); @Override void configure(); }### Answer: @Test public void testIntegrationRouteBuilder() throws Exception { String configurationLocation = "classpath:syndesis/integration/integration.json"; IntegrationRouteBuilder routeBuilder = new IntegrationRouteBuilder(configurationLocation, Resources.loadServices(IntegrationStepHandler.class), policyFactories); routeBuilder.configure(); dumpRoutes(new DefaultCamelContext(), routeBuilder.getRouteCollection()); RoutesDefinition routes = routeBuilder.getRouteCollection(); assertThat(routes.getRoutes()).hasSize(1); RouteDefinition route = routes.getRoutes().get(0); assertThat(route.getRoutePolicies()).hasSize(1); assertThat(route.getInput()).isNotNull(); assertThat(route.getInput()).hasFieldOrPropertyWithValue("uri", "direct:expression"); assertThat(route.getOutputs()).hasSize(2); assertThat(getOutput(route, 0)).isInstanceOf(PipelineDefinition.class); assertThat(getOutput(route, 0).getOutputs()).hasSize(2); assertThat(getOutput(route, 0).getOutputs().get(0)).isInstanceOf(SetHeaderDefinition.class); assertThat(getOutput(route, 0).getOutputs().get(1)).isInstanceOf(SetHeaderDefinition.class); assertThat(getOutput(route, 1)).isInstanceOf(SplitDefinition.class); assertThat(getOutput(route, 1).getOutputs()).hasSize(3); assertThat(getOutput(route, 1, 0)).isInstanceOf(SetHeaderDefinition.class); assertThat(getOutput(route, 1, 1)).isInstanceOf(ProcessDefinition.class); assertThat(getOutput(route, 1, 2)).isInstanceOf(PipelineDefinition.class); assertThat(getOutput(route, 1, 2).getOutputs()).hasSize(3); assertThat(getOutput(route, 1, 2, 0)).isInstanceOf(SetHeaderDefinition.class); assertThat(getOutput(route, 1, 2, 1)).isInstanceOf(ToDefinition.class); assertThat(getOutput(route, 1, 2, 1)).hasFieldOrPropertyWithValue("uri", "mock:expression"); assertThat(getOutput(route, 1, 2, 2)).isInstanceOf(ProcessDefinition.class); }
### 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: StaticEdition extends Edition { @Override protected KeySource keySource() { return keySource; } StaticEdition(final ClientSideStateProperties properties); }### Answer: @Test public void shouldCreateEditionFromProperties() { final ClientSideStateProperties properties = new ClientSideStateProperties(); properties.setAuthenticationAlgorithm("HmacSHA1"); properties.setAuthenticationKey("oID3dF6UovTkzMyr3a9dr0kgTnE="); properties.setEncryptionAlgorithm("AES/CBC/PKCS5Padding"); properties.setEncryptionKey("T2NasjRXURA3dSL8dUQubQ=="); properties.setTid(1L); final StaticEdition edition = new StaticEdition(properties); assertThat(edition.authenticationAlgorithm).isEqualTo("HmacSHA1"); assertThat(edition.encryptionAlgorithm).isEqualTo("AES/CBC/PKCS5Padding"); assertThat(edition.tid).isEqualTo(new byte[] {1}); final KeySource keySource = edition.keySource(); assertThat(keySource.authenticationKey()) .isEqualTo(new SecretKeySpec( new byte[] {(byte) 0xa0, (byte) 0x80, (byte) 0xf7, 0x74, 0x5e, (byte) 0x94, (byte) 0xa2, (byte) 0xf4, (byte) 0xe4, (byte) 0xcc, (byte) 0xcc, (byte) 0xab, (byte) 0xdd, (byte) 0xaf, 0x5d, (byte) 0xaf, 0x49, 0x20, 0x4e, 0x71}, "HmacSHA1")); assertThat(keySource.encryptionKey()).isEqualTo(new SecretKeySpec( new byte[] {0x4f, 0x63, 0x5a, (byte) 0xb2, 0x34, 0x57, 0x51, 0x10, 0x37, 0x75, 0x22, (byte) 0xfc, 0x75, 0x44, 0x2e, 0x6d}, "AES")); KeySourceAssert.assertThat(keySource).canBeUsedForCryptography(); } @Test public void shouldCreateEditionWithNonBase64Passwords() { final ClientSideStateProperties properties = new ClientSideStateProperties(); properties.setAuthenticationAlgorithm("HmacSHA1"); properties.setAuthenticationKey(RandomStringUtils.random(32, true, true)); properties.setEncryptionAlgorithm("AES/CBC/PKCS5Padding"); properties.setEncryptionKey(RandomStringUtils.random(32, true, true)); properties.setTid(1L); final StaticEdition edition = new StaticEdition(properties); final KeySource keySource = edition.keySource(); KeySourceAssert.assertThat(keySource).canBeUsedForCryptography(); }
### 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: ChoiceMetadataHandler implements StepMetadataHandler { @Override public DynamicActionMetadata createMetadata(Step step, List<Step> previousSteps, List<Step> subsequentSteps) { DataShape outputShape = StepMetadataHelper.getLastWithOutputShape(previousSteps) .flatMap(Step::outputDataShape) .orElse(StepMetadataHelper.NO_SHAPE); return new DynamicActionMetadata.Builder() .inputShape(outputShape) .outputShape(step.outputDataShape() .orElse(StepMetadataHelper.ANY_SHAPE)) .build(); } @Override boolean canHandle(StepKind kind); @Override DynamicActionMetadata createMetadata(Step step, List<Step> previousSteps, List<Step> subsequentSteps); }### Answer: @Test public void shouldCreateMetaDataFromSurroundingSteps() { Step previousStep = new Step.Builder() .stepKind(StepKind.endpoint) .action(new ConnectorAction.Builder() .descriptor(new ConnectorDescriptor.Builder() .inputDataShape(StepMetadataHelper.NO_SHAPE) .outputDataShape(new DataShape.Builder() .kind(DataShapeKinds.JSON_INSTANCE) .specification("{}") .description("previousOutput") .addVariant(testShape("variant1")) .addVariant(testShape("variant2")) .build()) .build()) .build()) .build(); Step subsequentStep = new Step.Builder() .stepKind(StepKind.endpoint) .action(new ConnectorAction.Builder() .descriptor(new ConnectorDescriptor.Builder() .inputDataShape(new DataShape.Builder() .kind(DataShapeKinds.JSON_INSTANCE) .specification("{}") .description("subsequentInput") .addVariant(testShape("variant3")) .addVariant(testShape("variant4")) .build()) .outputDataShape(StepMetadataHelper.NO_SHAPE) .build()) .build()) .build(); DynamicActionMetadata metadata = metadataHandler.createMetadata(choiceStep, Collections.singletonList(previousStep), Collections.singletonList(subsequentStep)); Assert.assertNotNull(metadata.outputShape()); Assert.assertEquals(DataShapeKinds.ANY, metadata.outputShape().getKind()); Assert.assertNotNull(metadata.inputShape()); Assert.assertEquals(DataShapeKinds.JSON_INSTANCE, metadata.inputShape().getKind()); Assert.assertEquals("previousOutput", metadata.inputShape().getDescription()); Assert.assertEquals(2, metadata.inputShape().getVariants().size()); Assert.assertEquals("variant1", metadata.inputShape().getVariants().get(0).getMetadata().get("name")); Assert.assertEquals("variant2", metadata.inputShape().getVariants().get(1).getMetadata().get("name")); } @Test public void shouldCreateMetaDataFromAnyShapes() { Step previousStep = new Step.Builder() .stepKind(StepKind.endpoint) .action(new ConnectorAction.Builder() .descriptor(new ConnectorDescriptor.Builder() .inputDataShape(StepMetadataHelper.NO_SHAPE) .outputDataShape(StepMetadataHelper.ANY_SHAPE) .build()) .build()) .build(); Step subsequentStep = new Step.Builder() .stepKind(StepKind.endpoint) .action(new ConnectorAction.Builder() .descriptor(new ConnectorDescriptor.Builder() .inputDataShape(StepMetadataHelper.ANY_SHAPE) .outputDataShape(StepMetadataHelper.NO_SHAPE) .build()) .build()) .build(); DynamicActionMetadata metadata = metadataHandler.createMetadata(choiceStep, Collections.singletonList(previousStep), Collections.singletonList(subsequentStep)); Assert.assertEquals(StepMetadataHelper.ANY_SHAPE, metadata.inputShape()); Assert.assertEquals(StepMetadataHelper.ANY_SHAPE, metadata.outputShape()); } @Test public void shouldCreateMetaDataFromEmptySurroundingSteps() { DynamicActionMetadata metadata = metadataHandler.createMetadata(choiceStep, Collections.emptyList(), Collections.emptyList()); Assert.assertEquals(StepMetadataHelper.NO_SHAPE, metadata.inputShape()); Assert.assertEquals(StepMetadataHelper.ANY_SHAPE, metadata.outputShape()); }
### Question: ProjectGenerator implements IntegrationProjectGenerator { @Override public Properties generateApplicationProperties(final Integration integrationDefinition) { final Integration integration = resourceManager.sanitize(integrationDefinition); final Properties properties = new Properties(); properties.putAll(integration.getConfiguredProperties()); addPropertiesFrom(properties, integration, resourceManager); return properties; } ProjectGenerator(ProjectGeneratorConfiguration configuration, IntegrationResourceManager resourceManager, MavenProperties mavenProperties); @Override @SuppressWarnings("resource") InputStream generate(final Integration integrationDefinition, IntegrationErrorHandler errorHandler); @Override Properties generateApplicationProperties(final Integration integrationDefinition); @Override byte[] generatePom(final Integration integration); }### Answer: @Test public void testGenerateApplicationProperties() throws IOException { final ConnectorAction newAction = new ConnectorAction.Builder() .id(KeyGenerator.createKey()) .descriptor(new ConnectorDescriptor.Builder() .connectorId("new") .componentScheme("http4") .build()) .build(); final Connector newConnector = new Connector.Builder() .id("new") .addAction(newAction) .putProperty("username", new ConfigurationProperty.Builder() .componentProperty(false) .secret(true) .build()) .putProperty("password", new ConfigurationProperty.Builder() .componentProperty(false) .secret(true) .build()) .putProperty("token", new ConfigurationProperty.Builder() .componentProperty(true) .secret(true) .build()) .build(); Step s1 = new Step.Builder() .stepKind(StepKind.endpoint) .connection(new Connection.Builder() .id(KeyGenerator.createKey()) .connector(newConnector) .build()) .putConfiguredProperty("username", "my-username-2") .putConfiguredProperty("password", "my-password-2") .putConfiguredProperty("token", "my-token-2") .action(newAction) .build(); TestResourceManager resourceManager = new TestResourceManager(); ProjectGeneratorConfiguration configuration = new ProjectGeneratorConfiguration(); ProjectGenerator generator = new ProjectGenerator(configuration, resourceManager, TestConstants.MAVEN_PROPERTIES); Integration integration = new Integration.Builder() .createFrom(resourceManager.newIntegration(s1)) .putConfiguredProperty("integration", "property") .build(); Properties properties = generator.generateApplicationProperties(integration); assertThat(properties).containsOnly( entry("integration", "property"), entry("flow-0.http4-0.token", "my-token-2"), entry("flow-0.http4-0.username", "my-username-2"), entry("flow-0.http4-0.password", "my-password-2") ); } @Test public void testGenerateApplicationPropertiesOldStyle() throws IOException { final ConnectorAction oldAction = new ConnectorAction.Builder() .id(KeyGenerator.createKey()) .descriptor(new ConnectorDescriptor.Builder() .connectorId("old") .build()) .build(); final Connector oldConnector = new Connector.Builder() .id("old") .addAction(oldAction) .putProperty("username", new ConfigurationProperty.Builder() .componentProperty(false) .secret(true) .build()) .putProperty("password", new ConfigurationProperty.Builder() .componentProperty(false) .secret(true) .build()) .putProperty("token", new ConfigurationProperty.Builder() .componentProperty(true) .secret(true) .build()) .build(); Step s1 = new Step.Builder() .stepKind(StepKind.endpoint) .connection(new Connection.Builder() .id(KeyGenerator.createKey()) .connector(oldConnector) .build()) .putConfiguredProperty("username", "my-username-1") .putConfiguredProperty("password", "my-password-1") .putConfiguredProperty("token", "my-token-1") .action(oldAction) .build(); TestResourceManager resourceManager = new TestResourceManager(); ProjectGeneratorConfiguration configuration = new ProjectGeneratorConfiguration(); ProjectGenerator generator = new ProjectGenerator(configuration, resourceManager, TestConstants.MAVEN_PROPERTIES); Integration integration = new Integration.Builder() .createFrom(resourceManager.newIntegration(s1)) .putConfiguredProperty("integration", "property") .build(); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> generator.generateApplicationProperties(integration)) .withMessage("Old style of connectors from camel-connector are not supported anymore, please be sure that integration json satisfy connector.getComponentScheme().isPresent() || descriptor.getComponentScheme().isPresent()"); }
### Question: CustomConnectorHandler extends BaseConnectorGeneratorHandler { @POST @Path("/info") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Operation(description = "Provides a summary of the connector as it would be built using a ConnectorTemplate identified by the provided `connector-template-id` and the data given in `connectorSettings`") public APISummary info(final ConnectorSettings connectorSettings) { return withGeneratorAndTemplate(connectorSettings.getConnectorTemplateId(), (generator, template) -> generator.info(template, connectorSettings)); } CustomConnectorHandler(final DataManager dataManager, final ApplicationContext applicationContext, final IconDao iconDao); @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Operation(description = "Creates a new Connector based on the ConnectorTemplate identified by the provided `id` and the data given in `connectorSettings`") @ApiResponse(responseCode = "200", description = "Newly created Connector") Connector create(final ConnectorSettings connectorSettings); @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.MULTIPART_FORM_DATA) @Operation(description = "Creates a new Connector based on the ConnectorTemplate identified by the provided `id` and the data given in `connectorSettings` multipart part, plus optional `icon` file") @ApiResponse(responseCode = "200", description = "Newly created Connector") Connector create(@MultipartForm CustomConnectorFormData customConnectorFormData); @POST @Path("/info") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Operation(description = "Provides a summary of the connector as it would be built using a ConnectorTemplate identified by the provided `connector-template-id` and the data given in `connectorSettings`") APISummary info(final ConnectorSettings connectorSettings); @POST @Path("/info") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.MULTIPART_FORM_DATA) @Operation(description = "Provides a summary of the connector as it would be built using a ConnectorTemplate identified by the provided `connector-template-id` and the data given in `connectorSettings`") APISummary info(@MultipartForm final CustomConnectorFormData connectorFormData); static final String SPECIFICATION; }### Answer: @Test public void shouldProvideInfoAboutAppliedConnectorSettings() { final CustomConnectorHandler handler = new CustomConnectorHandler(dataManager, applicationContext, iconDao); final ConnectorGenerator connectorGenerator = mock(ConnectorGenerator.class); final ConnectorTemplate template = new ConnectorTemplate.Builder().build(); final ConnectorSettings connectorSettings = new ConnectorSettings.Builder().connectorTemplateId("connector-template").build(); final APISummary preparedSummary = new APISummary.Builder().build(); when(dataManager.fetch(ConnectorTemplate.class, "connector-template")).thenReturn(template); when(applicationContext.getBean("connector-template")).thenReturn(connectorGenerator); when(connectorGenerator.info(same(template), same(connectorSettings))).thenReturn(preparedSummary); final APISummary info = handler.info(connectorSettings); assertThat(info).isSameAs(preparedSummary); }
### Question: ConnectionHandler extends BaseHandler implements Lister<ConnectionOverview>, Getter<ConnectionOverview>, Creator<Connection>, Deleter<Connection>, Updater<Connection>, Validating<Connection> { @Override public void delete(String id) { final DataManager dataManager = getDataManager(); dataManager.fetchIdsByPropertyValue(ConnectionBulletinBoard.class, "targetResourceId", id) .forEach(cbbId -> dataManager.delete(ConnectionBulletinBoard.class, cbbId)); Deleter.super.delete(id); } ConnectionHandler(final DataManager dataMgr, final Validator validator, final Credentials credentials, final ClientSideState state, final MetadataConfigurationProperties config, final EncryptionComponent encryptionComponent); @Override Kind resourceKind(); @Override ListResult<ConnectionOverview> list(int page, int perPage); @Override ConnectionOverview get(final String id); @Override @SuppressWarnings("JdkObsolete") Connection create(@Context SecurityContext sec, final Connection connection); @Override void delete(String id); @Override @SuppressWarnings("JdkObsolete") void update(final String id, final Connection connection); @Path("/{id}/actions") ConnectionActionHandler metadata(@NotNull @PathParam("id") @Parameter(required = true, example = "my-connection") final String connectionId); @GET @Produces(MediaType.APPLICATION_JSON) @Path(value = "/{id}/bulletins") ConnectionBulletinBoard getBulletins(@NotNull @PathParam("id") @Parameter(required = true) String id); @Override Validator getValidator(); }### Answer: @Test public void shouldDeleteConnectionsAndDeletingAssociatedResources() { String id = "to-delete"; Connection connection = new Connection.Builder().id(id).build(); when(dataManager.fetch(Connection.class, id)).thenReturn(connection); Set<String> cbbIds = new HashSet<>(); for (int i = 1; i <= 2; ++i) { cbbIds.add(id + "-cbb" + i); } when(dataManager.fetchIdsByPropertyValue(ConnectionBulletinBoard.class, "targetResourceId", id)) .thenReturn(cbbIds); for (String cbbId : cbbIds) { when(dataManager.delete(ConnectionBulletinBoard.class, cbbId)).thenReturn(true); } when(dataManager.delete(Connection.class, id)).thenReturn(true); handler.delete(id); verify(dataManager).delete(Connection.class, id); for (String cbbId : cbbIds) { verify(dataManager).delete(ConnectionBulletinBoard.class, cbbId); } }
### 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: UserHandler extends BaseHandler implements Lister<User>, Getter<User> { @Path("~") @GET @Produces(MediaType.APPLICATION_JSON) public User whoAmI(@Context SecurityContext sec) { String username = sec.getUserPrincipal().getName(); io.fabric8.openshift.api.model.User openShiftUser = this.openShiftService.whoAmI(username); Assert.notNull(openShiftUser, "A valid user is required"); return new User.Builder().username(openShiftUser.getMetadata().getName()) .fullName(Optional.ofNullable(openShiftUser.getFullName())) .name(Optional.ofNullable(openShiftUser.getFullName())).build(); } @Autowired UserHandler(DataManager dataMgr, OpenShiftService openShiftService, UserConfigurationProperties properties); @Override Kind resourceKind(); @Path("~") @GET @Produces(MediaType.APPLICATION_JSON) User whoAmI(@Context SecurityContext sec); @Path("~/quota") @GET @Produces(MediaType.APPLICATION_JSON) Quota quota(@Context SecurityContext sec); }### Answer: @Test public void successfulWhoAmIWithoutFullName() { SecurityContext sec = mock(SecurityContext.class); Principal principal = mock(Principal.class); when(principal.getName()).thenReturn("testuser"); when(sec.getUserPrincipal()).thenReturn(principal); NamespacedOpenShiftClient client = mock(NamespacedOpenShiftClient.class); @SuppressWarnings("unchecked") Resource<User,DoneableUser> user = mock(Resource.class); when(user.get()).thenReturn(new UserBuilder().withNewMetadata().withName("testuser").and().build()); @SuppressWarnings("unchecked") NonNamespaceOperation<User, UserList, DoneableUser, Resource<User, DoneableUser>> users = mock(NonNamespaceOperation.class); when(users.withName("testuser")).thenReturn(user); when(client.users()).thenReturn(users); SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken("testuser", "doesn'tmatter")); UserConfigurationProperties properties = new UserConfigurationProperties(); properties.setMaxDeploymentsPerUser(1); UserHandler userHandler = new UserHandler(null, new OpenShiftServiceImpl(client, null), properties); io.syndesis.common.model.user.User whoAmI = userHandler.whoAmI(sec); Assertions.assertThat(whoAmI).isNotNull(); Assertions.assertThat(whoAmI.getUsername()).isEqualTo("testuser"); Assertions.assertThat(whoAmI.getFullName()).isEmpty(); }
### Question: KeyGenerator { public static String createKey() { final long now = clock.getAsLong(); final ByteBuffer buffer = ByteBuffer.wrap(new byte[8 + 1 + 8]); buffer.putLong(now); buffer.put(randomnessByte); buffer.putLong(getRandomPart(now)); return encodeKey(buffer.array()); } private KeyGenerator(); static String createKey(); static long getKeyTimeMillis(String key); static String recreateKey(long timestamp, int random1, long random2); }### Answer: @Test public void testCreateKey() { String last = KeyGenerator.createKey(); for (int i = 0; i < 1000000; i++) { final String lastKey = last; final String key = KeyGenerator.createKey(); assertThat(key).is(new Condition<>((other) -> lastKey.compareTo(other) < 0, "greater than " + lastKey)); last = key; } } @Test public void testCreateKeyMultithreaded() { final int count = 100000; final Collection<Callable<String>> tasks = IntStream.range(0, count).boxed() .map(i -> (Callable<String>) () -> KeyGenerator.createKey()).collect(Collectors.toList()); final ForkJoinPool pool = ForkJoinPool.commonPool(); final List<Future<String>> results = pool.invokeAll(tasks); final Set<String> keys = results.stream().map(t -> { try { return t.get(); } catch (InterruptedException | ExecutionException e) { throw new IllegalStateException(e); } }).collect(Collectors.toSet()); Assert.assertEquals("If " + count + " key generations are performed in parallel, it should yield " + count + " of distinct keys", count, keys.size()); } @Test public void shouldGenerateKeysInChronologicalOrder() { for (int rnd = Byte.MIN_VALUE; rnd <= Byte.MAX_VALUE; rnd++) { KeyGenerator.randomnessByte = (byte) rnd; KeyGenerator.clock = () -> 1534509528000L; final String newer = KeyGenerator.createKey(); KeyGenerator.clock = () -> 1534245726000L; final String older = KeyGenerator.createKey(); assertThat(newer.compareTo(older)).isGreaterThan(0); } }
### Question: DataShapeUtils { static Optional<DataShape> buildDataShape(final JsonNode root) { if (root == null) { return Optional.empty(); } final DataShape.Builder builder = new DataShape.Builder(); addKindAndTypeTo(builder, root); addValueTo(root, "name", builder::name); addValueTo(root, "description", builder::description); addValueTo(root, "specification", builder::specification); addMetadataTo(builder, root); addVariantsTo(builder, root); return Optional.of(builder.build()); } private DataShapeUtils(); }### Answer: @Test public void testCompositeJavaDataShape() throws Exception { final ObjectNode ds = new ObjectMapper().createObjectNode(); ds.put("type", "java:" + String.class.getName()); final Optional<DataShape> shape = DataShapeUtils.buildDataShape(ds); assertThat(shape.isPresent()).isTrue(); assertThat(shape.get().getKind()).isEqualTo(DataShapeKinds.JAVA); assertThat(shape.get().getType()).isEqualTo(String.class.getName()); assertThat(shape.get().getName()).isNull(); assertThat(shape.get().getDescription()).isNull(); assertThat(shape.get().getSpecification()).isNull(); } @Test public void testDefaultDataShape() throws Exception { final ObjectNode ds = new ObjectMapper().createObjectNode(); final Optional<DataShape> shape = DataShapeUtils.buildDataShape(ds); assertThat(shape.isPresent()).isTrue(); assertThat(shape.get().getKind()).isEqualTo(DataShapeKinds.NONE); assertThat(shape.get().getType()).isNull(); assertThat(shape.get().getName()).isNull(); assertThat(shape.get().getDescription()).isNull(); assertThat(shape.get().getSpecification()).isNull(); } @Test public void testJsonInstanceDataShape() throws Exception { final String spec = "{\"kind\":\"java-instance\",\"name\":\"person\"}"; final ObjectNode ds = new ObjectMapper().createObjectNode(); ds.put("kind", DataShapeKinds.JSON_INSTANCE.toString()); ds.put("specification", spec); final Optional<DataShape> shape = DataShapeUtils.buildDataShape(ds); assertThat(shape.isPresent()).isTrue(); assertThat(shape.get().getKind()).isEqualTo(DataShapeKinds.JSON_INSTANCE); assertThat(shape.get().getType()).isNull(); assertThat(shape.get().getName()).isNull(); assertThat(shape.get().getDescription()).isNull(); assertThat(shape.get().getSpecification()).isEqualTo(spec); } @Test public void testSimpleJavaDataShape() throws Exception { final ObjectNode ds = new ObjectMapper().createObjectNode(); ds.put("kind", DataShapeKinds.JAVA.toString()); ds.put("type", String.class.getName()); final Optional<DataShape> shape = DataShapeUtils.buildDataShape(ds); assertThat(shape.isPresent()).isTrue(); assertThat(shape.get().getKind()).isEqualTo(DataShapeKinds.JAVA); assertThat(shape.get().getType()).isEqualTo(String.class.getName()); assertThat(shape.get().getName()).isNull(); assertThat(shape.get().getDescription()).isNull(); assertThat(shape.get().getSpecification()).isNull(); }
### Question: IntegrationDeploymentHandler extends BaseHandler { @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{version}") public IntegrationDeployment get(@NotNull @PathParam("id") @Parameter(required = true) final String id, @NotNull @PathParam("version") @Parameter(required = true) final int version) { final String compositeId = IntegrationDeployment.compositeId(id, version); return getDataManager().fetch(IntegrationDeployment.class, compositeId); } @Autowired IntegrationDeploymentHandler(final DataManager dataMgr, OpenShiftService openShiftService, UserConfigurationProperties properties); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{version}") IntegrationDeployment get(@NotNull @PathParam("id") @Parameter(required = true) final String id, @NotNull @PathParam("version") @Parameter(required = true) final int version); @GET @Produces(MediaType.APPLICATION_JSON) ListResult<IntegrationDeployment> list( @NotNull @PathParam("id") @Parameter(required = true) final String id, @Parameter(required = false, description = "Page number to return") @QueryParam("page") @DefaultValue("1") int page, @Parameter(required = false, description = "Number of records per page") @QueryParam("per_page") @DefaultValue("20") int perPage ); @PUT @Produces(MediaType.APPLICATION_JSON) IntegrationDeployment update(@Context final SecurityContext sec, @NotNull @PathParam("id") @Parameter(required = true) final String id); @POST @Produces(MediaType.APPLICATION_JSON) @Path("/{version}/targetState") void updateTargetState(@NotNull @PathParam("id") @Parameter(required = true) final String id, @NotNull @PathParam("version") @Parameter(required = true) final int version, @Parameter(required = true) final TargetStateRequest request); }### Answer: @Test public void shouldFetchIntegrationDeployments() { final IntegrationDeployment expected = deployment(0); when(dataManager.fetch(IntegrationDeployment.class, compositeId(INTEGRATION_ID, 3))).thenReturn(expected); final IntegrationDeployment got = handler.get(INTEGRATION_ID, 3); assertThat(got).isEqualTo(expected); }
### Question: IntegrationHandler extends BaseHandler implements Lister<IntegrationOverview>, Getter<IntegrationOverview>, Creator<Integration>, Deleter<Integration>, Updater<Integration>, Validating<Integration> { @POST @Produces(MediaType.APPLICATION_JSON) @Path(value = "/filters/options") public FilterOptions getFilterOptions(final DataShape dataShape) { final FilterOptions.Builder builder = new FilterOptions.Builder().addAllOps(Op.DEFAULT_OPTS); final List<String> paths = inspectors.getPaths(dataShape.getKind().toString(), dataShape.getType(), dataShape.getSpecification(), dataShape.getExemplar()); builder.paths(paths); return builder.build(); } IntegrationHandler(final DataManager dataMgr, final OpenShiftService openShiftService, final Validator validator, final Inspectors inspectors, final EncryptionComponent encryptionSupport, final APIGenerator apiGenerator, final IntegrationOverviewHelper integrationOverviewHelper); @Override Integration create(@Context final SecurityContext sec, final Integration integration); @Override void delete(final String id); @Override IntegrationOverview get(final String id); @POST @Produces(MediaType.APPLICATION_JSON) @Path(value = "/filters/options") FilterOptions getFilterOptions(final DataShape dataShape); @GET @Produces(MediaType.APPLICATION_JSON) @Path(value = "/filters/options") FilterOptions getGlobalFilterOptions(); Integration getIntegration(final String id); @GET @Produces(MediaType.APPLICATION_JSON) @Path(value = "/{id}/overview") IntegrationOverview getOverview(@PathParam("id") final String id); @Override Validator getValidator(); @Override ListResult<IntegrationOverview> list(int page, int perPage); @Override Kind resourceKind(); @Override void update(final String id, final Integration integration); }### Answer: @Test public void filterOptionsNoOutputShape() { DataShape dataShape = dataShape(DataShapeKinds.NONE); FilterOptions options = handler.getFilterOptions(dataShape); assertThat(options.getPaths()).isEmpty(); } @Test public void filterOptionsSimple() { when(inspectors.getPaths(DataShapeKinds.JAVA.toString(), "twitter4j.Status", null, Optional.empty())) .thenReturn(Arrays.asList("paramA", "paramB")); DataShape dataShape = dataShape(DataShapeKinds.JAVA, "twitter4j.Status"); FilterOptions options = handler.getFilterOptions(dataShape); assertThat(options.getPaths()).hasSize(2).contains("paramA", "paramB"); }
### Question: IntegrationHandler extends BaseHandler implements Lister<IntegrationOverview>, Getter<IntegrationOverview>, Creator<Integration>, Deleter<Integration>, Updater<Integration>, Validating<Integration> { @Override public Integration create(@Context final SecurityContext sec, final Integration integration) { final Integration encryptedIntegration = encryptionSupport.encrypt(integration); final Integration updatedIntegration = new Integration.Builder().createFrom(encryptedIntegration) .createdAt(System.currentTimeMillis()).build(); return getDataManager().create(updatedIntegration); } IntegrationHandler(final DataManager dataMgr, final OpenShiftService openShiftService, final Validator validator, final Inspectors inspectors, final EncryptionComponent encryptionSupport, final APIGenerator apiGenerator, final IntegrationOverviewHelper integrationOverviewHelper); @Override Integration create(@Context final SecurityContext sec, final Integration integration); @Override void delete(final String id); @Override IntegrationOverview get(final String id); @POST @Produces(MediaType.APPLICATION_JSON) @Path(value = "/filters/options") FilterOptions getFilterOptions(final DataShape dataShape); @GET @Produces(MediaType.APPLICATION_JSON) @Path(value = "/filters/options") FilterOptions getGlobalFilterOptions(); Integration getIntegration(final String id); @GET @Produces(MediaType.APPLICATION_JSON) @Path(value = "/{id}/overview") IntegrationOverview getOverview(@PathParam("id") final String id); @Override Validator getValidator(); @Override ListResult<IntegrationOverview> list(int page, int perPage); @Override Kind resourceKind(); @Override void update(final String id, final Integration integration); }### Answer: @Test public void shouldCreateIntegrations() { final SecurityContext security = mock(SecurityContext.class); final Principal principal = mock(Principal.class); when(security.getUserPrincipal()).thenReturn(principal); when(principal.getName()).thenReturn("user"); final Integration integration = new Integration.Builder().build(); final Integration created = new Integration.Builder().build(); final Integration encrypted = new Integration.Builder().addTag("encrypted").build(); when(encryptionSupport.encrypt(integration)).thenReturn(encrypted); final ArgumentCaptor<Integration> persisted = ArgumentCaptor.forClass(Integration.class); when(dataManager.create(persisted.capture())).thenReturn(created); assertThat(handler.create(security, integration)).isSameAs(created); assertThat(persisted.getValue()).isEqualToIgnoringGivenFields(encrypted, "createdAt"); verify(encryptionSupport).encrypt(same(integration)); }
### 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: JaegerActivityTrackingService implements ActivityTrackingService { @Override @SuppressWarnings({"PMD.NPathComplexity"}) public List<Activity> getActivities(String integrationId, String from, Integer requestedLimit) { int lookbackDays = 30; int limit = 10; if (requestedLimit != null) { limit = requestedLimit; } if (limit > 1000) { limit = 1000; } List<JaegerQueryAPI.Trace> traces = jaegerQueryApi.tracesForService(integrationId, lookbackDays, limit); ArrayList<Activity> rc = new ArrayList<>(); for (JaegerQueryAPI.Trace trace : traces) { Activity activity = null; ArrayList<ActivityStep> steps = new ArrayList<>(); if (trace.spans != null && trace.spans.size() >= 1) { for (JaegerQueryAPI.Span span : trace.spans) { String kind = span.findTag(Tags.SPAN_KIND.getKey(), String.class); if (kind == null) { LOG.debug("Cannot find tag 'span.kind' in trace: {} and span: {}", trace.traceID, span); continue; } switch (kind) { case "activity": { activity = new Activity(); activity.setId(trace.traceID); JaegerQueryAPI.JaegerProcess process = trace.processes.get(span.processID); String version = process.findTag("integration.version", String.class); activity.setVer(version); String hostname = process.findTag("hostname", String.class); activity.setPod(hostname); activity.setStatus("done"); activity.setAt(span.startTime/1000); Boolean failed = span.findTag(Tags.ERROR.getKey(), Boolean.class); if (failed != null) { activity.setFailed(failed); } } break; case "step": { ActivityStep step = new ActivityStep(); step.setId(span.operationName); step.setAt(span.startTime); step.setDuration(span.duration*1000); List<String> messages = span.findLogs("event"); Boolean failed = span.findTag(Tags.ERROR.getKey(), Boolean.class); if (failed != null && failed) { String msg = messages != null && !messages.isEmpty() ? messages.get(0) : ""; step.setFailure(msg); } else { step.setMessages(messages); } steps.add(step); } break; default: LOG.debug("Unknown span: " + span); break; } } } if (activity != null) { steps.sort(Comparator.comparing(ActivityStep::getAt)); for (ActivityStep step: steps) { step.setAt(step.getAt()/1000); } activity.setSteps(steps); rc.add(activity); } } rc.sort(Comparator.comparing(Activity::getAt)); Collections.reverse(rc); return rc; } JaegerActivityTrackingService(JaegerQueryAPI jaegerQueryApi); @Override @SuppressWarnings({"PMD.NPathComplexity"}) List<Activity> getActivities(String integrationId, String from, Integer requestedLimit); }### Answer: @Test public void shouldRetainLastRetainActivityLogs() throws Exception { JaegerActivityTrackingService service = new JaegerActivityTrackingService(new JaegerQueryAPI("http: @Override public List<Trace> tracesForService(String service, int lookbackDays, int limit) { try { String json = resource("example-jaeger-trace-result.json"); Traces traces = JsonUtils.reader().forType(Traces.class).readValue(json); return traces.data; } catch (IOException e) { throw new WebApplicationException(e); } } }); List<Activity> activities = service.getActivities("test", null, null); assertThat(activities).isNotNull(); String activitiesJson = JsonUtils.writer().withDefaultPrettyPrinter().writeValueAsString(activities).trim(); String expectedActivitiesJson = resource("expected-activities.json").trim(); assertThatJson(activitiesJson).isEqualTo(expectedActivitiesJson); }
### Question: ExposureDeploymentDataCustomizer implements DeploymentDataCustomizer { EnumSet<Exposure> determineExposure(final IntegrationDeployment integrationDeployment) { if (integrationDeployment.getSpec().isExposable()) { return exposureHelper.determineExposure(integrationDeployment.getSpec().getExposure()); } return EnumSet.noneOf(Exposure.class); } ExposureDeploymentDataCustomizer(ExposureHelper exposureHelper); @Override DeploymentData customize(final DeploymentData data, final IntegrationDeployment integrationDeployment); }### Answer: @Test public void shouldDetermineWhenExposureIsNotNeeded() { final ExposureDeploymentDataCustomizer customizer = new ExposureDeploymentDataCustomizer( new ExposureHelper(new OpenShiftConfigurationProperties())); assertThat(customizer.determineExposure(simpleIntegration)).isEmpty(); } @Test public void shouldDetermineExposureWhen3scaleIsNotEnabled() { OpenShiftConfigurationProperties properties = new OpenShiftConfigurationProperties(); final ExposureDeploymentDataCustomizer customizer = new ExposureDeploymentDataCustomizer( new ExposureHelper(properties)); assertThat(customizer.determineExposure(exposedIntegration)).containsOnly(Exposure.SERVICE, Exposure.ROUTE); } @Test public void shouldDetermineExposureWhen3scaleIsEnabled() { final OpenShiftConfigurationProperties properties = new OpenShiftConfigurationProperties(); properties.setManagementUrlFor3scale("https: final ExposureDeploymentDataCustomizer customizer = new ExposureDeploymentDataCustomizer(new ExposureHelper(properties)); assertThat(customizer.determineExposure(exposedIntegration)).containsOnly(Exposure.SERVICE, Exposure._3SCALE); } @Test public void shouldExposeWebHooksVia3scaleWhen3scaleIsEnabled() { final OpenShiftConfigurationProperties properties = new OpenShiftConfigurationProperties(); properties.setManagementUrlFor3scale("https: final ExposureDeploymentDataCustomizer customizer = new ExposureDeploymentDataCustomizer(new ExposureHelper(properties)); final IntegrationDeployment webHookIntegration = new IntegrationDeployment.Builder() .spec(new Integration.Builder() .addFlow(new Flow.Builder().addStep(new Step.Builder().action(new ConnectorAction.Builder() .descriptor(new ConnectorDescriptor.Builder().connectorId("webhook").build()).addTag("expose") .build()).build()).build()) .build()) .build(); assertThat(customizer.determineExposure(webHookIntegration)).containsOnly(Exposure.SERVICE, Exposure._3SCALE); }
### Question: CamelKPublishHandler extends BaseCamelKHandler implements StateChangeHandler { protected Secret createIntegrationSecret(IntegrationDeployment integrationDeployment) { final Integration integration = integrationDeployment.getSpec(); Properties applicationProperties = projectGenerator.generateApplicationProperties(integration); return new SecretBuilder() .withNewMetadata() .withName(CamelKSupport.integrationName(integration.getName())) .endMetadata() .addToStringData("application.properties", CamelKSupport.propsToString(applicationProperties)) .build(); } CamelKPublishHandler( OpenShiftService openShiftService, IntegrationDao iDao, IntegrationDeploymentDao idDao, IntegrationProjectGenerator projectGenerator, IntegrationPublishValidator validator, IntegrationResourceManager resourceManager, List<CamelKIntegrationCustomizer> customizers, ControllersConfigurationProperties configuration, ExposureHelper exposureHelper); @Override Set<IntegrationDeploymentState> getTriggerStates(); @Override @SuppressWarnings("PMD.NPathComplexity") StateUpdate execute(IntegrationDeployment integrationDeployment); }### Answer: @Test public void testCamelkIntegrationSecret() throws Exception { TestResourceManager manager = new TestResourceManager(); Integration integration = manager.newIntegration( new Step.Builder() .stepKind(StepKind.endpoint) .putConfiguredProperty("username", "admin") .action(HTTP_ACTION) .connection(HTTP_CONNECTION) .build() ); ProjectGenerator generator = new ProjectGenerator(new ProjectGeneratorConfiguration(), manager, new MavenProperties()); IntegrationDeployment deployment = new IntegrationDeployment.Builder().spec(integration).build(); CamelKPublishHandler handler = new CamelKPublishHandler( new OpenShiftServiceNoOp(), null, null, generator, null, manager, Collections.emptyList(), new ControllersConfigurationProperties(), new ExposureHelper(new OpenShiftConfigurationProperties())); Secret secret = handler.createIntegrationSecret(deployment); assertThat(secret.getMetadata()).hasFieldOrPropertyWithValue("name", "i-test-integration"); assertThat(secret.getStringData()).containsKeys("application.properties"); Properties actual = CamelKSupport.secretToProperties(secret); Properties expected = generator.generateApplicationProperties(integration); assertThat(actual).isEqualTo(expected); assertThat(actual).containsEntry("flow-0.http4-0.username", "admin"); }
### 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: OpenApiCustomizer implements CamelKIntegrationCustomizer { public OpenApiCustomizer( ControllersConfigurationProperties configuration, IntegrationResourceManager resourceManager) { this.configuration = configuration; this.resourceManager = resourceManager; } OpenApiCustomizer( ControllersConfigurationProperties configuration, IntegrationResourceManager resourceManager); @Override Integration customize(IntegrationDeployment deployment, Integration integration, EnumSet<Exposure> exposure); }### Answer: @Test public void testOpenApiCustomizer() throws Exception { URL location = getClass().getResource("/petstore.json"); byte[] content = Files.readAllBytes(Paths.get(location.toURI())); TestResourceManager manager = new TestResourceManager(); manager.put("petstore", new OpenApi.Builder().document(content).id("petstore").build()); Integration integration = new Integration.Builder() .id("test-integration") .name("Test Integration") .description("This is a test integration!") .addResource(new ResourceIdentifier.Builder() .kind(Kind.OpenApi) .id("petstore") .build()) .build(); IntegrationDeployment deployment = new IntegrationDeployment.Builder() .userId("user") .id("idId") .spec(integration) .build(); CamelKIntegrationCustomizer customizer = new OpenApiCustomizer(new ControllersConfigurationProperties(), manager); 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().getConfiguration()).hasSize(0); assertThat(i.getSpec().getSources()).anyMatch( s -> Objects.equals("openapi-routes", s.getDataSpec().getName()) && Objects.equals("xml", s.getLanguage()) && !s.getDataSpec().getCompression().booleanValue() ); assertThat(i.getSpec().getSources()).anyMatch( s -> Objects.equals("openapi-endpoint", s.getDataSpec().getName()) && Objects.equals("xml", s.getLanguage()) && !s.getDataSpec().getCompression().booleanValue() ); assertThat(i.getSpec().getResources()).anyMatch( s -> Objects.equals("openapi.json", s.getDataSpec().getName()) && Objects.equals("data", s.getType()) && s.getDataSpec().getCompression().booleanValue() && (s.getDataSpec().getContent().getBytes(UTF_8).length <= content.length) ); }
### 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: WebhookCustomizer implements CamelKIntegrationCustomizer { @Override public Integration customize(IntegrationDeployment deployment, Integration integration, EnumSet<Exposure> exposure) { IntegrationSpec.Builder spec = new IntegrationSpec.Builder(); if (integration.getSpec() != null) { spec = spec.from(integration.getSpec()); } if (!CamelKSupport.isWebhookPresent(deployment.getSpec())) { return integration; } try { spec.addConfiguration( new ConfigurationSpec.Builder() .type("property") .value("customizer.platform-http.path=/webhook/") .build() ); } catch (Exception e) { throw new IllegalStateException(e); } integration.setSpec(spec.build()); return integration; } @Override Integration customize(IntegrationDeployment deployment, Integration integration, EnumSet<Exposure> exposure); }### Answer: @Test public void testOpenApiCustomizer() throws Exception { TestResourceManager manager = new TestResourceManager(); Connector connector; ConnectorAction webhookIncomingAction; try (InputStream is = WebhookCustomizerTest.class.getResourceAsStream("/META-INF/syndesis/connector/webhook.json")) { connector = JsonUtils.readFromStream(is, Connector.class); webhookIncomingAction = connector.getActions(ConnectorAction.class).stream() .filter(a -> a.getId().get().equals("io.syndesis:webhook-incoming")) .findFirst() .orElseThrow(IllegalArgumentException::new); } webhookIncomingAction = webhookIncomingAction.builder().descriptor(new ConnectorDescriptor.Builder().connectorId("webhook").build()).build(); Integration integration = manager.newIntegration( new Step.Builder() .stepKind(StepKind.endpoint) .putConfiguredProperty("contextPath", "token") .action(webhookIncomingAction) .connection(new Connection.Builder() .connector(connector) .build()) .build() ); IntegrationDeployment deployment = new IntegrationDeployment.Builder() .userId("user") .id("idId") .spec(integration) .build(); CamelKIntegrationCustomizer customizer = new WebhookCustomizer(); 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().getConfiguration()).hasSize(1); assertThat(i.getSpec().getConfiguration()).anyMatch( c -> Objects.equals("customizer.platform-http.path=/webhook/", c.getValue()) && Objects.equals("property", c.getType()) ); }
### 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: TemplatingCustomizer implements CamelKIntegrationCustomizer { @Override public Integration customize(IntegrationDeployment deployment, Integration integration, EnumSet<Exposure> exposure) { Set<TemplateStepLanguage> languages = deployment.getSpec().getFlows().stream() .flatMap(f -> f.getSteps().stream()) .filter(s -> s.getStepKind() == StepKind.template) .flatMap(s -> asStream(Optional.of(s.getConfiguredProperties().get("language")))) .map(TemplateStepLanguage::stepLanguage) .collect(Collectors.toSet()); if (!languages.isEmpty()) { IntegrationSpec.Builder spec = new IntegrationSpec.Builder(); if (integration.getSpec() != null) { spec = spec.from(integration.getSpec()); } for (TemplateStepLanguage lan : languages) { spec = spec.addDependencies("mvn:" + lan.mavenDependency()); } integration.setSpec(spec.build()); } return integration; } @Override Integration customize(IntegrationDeployment deployment, Integration integration, EnumSet<Exposure> exposure); }### Answer: @Test public void testTemplatingCustomizer() { TestResourceManager manager = new TestResourceManager(); Integration integration = manager.newIntegration( new Step.Builder() .stepKind(StepKind.template) .putConfiguredProperty("language", "MUSTACHE") .build(), new Step.Builder() .stepKind(StepKind.template) .putConfiguredProperty("language", "VELOCITY") .build() ); IntegrationDeployment deployment = new IntegrationDeployment.Builder() .userId("user") .id("idId") .spec(integration) .build(); CamelKIntegrationCustomizer customizer = new TemplatingCustomizer(); 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().getDependencies()).anyMatch(s -> s.startsWith("mvn:org.apache.camel:camel-mustache")); assertThat(i.getSpec().getDependencies()).anyMatch(s -> s.startsWith("mvn:org.apache.camel:camel-velocity")); }
### 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: OasModelHelper { public static String sanitizeTag(final String tag) { if (StringUtils.isEmpty(tag)) { return null; } final String sanitized = JSONDB_DISALLOWED_KEY_CHARS.matcher(tag).replaceAll("").trim(); if (sanitized.length() > 768) { return sanitized.substring(0, Math.min(tag.length(), 768)); } return sanitized; } 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 shouldSanitizeTags() { assertThat(OasModelHelper.sanitizeTag("tag")).isEqualTo("tag"); assertThat(OasModelHelper.sanitizeTag(".]t%a$g#[/")).isEqualTo("tag"); final char[] str = new char[1024]; final String randomString = IntStream.range(0, str.length) .map(x -> (int) (Character.MAX_CODE_POINT * Math.random())).mapToObj(i -> new String(Character.toChars(i))) .collect(Collectors.joining("")); final String sanitized = OasModelHelper.sanitizeTag(randomString); assertThatCode(() -> JsonRecordSupport.validateKey(sanitized)).doesNotThrowAnyException(); }
### 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: OpenApiModelParser { static JsonNode convertToJson(final String specification) throws IOException { final JsonNode specRoot; if (isJsonSpec(specification)) { specRoot = JsonUtils.reader().readTree(specification); } else { specRoot = JsonUtils.convertValue(YAML_PARSER.load(specification), JsonNode.class); } return specRoot; } private OpenApiModelParser(); static OpenApiModelInfo parse(final String specification, final APIValidationContext validationContext); static boolean isJsonSpec(final String specification); static String resolve(URL url); }### Answer: @Test public void convertingToJsonShouldNotLooseSecurityDefinitions() throws IOException { final String definition = "{\"swagger\":\"2.0\",\"securityDefinitions\": {\n" + " \"api-key-header\": {\n" + " \"type\": \"apiKey\",\n" + " \"name\": \"API-KEY\",\n" + " \"in\": \"header\"\n" + " },\n" + " \"api-key-parameter\": {\n" + " \"type\": \"apiKey\",\n" + " \"name\": \"api_key\",\n" + " \"in\": \"query\"\n" + " }\n" + " }}"; final JsonNode node = OpenApiModelParser.convertToJson(definition); final JsonNode securityDefinitions = node.get("securityDefinitions"); assertThat(securityDefinitions.get("api-key-header")).isEqualTo(newNode() .put("type", "apiKey") .put("name", "API-KEY") .put("in", "header")); assertThat(securityDefinitions.get("api-key-parameter")).isEqualTo(newNode() .put("type", "apiKey") .put("name", "api_key") .put("in", "query")); } @Test public void convertingToJsonShouldNotLooseSecurityRequirements() throws IOException { final String definition = "{\"swagger\":\"2.0\",\"paths\":{\"/api\":{\"get\":{\"security\":[{\"secured\":[\"scope\"]}]}}}}"; final JsonNode node = OpenApiModelParser.convertToJson(definition); assertThat(node.get("paths").get("/api").get("get").get("security")) .hasOnlyOneElementSatisfying(securityRequirement -> assertThat(securityRequirement.get("secured")) .hasOnlyOneElementSatisfying(scope -> assertThat(scope.asText()).isEqualTo("scope"))); }
### 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: OpenApiGenerator implements APIGenerator { @Override public APISummary info(final String specification, final APIValidationContext validation) { final OpenApiModelInfo modelInfo = OpenApiModelParser.parse(specification, validation); final OasDocument model = modelInfo.getModel(); if (model == null) { return new APISummary.Builder().errors(modelInfo.getErrors()).warnings(modelInfo.getWarnings()).build(); } final OasPaths paths = model.paths; final ActionsSummary actionsSummary = determineSummaryFrom(OasModelHelper.getPathItems(paths)); final Info info = model.info; final String title = Optional.ofNullable(info).map(i -> i.title).orElse("unspecified"); final String description = Optional.ofNullable(info).map(i -> i.description).orElse("unspecified"); return new APISummary.Builder() .name(title) .description(description) .actionsSummary(actionsSummary) .errors(modelInfo.getErrors()) .warnings(modelInfo.getWarnings()) .putConfiguredProperty("specification", modelInfo.getResolvedSpecification()) .build(); } @Override @SuppressWarnings({"PMD.ExcessiveMethodLength"}) APIIntegration generateIntegration(final String specification, final ProvidedApiTemplate template); @Override APISummary info(final String specification, final APIValidationContext validation); @Override Integration updateFlowExcerpts(final Integration integration); }### Answer: @Test public void infoShouldHandleNullModels() { final OpenApiGenerator generator = new OpenApiGenerator(); final APISummary summary = generator.info("invalid", APIValidationContext.NONE); assertThat(summary).isNotNull(); assertThat(summary.getErrors()).hasSize(1) .allSatisfy(v -> assertThat(v.message()).startsWith("This document cannot be uploaded. Provide an OpenAPI document")); assertThat(summary.getWarnings()).isEmpty(); } @Test public void infoShouldHandleNullPaths() { final OpenApiGenerator generator = new OpenApiGenerator(); final APISummary summary = generator.info("{\"swagger\": \"2.0\"}", APIValidationContext.NONE); assertThat(summary).isNotNull(); assertThat(summary.getErrors()).isEmpty(); assertThat(summary.getWarnings()).isEmpty(); } @Test public void infoShouldHandleNullSpecifications() { final OpenApiGenerator generator = new OpenApiGenerator(); final APISummary summary = generator.info(null, APIValidationContext.NONE); assertThat(summary).isNotNull(); assertThat(summary.getErrors()).hasSize(1).allSatisfy(v -> assertThat(v.message()).startsWith("Unable to resolve OpenAPI document from")); assertThat(summary.getWarnings()).isEmpty(); }
### Question: OpenApiGenerator implements APIGenerator { @Override @SuppressWarnings({"PMD.ExcessiveMethodLength"}) public APIIntegration generateIntegration(final String specification, final ProvidedApiTemplate template) { final OpenApiModelInfo info = OpenApiModelParser.parse(specification, APIValidationContext.NONE); final OasDocument openApiDoc = info.getModel(); final String name = Optional.ofNullable(openApiDoc.info) .flatMap(i -> Optional.ofNullable(i.title)) .orElse("Untitled"); final Integration.Builder integration = new Integration.Builder() .addTag("api-provider") .createdAt(System.currentTimeMillis()) .name(name); switch (info.getApiVersion()) { case V2: oas20FlowGenerator.generateFlows(info.getV2Model(), integration, info, template); break; case V3: oas30FlowGenerator.generateFlows(info.getV3Model(), integration, info, template); break; default: throw new IllegalStateException(String.format("Unable to retrieve integration flow generator for OpenAPI document type '%s'", openApiDoc.getClass())); } final byte[] updatedSpecification = Library.writeDocumentToJSONString(openApiDoc).getBytes(StandardCharsets.UTF_8); final String apiId = KeyGenerator.createKey(); final OpenApi api = new OpenApi.Builder() .id(apiId) .name(name) .document(updatedSpecification) .putMetadata("Content-Type", getContentType(specification)) .build(); integration.addResource(new ResourceIdentifier.Builder() .id(apiId) .kind(Kind.OpenApi) .build()); return new APIIntegration(integration.build(), api); } @Override @SuppressWarnings({"PMD.ExcessiveMethodLength"}) APIIntegration generateIntegration(final String specification, final ProvidedApiTemplate template); @Override APISummary info(final String specification, final APIValidationContext validation); @Override Integration updateFlowExcerpts(final Integration integration); }### Answer: @Test public void testEmptyOperationSummary() throws IOException { final ProvidedApiTemplate template = new ProvidedApiTemplate(dummyConnection(), "fromAction", "toAction"); final String specification = TestHelper.resource("/openapi/v2/empty-summary.json"); final OpenApiGenerator generator = new OpenApiGenerator(); final APIIntegration apiIntegration = generator.generateIntegration(specification, template); assertThat(apiIntegration).isNotNull(); assertThat(apiIntegration.getIntegration().getFlows()).hasSize(3); final List<Flow> flows = apiIntegration.getIntegration().getFlows(); assertThat(flows).filteredOn(operationIdEquals("operation-1")).first() .hasFieldOrPropertyWithValue("description", Optional.of("GET /hi")) .hasFieldOrPropertyWithValue("name", "Receiving GET request on /hi"); assertThat(flows).filteredOn(operationIdEquals("operation-2")).first() .hasFieldOrPropertyWithValue("description", Optional.of("POST /hi")) .hasFieldOrPropertyWithValue("name", "post operation"); assertThat(flows).filteredOn(operationIdEquals("operation-3")).first() .hasFieldOrPropertyWithValue("description", Optional.of("PUT /hi")) .hasFieldOrPropertyWithValue("name", "Receiving PUT request on /hi"); }
### 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: Oas30ValidationRules extends OpenApiValidationRules<Oas30Response, Oas30SecurityScheme, Oas30SchemaDefinition> { static OpenApiModelInfo validateServerBasePaths(OpenApiModelInfo info) { if (info.getModel() == null) { return info; } final Oas30Document openApiDoc = info.getV3Model(); if (openApiDoc.servers == null || openApiDoc.servers.isEmpty()) { return info; } List<String> basePaths = openApiDoc.servers.stream().map(Oas30ModelHelper::getBasePath).collect(Collectors.toList()); if (basePaths.size() > 1 && new HashSet<>(basePaths).size() == basePaths.size()) { return new OpenApiModelInfo.Builder().createFrom(info) .addWarning(new Violation.Builder() .error("differing-base-paths") .message(String.format("Specified servers do not share the same base path. " + "REST endpoint will use '%s' as base path.", Oas30ModelHelper.getBasePath(openApiDoc))) .build()) .build(); } return info; } Oas30ValidationRules(APIValidationContext context); static Oas30ValidationRules get(final APIValidationContext context); }### Answer: @Test public void shouldNotGenerateWarningForSameServerBasePath() { final Oas30Document openApiDoc = new Oas30Document(); openApiDoc.addServer("https: openApiDoc.addServer("https: openApiDoc.addServer("https: final OpenApiModelInfo info = new OpenApiModelInfo.Builder().model(openApiDoc).build(); final OpenApiModelInfo validated = Oas30ValidationRules.validateServerBasePaths(info); assertThat(validated.getErrors()).isEmpty(); assertThat(validated.getWarnings()).isEmpty(); } @Test public void shouldGenerateWarningForDifferingServerBasePaths() { final Oas30Document openApiDoc = new Oas30Document(); openApiDoc.addServer("https: openApiDoc.addServer("https: openApiDoc.addServer("https: final OpenApiModelInfo info = new OpenApiModelInfo.Builder().model(openApiDoc).build(); final OpenApiModelInfo validated = Oas30ValidationRules.validateServerBasePaths(info); assertThat(validated.getErrors()).isEmpty(); assertThat(validated.getWarnings()).containsOnly(new Violation.Builder().error("differing-base-paths") .message("Specified servers do not share the same base path. REST endpoint will use '/development' as base path.").build()); }
### 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: OpenApiConnectorGenerator extends ConnectorGenerator { final Connector configureConnector(final ConnectorTemplate connectorTemplate, final Connector connector, final ConnectorSettings connectorSettings) { final Connector.Builder builder = new Connector.Builder().createFrom(connector); final OpenApiModelInfo info = parseSpecification(connectorSettings, APIValidationContext.NONE); final OasDocument openApiDoc = info.getModel(); addGlobalParameters(builder, info); final OasPaths paths = ofNullable(openApiDoc.paths) .orElse(openApiDoc.createPaths()); final String connectorId = connector.getId().orElseThrow(() -> new IllegalArgumentException("Missing connector identifier")); final List<ConnectorAction> actions = new ArrayList<>(); final Map<String, Integer> operationIdCounts = new HashMap<>(); for (final OasPathItem path : OasModelHelper.getPathItems(paths)) { final Map<String, OasOperation> operationMap = OasModelHelper.getOperationMap(path); for (final Map.Entry<String, OasOperation> entry : operationMap.entrySet()) { final OasOperation operation = entry.getValue(); final String operationId = operation.operationId; if (operationId == null) { operation.operationId = operationIdGenerator.get(); } else { final Integer count = operationIdCounts.compute(operationId, (id, currentCount) -> ofNullable(currentCount).map(c -> ++c).orElse(0)); if (count > 0) { operation.operationId = operationId + count; } } final ConnectorDescriptor descriptor = createDescriptor(connectorId, info, operation); final OperationDescription description = OasModelHelper.operationDescriptionOf(openApiDoc, operation, (m, p) -> "Send " + m + " request to " + p); final ConnectorAction action = new ConnectorAction.Builder() .id(createActionId(connectorId, operation)) .name(description.name) .description(description.description) .pattern(Action.Pattern.To) .descriptor(descriptor).tags(OasModelHelper.sanitizeTags(operation.tags).distinct()::iterator) .build(); actions.add(action); } } actions.sort(ActionComparator.INSTANCE); builder.addAllActions(actions); builder.putConfiguredProperty(SPECIFICATION, SpecificationOptimizer.minimizeForComponent(openApiDoc)); return builder.build(); } 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 shouldMakeNonUniqueOperationIdsUnique() { final Oas20Document openApiDoc = new Oas20Document(); openApiDoc.paths = openApiDoc.createPaths(); Oas20PathItem pathItem = (Oas20PathItem) openApiDoc.paths.createPathItem("/path"); pathItem.get = pathItem.createOperation("get"); pathItem.get.operationId = "foo"; pathItem.post = pathItem.createOperation("post"); pathItem.post.operationId = "foo"; pathItem.put = pathItem.createOperation("put"); pathItem.put.operationId = "bar"; openApiDoc.paths.addPathItem("/path", pathItem); final Connector generated = generator.configureConnector(ApiConnectorTemplate.SWAGGER_TEMPLATE, new Connector.Builder().id("connector1").build(), createSettingsFrom(openApiDoc)); final List<ConnectorAction> actions = generated.getActions(); assertThat(actions).hasSize(3); assertThat(actions.get(0).getId()).hasValueSatisfying(id -> assertThat(id).endsWith("foo")); assertThat(actions.get(1).getId()).hasValueSatisfying(id -> assertThat(id).endsWith("foo1")); assertThat(actions.get(2).getId()).hasValueSatisfying(id -> assertThat(id).endsWith("bar")); }
### 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: SoapApiModelParser { public static SoapApiModelInfo parseSoapAPI(final String specification, final String wsdlURL) { SoapApiModelInfo.Builder builder = new SoapApiModelInfo.Builder(); try { final String resolvedSpecification; final Optional<String> resolvedWsdlURL; final boolean isHttpUrl = specification.toLowerCase(Locale.US).startsWith("http"); if (isHttpUrl) { final URL httpURL = new URL(specification); resolvedWsdlURL = Optional.of(httpURL.toString()); final HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection(); connection.setRequestMethod("GET"); if (connection.getResponseCode() > 299) { throw new IOException(connection.getResponseMessage()); } resolvedSpecification = IOStreams.readText(connection.getInputStream()); } else { resolvedSpecification = specification; resolvedWsdlURL = Optional.ofNullable(wsdlURL); } builder.wsdlURL(resolvedWsdlURL); final String condensedSpecification = condenseWSDL(resolvedSpecification); builder.resolvedSpecification(condensedSpecification); final InputSource inputSource = new InputSource(new StringReader(condensedSpecification)); final Definition definition = getWsdlReader().readWSDL(resolvedWsdlURL.orElse(null), inputSource); builder.model(definition); validateModel(definition, builder); final SoapApiModelInfo localBuild = builder.build(); if (localBuild.getServices().size() == 1) { final QName defaultService = localBuild.getServices().get(0); builder.defaultService(defaultService); final List<String> ports = localBuild.getPorts().get(defaultService); if (ports.size() == 1) { final String defaultPort = ports.get(0); builder.defaultPort(defaultPort); String locationURI = getAddress(definition, defaultService, defaultPort); if (locationURI != null) { builder.defaultAddress(locationURI); } } } } catch (IOException e) { addError(builder, "Error reading WSDL: " + e.getMessage(), e); } catch (WSDLException | BusException e) { addError(builder, "Error parsing WSDL: " + e.getMessage(), e); } catch (TransformerException e) { addError(builder, "Error condensing WSDL: " + e.getMessage(), e); } return builder.build(); } private SoapApiModelParser(); static SoapApiModelInfo parseSoapAPI(final String specification, final String wsdlURL); static String getAddress(Definition definition, QName service, String port); static ActionsSummary parseActionsSummary(Definition definition, QName serviceName, String portName); static List<ConnectorAction> parseActions(Definition definition, QName serviceName, QName portName, String connectorId); }### Answer: @Test public void parseSoapAPI() { final SoapApiModelInfo soapApiModelInfo = SoapApiModelParser.parseSoapAPI(this.specification, this.specification); assertThat(soapApiModelInfo).isNotNull(); assertThat(soapApiModelInfo.getErrors()).isEmpty(); assertThat(soapApiModelInfo.getWarnings()).isEmpty(); assertThat(soapApiModelInfo.getResolvedSpecification()).isNotNull(); assertThat(soapApiModelInfo.getModel()).isNotNull(); assertThat(soapApiModelInfo.getServices()).isNotNull(); assertThat(soapApiModelInfo.getPorts()).isNotNull(); assertThat(soapApiModelInfo.getDefaultService()).isNotNull(); assertThat(soapApiModelInfo.getDefaultPort()).isNotNull(); assertThat(soapApiModelInfo.getDefaultAddress()).isNotNull(); }
### Question: ConnectorGenerator { protected final Connector baseConnectorFrom(final ConnectorTemplate connectorTemplate, final ConnectorSettings connectorSettings) { final Set<String> properties = connectorTemplate.getProperties().keySet(); final Map<String, String> configuredProperties = connectorSettings.getConfiguredProperties() .entrySet().stream() .filter(e -> properties.contains(e.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); configuredProperties.putAll(baseConnector.getConfiguredProperties()); final String name = Optional.ofNullable(connectorSettings.getName()) .orElseGet(() -> determineConnectorName(connectorTemplate, connectorSettings)); final String description = Optional.ofNullable(connectorSettings.getDescription()) .orElseGet(() -> determineConnectorDescription(connectorTemplate, connectorSettings)); final Optional<ConnectorGroup> connectorGroup = connectorTemplate.getConnectorGroup(); final String icon; if (connectorSettings.getIcon() != null) { icon = connectorSettings.getIcon(); } else { icon = IconGenerator.generate(connectorTemplate.getId().get(), name); } return new Connector.Builder() .createFrom(baseConnector) .id(KeyGenerator.createKey()) .name(name) .description(description) .icon(icon) .configuredProperties(configuredProperties) .connectorGroup(connectorGroup) .connectorGroupId(connectorGroup.map(ConnectorGroup::getId).orElse(Optional.empty())) .build(); } protected ConnectorGenerator(final Connector baseConnector); abstract Connector generate(ConnectorTemplate connectorTemplate, ConnectorSettings connectorSettings); abstract APISummary info(ConnectorTemplate connectorTemplate, ConnectorSettings connectorSettings); }### Answer: @Test public void shouldCreateBaseConnectors() { final ConnectorSettings settings = new ConnectorSettings.Builder().putConfiguredProperty("property2", "value2").build(); final Connector connector = generator.baseConnectorFrom(template, settings); assertThat(connector).isEqualToIgnoringGivenFields( new Connector.Builder() .name("test-name") .description("test-description") .addTags("from-connector") .connectorGroup(template.getConnectorGroup()) .connectorGroupId("template-group") .properties(template.getConnectorProperties()) .putConfiguredProperty("property2", "value2") .build(), "id", "icon"); assertThat(connector.getIcon()).isEqualTo("data:image/svg+xml,dummy"); } @Test public void shouldCreateBaseConnectorsWithGivenNameAndDescription() { final ConnectorSettings settings = new ConnectorSettings.Builder().name("given-name").description("given-description") .putConfiguredProperty("property2", "value2").build(); final Connector connector = generator.baseConnectorFrom(template, settings); assertThat(connector).isEqualToIgnoringGivenFields( new Connector.Builder() .name("given-name") .description("given-description") .addTags("from-connector") .connectorGroup(template.getConnectorGroup()) .connectorGroupId("template-group") .properties(template.getConnectorProperties()) .putConfiguredProperty("property2", "value2").build(), "id", "icon"); assertThat(connector.getIcon()).isEqualTo("data:image/svg+xml,dummy"); }
### 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: CredentialProviderRegistry implements CredentialProviderLocator { @Override public CredentialProvider providerWithId(final String providerId) { final Connector connector = dataManager.fetch(Connector.class, providerId); if (connector == null) { throw new IllegalArgumentException("Unable to find connector with id: " + providerId); } final String providerToUse = determineProviderFrom(connector); final CredentialProviderFactory credentialProviderFactory = credentialProviderFactories.get(providerToUse); if (credentialProviderFactory == null) { throw new IllegalArgumentException("Unable to locate credential provider factory with id: " + providerId); } final SocialProperties socialProperties = createSocialProperties(providerToUse, connector); final CredentialProvider providerWithId = credentialProviderFactory.create(socialProperties); if (providerWithId == null) { throw new IllegalArgumentException("Unable to locate credential provider with id: " + providerId); } return providerWithId; } CredentialProviderRegistry(final DataManager dataManager); @Override CredentialProvider providerWithId(final String providerId); }### Answer: @Test public void shouldComplainAboutUnregisteredProviders() { final DataManager dataManager = mock(DataManager.class); final CredentialProviderRegistry registry = new CredentialProviderRegistry(dataManager); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> registry.providerWithId("unregistered")) .withMessage("Unable to find connector with id: unregistered"); } @Test public void shouldFetchProvidersFromDataManager() { final DataManager dataManager = mock(DataManager.class); final CredentialProviderRegistry registry = new CredentialProviderRegistry(dataManager); final Connector connector = new Connector.Builder().id("test-provider") .putProperty("clientId", new ConfigurationProperty.Builder().addTag(Credentials.CLIENT_ID_TAG).build()) .putProperty("clientSecret", new ConfigurationProperty.Builder().addTag(Credentials.CLIENT_SECRET_TAG).build()) .putConfiguredProperty("clientId", "a-client-id").putConfiguredProperty("clientSecret", "a-client-secret") .build(); when(dataManager.fetch(Connector.class, "test-provider")).thenReturn(connector); assertThat(registry.providerWithId("test-provider")).isInstanceOfSatisfying(TestCredentialProvider.class, p -> { assertThat(p.getProperties().getAppId()).isEqualTo("a-client-id"); assertThat(p.getProperties().getAppSecret()).isEqualTo("a-client-secret"); }); }
### 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 Set<CredentialFlowState> restoreFrom(final Restorer restore, final HttpServletRequest request) { final Cookie[] servletCookies = request.getCookies(); if (ArrayUtils.isEmpty(servletCookies)) { return Collections.emptySet(); } final List<javax.ws.rs.core.Cookie> credentialCookies = Arrays.stream(servletCookies) .filter(c -> c.getName().startsWith(CredentialFlowState.CREDENTIAL_PREFIX)) .map(CredentialFlowStateHelper::toJaxRsCookie).collect(Collectors.toList()); try { return restore.apply(credentialCookies, CredentialFlowState.class); } catch (final IllegalArgumentException e) { return Collections.emptySet(); } } private CredentialFlowStateHelper(); }### Answer: @Test public void ifCookieNameDoesNotMatchShouldReturnEmptySet() { final Cookie cookie = new Cookie("notMatching", "anyValue"); final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getCookies()).thenReturn(new Cookie[] {cookie}); final Set<CredentialFlowState> got = CredentialFlowStateHelper.restoreFrom((cookies, cls) -> { assertThat(cookies).isEmpty(); return Collections.emptySet(); }, request); assertThat(got).isEmpty(); } @Test public void ifRestoreFailsShouldReturnEmptySet() { final Cookie cookie = new Cookie(CredentialFlowState.CREDENTIAL_PREFIX + "key", "anyValue"); final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getCookies()).thenReturn(new Cookie[] {cookie}); final Set<CredentialFlowState> got = CredentialFlowStateHelper.restoreFrom((cookies, cls) -> { assertThat(cookies.get(0).getValue()).isEqualTo("anyValue"); throw new IllegalArgumentException(); }, request); assertThat(got).isEmpty(); } @Test public void shouldRestoreCookiesToStreamOfState() { final CredentialFlowState expected1 = new OAuth2CredentialFlowState.Builder().connectorId("connectorId") .key("key1").build(); final CredentialFlowState expected2 = new OAuth2CredentialFlowState.Builder().connectorId("connectorId") .key("key2").build(); final Cookie cookie1 = new Cookie(CredentialFlowState.CREDENTIAL_PREFIX + "key1", "anyValue"); final Cookie cookie2 = new Cookie(CredentialFlowState.CREDENTIAL_PREFIX + "key2", "anyValue"); final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getCookies()).thenReturn(new Cookie[] {cookie1, cookie2}); when(request.getCookies()).thenReturn(new Cookie[] {cookie1, cookie2}); final Set<CredentialFlowState> states = CredentialFlowStateHelper.restoreFrom((cookies, cls) -> { assertThat(cookies).allSatisfy(cookie -> assertThat(cookie.getValue()).isEqualTo("anyValue")); return cookies.stream() .map(cookie -> new OAuth2CredentialFlowState.Builder().connectorId("connectorId") .key(cookie.getName().substring(CredentialFlowState.CREDENTIAL_PREFIX.length())).build()) .collect(Collectors.toSet()); }, request); assertThat(states).containsOnly(expected1, expected2); } @Test public void shouldReturnEmptyStreamIfNoCookiesPresent() { final HttpServletRequest request = mock(HttpServletRequest.class); final Set<CredentialFlowState> streamFromNullCookies = CredentialFlowStateHelper.restoreFrom((c, cls) -> null, request); assertThat(streamFromNullCookies).isEmpty(); when(request.getCookies()).thenReturn(new Cookie[0]); final Set<CredentialFlowState> streamFromEmptyCookies = CredentialFlowStateHelper.restoreFrom((c, cls) -> null, request); assertThat(streamFromEmptyCookies).isEmpty(); }
### 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: Credentials { public Connection apply(final Connection updatedConnection, final CredentialFlowState flowState) { final CredentialProvider credentialProvider = providerFrom(flowState); final Connection withDerivedFlag = new Connection.Builder().createFrom(updatedConnection).isDerived(true).build(); final Connection appliedConnection = credentialProvider.applyTo(withDerivedFlag, flowState); final Map<String, String> configuredProperties = appliedConnection.getConfiguredProperties(); final Map<String, ConfigurationProperty> properties = updatedConnection.getConnector() .orElseGet(() -> dataManager.fetch(Connector.class, updatedConnection.getConnectorId())).getProperties(); final Map<String, String> encryptedConfiguredProperties = encryptionComponent.encryptPropertyValues(configuredProperties, properties); return new Connection.Builder().createFrom(appliedConnection).configuredProperties(encryptedConfiguredProperties).build(); } @Autowired Credentials(final CredentialProviderLocator credentialProviderLocator, final EncryptionComponent encryptionComponent, final DataManager dataManager); AcquisitionFlow acquire(final String providerId, final URI baseUrl, final URI returnUrl); AcquisitionMethod acquisitionMethodFor(final String providerId); Connection apply(final Connection updatedConnection, final CredentialFlowState flowState); CredentialFlowState finishAcquisition(final CredentialFlowState flowState, final URI baseUrl); static final String ACCESS_TOKEN_TAG; static final String ACCESS_TOKEN_URL_TAG; static final String AUTHENTICATION_TYPE_TAG; static final String AUTHENTICATION_URL_TAG; static final String AUTHORIZATION_URL_TAG; static final String AUTHORIZE_USING_PARAMETERS_TAG; static final String CLIENT_ID_TAG; static final String CLIENT_SECRET_TAG; static final String SCOPE_TAG; static final String TOKEN_STRATEGY_TAG; static final String ADDITIONAL_QUERY_PARAMETERS_TAG; }### Answer: @Test public void shouldApplyReceivedCredentialsToConnections() { final CredentialProvider credentialProvider = mock(CredentialProvider.class); when(locator.providerWithId("providerId")).thenReturn(credentialProvider); final CredentialFlowState flowState = new OAuth2CredentialFlowState.Builder().providerId("providerId") .returnUrl(URI.create("/ui#state")).code("code").state("state").build(); final Connection connection = new Connection.Builder() .connector(new Connector.Builder().putProperty("key", new ConfigurationProperty.Builder().build()).build()) .build(); when(credentialProvider.applyTo(new Connection.Builder().createFrom(connection).isDerived(true).build(), flowState)) .then(a -> new Connection.Builder().createFrom(a.getArgument(0)) .putConfiguredProperty("key", "value").build()); final Connection finishedConnection = credentials.apply(connection, flowState); assertThat(finishedConnection).isNotNull(); assertThat(finishedConnection.getConfiguredProperties()).contains(entry("key", "value")); assertThat(finishedConnection.isDerived()).isTrue(); }
### 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 { @Override public List<String> getPaths(final String kind, final String type, final String specification, final Optional<byte[]> exemplar) { final JsonSchema schema; try { schema = JsonSchemaUtils.reader().readValue(specification); } catch (final IOException e) { LOG.warn("Unable to parse the given JSON schema, increase log level to DEBUG to see the schema being parsed", e); LOG.debug(specification); return Collections.emptyList(); } String context = null; final List<String> paths = new ArrayList<>(); ObjectSchema objectSchema; if (schema.isObjectSchema()) { objectSchema = schema.asObjectSchema(); } else if (schema.isArraySchema()) { objectSchema = getItemSchema(schema.asArraySchema()); paths.addAll(COLLECTION_PATHS); context = ARRAY_CONTEXT; } else { throw new IllegalStateException(String.format("Unexpected schema type %s - expected object or array schema", schema.getType())); } if (objectSchema != null) { final Map<String, JsonSchema> properties = objectSchema.getProperties(); fetchPaths(context, paths, properties); } return Collections.unmodifiableList(paths); } @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 shouldCollectPathsFromJsonSchema() throws IOException { final List<String> paths = inspector.getPaths(JSON_SCHEMA_KIND, "", IOStreams.readText(getSalesForceContactSchema()), Optional.empty()); assertSalesforceContactProperties(paths); assertThat(paths).doesNotContainAnyElementsOf(JsonSchemaInspector.COLLECTION_PATHS); } @Test @Parameters({"/petstore-unified-schema.json", "/petstore-unified-schema-draft-4.json", "/petstore-unified-schema-draft-6.json"}) public void shouldCollectPathsFromUnifiedJsonSchema(final String schemaPath) throws IOException { final List<String> paths = inspector.getPaths(JSON_SCHEMA_KIND, "", IOStreams.readText(getPetstoreUnifiedSchema(schemaPath)), Optional.empty()); assertPetstoreProperties(paths); assertThat(paths).doesNotContainAnyElementsOf(JsonSchemaInspector.COLLECTION_PATHS); } @Test public void shouldCollectPathsFromJsonArraysSchema() throws IOException { final List<String> paths = inspector.getPaths(JSON_SCHEMA_KIND, "", getSalesForceContactArraySchema(), Optional.empty()); assertSalesforceContactArrayProperties(paths); assertThat(paths).containsAll(JsonSchemaInspector.COLLECTION_PATHS); }
### 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: JsonInstanceInspector implements Inspector { @Override @SuppressWarnings("unchecked") public List<String> getPaths(String kind, String type, String specification, Optional<byte[]> exemplar) { if (specification == null) { return Collections.emptyList(); } String context = null; final List<String> paths = new ArrayList<>(); try { Map<String, Object> json; if (JsonUtils.isJsonArray(specification)) { List<Object> items = JsonUtils.reader().forType(List.class).readValue(specification); paths.addAll(COLLECTION_PATHS); context = ARRAY_CONTEXT; if (items.isEmpty()) { return Collections.unmodifiableList(paths); } json = (Map<String, Object>) items.get(0); } else { json = JsonUtils.reader().forType(Map.class).readValue(specification); } fetchPaths(context, paths, json); } catch (final IOException e) { LOG.warn("Unable to parse the given JSON instance, increase log level to DEBUG to see the instance being parsed"); LOG.debug(specification); LOG.trace("Unable to parse the given JSON instance", e); } return Collections.unmodifiableList(paths); } @Override @SuppressWarnings("unchecked") List<String> getPaths(String kind, String type, String specification, Optional<byte[]> exemplar); @Override boolean supports(String kind, String type, String specification, Optional<byte[]> optional); }### Answer: @Test public void shouldCollectPathsFromJsonObject() { final List<String> paths = inspector.getPaths(JSON_INSTANCE_KIND, "", getJsonInstance(), Optional.empty()); assertProperties(paths); assertThat(paths).doesNotContainAnyElementsOf(JsonInstanceInspector.COLLECTION_PATHS); } @Test public void shouldCollectPathsFromEmptyJsonObject() { final List<String> paths = inspector.getPaths(JSON_INSTANCE_KIND, "", "{}", Optional.empty()); assertThat(paths).isEmpty(); } @Test public void shouldCollectPathsFromJsonArray() { final List<String> paths = inspector.getPaths(JSON_INSTANCE_KIND, "", getJsonArrayInstance(), Optional.empty()); assertArrayProperties(paths); assertThat(paths).containsAll(JsonInstanceInspector.COLLECTION_PATHS); } @Test public void shouldCollectPathsFromEmptyJsonArray() { final List<String> paths = inspector.getPaths(JSON_INSTANCE_KIND, "", "[]", Optional.empty()); assertThat(paths).isEqualTo(JsonInstanceInspector.COLLECTION_PATHS); }
### 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: ConnectionUpdateHandler extends AbstractResourceUpdateHandler<ConnectionBulletinBoard> { ConnectionBulletinBoard computeBoard(Connection connection, Connector oldConnector, Connector newConnector) { final DataManager dataManager = getDataManager(); final String id = connection.getId().get(); final ConnectionBulletinBoard board = dataManager.fetchByPropertyValue(ConnectionBulletinBoard.class, "targetResourceId", id).orElse(null); final ConnectionBulletinBoard.Builder builder; if (board != null) { builder = new ConnectionBulletinBoard.Builder() .createFrom(board); } else { builder = new ConnectionBulletinBoard.Builder() .id(KeyGenerator.createKey()) .targetResourceId(id) .createdAt(System.currentTimeMillis()); } List<LeveledMessage> messages = new ArrayList<>(); messages.addAll(computeValidatorMessages(LeveledMessage.Builder::new, connection)); messages.addAll(computePropertiesDiffMessages(LeveledMessage.Builder::new, oldConnector.getProperties(), newConnector.getProperties())); if (!connection.isDerived()) { messages.addAll(computeMissingMandatoryPropertiesMessages( LeveledMessage.Builder::new, newConnector.getProperties(), merge(newConnector.getConfiguredProperties(), connection.getConfiguredProperties())) ); } messages.addAll(computeSecretsUpdateMessages(LeveledMessage.Builder::new, newConnector.getProperties(), connection.getConfiguredProperties())); builder.errors(countMessagesWithLevel(LeveledMessage.Level.ERROR, messages)); builder.warnings(countMessagesWithLevel(LeveledMessage.Level.WARN, messages)); builder.notices(countMessagesWithLevel(LeveledMessage.Level.INFO, messages)); builder.putMetadata("connector-id", newConnector.getId().get()); builder.putMetadata("connector-version-latest", Integer.toString(newConnector.getVersion())); builder.putMetadata("connector-version-connection", Integer.toString(oldConnector.getVersion())); builder.messages(messages); ConnectionBulletinBoard updated = builder.build(); if (!updated.equals(board)) { return builder.updatedAt(System.currentTimeMillis()).build(); } return null; } ConnectionUpdateHandler(DataManager dataManager, EncryptionComponent encryptionComponent, Validator validator); @Override boolean canHandle(ChangeEvent event); }### Answer: @Test public void shouldNotComputeConnectorConfiguredPropertiesAsMissing() { final ConnectionUpdateHandler updateHandler = new ConnectionUpdateHandler(dataManager, null, validator); final Connection connection = new Connection.Builder() .id("connection") .putConfiguredProperty("req2", "value2") .build(); final ConfigurationProperty required = new ConfigurationProperty.Builder().required(true).build(); final Connector sameConnector = new Connector.Builder() .id("new-connector") .putProperty("req1", required) .putProperty("req2", required) .putConfiguredProperty("req1", "value1") .build(); when(dataManager.fetchByPropertyValue(ConnectionBulletinBoard.class, "targetResourceId", "connection")) .thenReturn(Optional.empty()); final ConnectionBulletinBoard board = updateHandler.computeBoard(connection, sameConnector, sameConnector); assertThat(board.getMessages()).isEmpty(); }
### 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: RandomValueGenerator { public static String generate(final String generator) { if (generator == null) { throw new IllegalArgumentException("Generator cannot be null"); } final int split = generator.indexOf(':'); if (split < 0) { return generate(generator, null); } return generate(generator.substring(0, split), generator.substring(split + 1)); } private RandomValueGenerator(); static String generate(final String generator); }### Answer: @Test public void testNegativeValue() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> RandomValueGenerator.generate("alphanum:-1")) .withMessage("Cannot generate a string of negative length"); } @Test public void testPatternRespectedWithDefault() { for (int i = 0; i < 20; i++) { final String value = RandomValueGenerator.generate("alphanum"); assertThat(value).matches("[A-Za-z0-9]{40}"); } } @Test public void testPatternRespectedWithLength() { for (int i = 0; i < 20; i++) { final String value = RandomValueGenerator.generate("alphanum:12"); assertThat(value).matches("[A-Za-z0-9]{12}"); } } @Test public void testTrueRandom() { final Set<String> gen = new HashSet<>(); for (int i = 0; i < 20; i++) { final String value = RandomValueGenerator.generate("alphanum:80"); assertThat(value).matches("[A-Za-z0-9]{80}"); gen.add(value); } assertThat(gen.size()).isGreaterThan(10); } @Test public void testUnknownGenerator() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> RandomValueGenerator.generate("alphanumx")) .withMessage("Unsupported generator scheme: alphanumx"); } @Test public void testWrongValueType() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> RandomValueGenerator.generate("alphanum:aa")) .withMessage("Unexpected string after the alphanum scheme: expected length"); } @Test public void testZeroValue() { final String value = RandomValueGenerator.generate("alphanum:0"); assertThat(value).isEqualTo(""); }
### Question: MustacheTemplatePreProcessor extends AbstractTemplatePreProcessor { @SuppressWarnings("PMD.PrematureDeclaration") @Override public String preProcess(String template) throws TemplateProcessingException { String newTemplate = super.preProcess(template); if (inSectionSymbol) { throw new TemplateProcessingException("The template is invalid since a section has not been closed"); } newTemplate = newTemplate.replaceAll(DOUBLE_OPEN_BRACE_PATTERN, MUSTACHE_OPEN_DELIMITER); newTemplate = newTemplate.replaceAll(DOUBLE_CLOSE_BRACE_PATTERN, MUSTACHE_CLOSE_DELIMITER); return newTemplate; } MustacheTemplatePreProcessor(); @SuppressWarnings("PMD.PrematureDeclaration") @Override String preProcess(String template); @Override boolean isMySymbol(String literal); @Override void reset(); @Override Map<String, Object> getUriParams(); }### Answer: @Test public void testBasicTemplate() throws Exception { String template = "{{text}}"; String newTemplate = processor.preProcess(template); assertNotEquals(template, newTemplate); assertEquals("[[body.text]]", newTemplate); } @Test public void testTemplate() throws Exception { String template = EMPTY_STRING + "At {{time}}, {{name}}" + NEW_LINE + "submitted the following message:" + NEW_LINE + "{{text}}"; String expected = EMPTY_STRING + "At [[body.time]], [[body.name]]" + NEW_LINE + "submitted the following message:" + NEW_LINE + "[[body.text]]"; String newTemplate = processor.preProcess(template); assertNotEquals(template, newTemplate); assertEquals(expected, newTemplate); } @Test public void test2SymbolsTogether() throws Exception { String template = "{{name}}{{description}}"; String newTemplate = processor.preProcess(template); assertNotEquals(template, newTemplate); assertEquals("[[body.name]][[body.description]]", newTemplate); } @Test public void testSectionTemplate() throws Exception { String template = EMPTY_STRING + "{{name}} passed the following courses:" + NEW_LINE + "{{#course}}" + NEW_LINE + "\t* {{name}}" + NEW_LINE + "{{/course}}" + NEW_LINE + "{{text}}"; String expected = EMPTY_STRING + "[[body.name]] passed the following courses:" + NEW_LINE + "[[#body.course]]" + NEW_LINE + "\t* [[name]]" + NEW_LINE + "[[/body.course]]" + NEW_LINE + "[[body.text]]"; String newTemplate = processor.preProcess(template); assertNotEquals(template, newTemplate); assertEquals(expected, newTemplate); } @Test public void testDanglingSectionTemplate() { String template = EMPTY_STRING + "{{name}} passed the following courses:" + NEW_LINE + "{{#course}}" + NEW_LINE + "\t* {{name}}" + NEW_LINE + "{{text}}"; assertThatThrownBy(() -> processor.preProcess(template)) .isInstanceOf(TemplateProcessingException.class) .hasMessageContaining("section has not been closed"); } @Test public void testTemplateSymbolsWithSpaces() throws Exception { String template = EMPTY_STRING + "At {{the time}}, {{the name}}" + NEW_LINE + "submitted the following message:" + NEW_LINE + "{{the text}}"; String expected = EMPTY_STRING + "At [[body.the time]], [[body.the name]]" + NEW_LINE + "submitted the following message:" + NEW_LINE + "[[body.the text]]"; String newTemplate = processor.preProcess(template); assertNotEquals(template, newTemplate); assertEquals(expected, newTemplate); } @Test public void testInvalidTemplateWrongSyntax() { String template = EMPTY_STRING + "At ${time}, ${name}" + NEW_LINE + "submitted the following message:" + NEW_LINE + "${text}"; assertThatThrownBy(() -> processor.preProcess(template)) .isInstanceOf(TemplateProcessingException.class) .hasMessageContaining("wrong language"); } @Test public void testInvalidTemplateNoEndTag() { String template = EMPTY_STRING + "At {{time}"; assertThatThrownBy(() -> processor.preProcess(template)) .isInstanceOf(TemplateProcessingException.class) .hasMessageContaining("incomplete symbol"); }
### Question: SlackMetaDataExtension extends AbstractMetaDataExtension { @SuppressWarnings("unchecked") @Override public Optional<MetaData> meta(Map<String, Object> parameters) { final String token = ConnectorOptions.extractOption(parameters, "token"); if (token != null) { LOG.debug("Retrieving channels for connection to slack with token {}", token); HttpClient client = HttpClientBuilder.create().useSystemProperties().build(); HttpPost httpPost = new HttpPost("https: List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add(new BasicNameValuePair("token", token)); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response = client.execute(httpPost); String jsonString = readResponse(response); JSONParser parser = new JSONParser(); JSONObject c = (JSONObject) parser.parse(jsonString); List<Object> list = (List<Object>) c.get("channels"); Set<String> setChannels = new HashSet<String>(); Iterator<Object> it = list.iterator(); while (it.hasNext()) { Object object = it.next(); JSONObject singleChannel = (JSONObject) object; if (singleChannel.get("name") != null) { setChannels.add((String) singleChannel.get("name")); } } return Optional .of(MetaDataBuilder.on(getCamelContext()).withAttribute(MetaData.CONTENT_TYPE, "text/plain") .withAttribute(MetaData.JAVA_TYPE, String.class).withPayload(setChannels).build()); } catch (Exception e) { throw new IllegalStateException( "Get information about channels failed with token has failed.", e); } } else { return Optional.empty(); } } SlackMetaDataExtension(CamelContext context); @SuppressWarnings("unchecked") @Override Optional<MetaData> meta(Map<String, Object> parameters); }### Answer: @Test public void retrieveChannelListTest() { CamelContext context = new DefaultCamelContext(); SlackMetaDataExtension extension = new SlackMetaDataExtension(context); Map<String, Object> properties = new HashMap<>(); properties.put("token", "token"); Optional<MetaDataExtension.MetaData> meta = extension.meta(properties); assertThat(meta).isPresent(); assertThat(meta.get().getPayload()).isInstanceOf(Set.class); assertThat(meta.get().getAttributes()).hasEntrySatisfying(MetaDataExtension.MetaData.JAVA_TYPE, new Condition<Object>() { @Override public boolean matches(Object val) { return Objects.equals(String.class, val); } }); assertThat(meta.get().getAttributes()).hasEntrySatisfying(MetaDataExtension.MetaData.CONTENT_TYPE, new Condition<Object>() { @Override public boolean matches(Object val) { return Objects.equals("text/plain", val); } }); } @Test public void noChannelTest() { CamelContext context = new DefaultCamelContext(); SlackMetaDataExtension extension = new SlackMetaDataExtension(context); Map<String, Object> properties = new HashMap<>(); properties.put("webhookurl", "token"); Optional<MetaDataExtension.MetaData> meta = extension.meta(properties); assertThat(meta).isEmpty(); }
### 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: HttpConnectorFactories { public static String computeHttpUri(String scheme, Map<String, Object> options) { String baseUrl = (String)options.remove("baseUrl"); if (ObjectHelper.isEmpty(baseUrl)) { throw new IllegalArgumentException("baseUrl si mandatory"); } String uriScheme = StringHelper.before(baseUrl, ": if (ObjectHelper.isNotEmpty(uriScheme) && !ObjectHelper.equal(scheme, uriScheme)) { throw new IllegalArgumentException("Unsupported scheme: " + uriScheme); } if (ObjectHelper.isNotEmpty(uriScheme)) { baseUrl = StringHelper.after(baseUrl, ": } String path = (String)options.remove("path"); if (StringUtils.isNotEmpty(path)) { return StringUtils.removeEnd(baseUrl, "/") + "/" + StringUtils.removeStart(path, "/"); } else { return baseUrl; } } private HttpConnectorFactories(); static String computeHttpUri(String scheme, Map<String, Object> options); }### Answer: @Test public void testComputeHttpUri() { assertThat( computeHttpUri("http", mapOf( "baseUrl", "www.google.com" )) ).isEqualTo("www.google.com"); assertThat( computeHttpUri("http", mapOf( "baseUrl", "www.google.com", "path", "/test" )) ).isEqualTo("www.google.com/test"); assertThat( computeHttpUri("http", mapOf( "baseUrl", "www.google.com/", "path", "/test" )) ).isEqualTo("www.google.com/test"); assertThat( computeHttpUri("http", mapOf( "baseUrl", "www.google.com", "path", "/test" )) ).isEqualTo("www.google.com/test"); assertThat( computeHttpUri("http", mapOf( "baseUrl", "www.google.com", "path", "test" )) ).isEqualTo("www.google.com/test"); assertThat( computeHttpUri("http", mapOf( "baseUrl", "http: "path", "/test" )) ).isEqualTo("www.google.com/test"); assertThat( computeHttpUri("http", mapOf( "baseUrl", "http: "path", "/test" )) ).isEqualTo("www.google.com/test"); assertThat( computeHttpUri("http", mapOf( "baseUrl", "http: )) ).isEqualTo("www.google.com"); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy( () -> computeHttpUri( "http", mapOf( "baseUrl", "https: )) ); }
### Question: ODataMetadata implements ODataConstants { public Set<String> getEntityNames() { return entityNames; } boolean hasEntityProperties(); Set<PropertyMetadata> getEntityProperties(); void addEntityProperty(PropertyMetadata property); void setEntityProperties(Set<PropertyMetadata> properties); boolean hasEntityNames(); Set<String> getEntityNames(); void setEntityNames(Set<String> names); }### Answer: @Test public void testMetaDataExtensionRetrieval() throws Exception { ODataMetaDataExtension extension = new ODataMetaDataExtension(context); Map<String, Object> parameters = new HashMap<>(); parameters.put(SERVICE_URI, odataTestServer.getServiceUri()); Optional<MetaDataExtension.MetaData> meta = extension.meta(parameters); assertThat(meta).isPresent(); Object payload = meta.get().getPayload(); assertThat(payload).isInstanceOf(ODataMetadata.class); ODataMetadata odataMetadata = (ODataMetadata) payload; assertThat(odataMetadata.getEntityNames().size()).isEqualTo(3); assertThat(odataMetadata.getEntityNames()).contains(MANUFACTURERS, CARS, DRIVERS); } @Test public void testMetaDataExtensionRetrievalSSL() throws Exception { ODataMetaDataExtension extension = new ODataMetaDataExtension(context); Map<String, Object> parameters = new HashMap<>(); parameters.put(SERVICE_URI, sslTestServer.getSecuredServiceUri()); parameters.put(SERVER_CERTIFICATE, Certificates.TEST_SERVICE.get()); Optional<MetaDataExtension.MetaData> meta = extension.meta(parameters); assertThat(meta).isPresent(); Object payload = meta.get().getPayload(); assertThat(payload).isInstanceOf(ODataMetadata.class); ODataMetadata odataMetadata = (ODataMetadata) payload; assertThat(odataMetadata.getEntityNames().size()).isEqualTo(3); assertThat(odataMetadata.getEntityNames()).contains(MANUFACTURERS, CARS, DRIVERS); } @Test public void testMetaDataExtensionRetrieval() throws Exception { ODataMetaDataExtension extension = new ODataMetaDataExtension(context); Map<String, Object> parameters = new HashMap<>(); parameters.put(SERVICE_URI, defaultTestServer.servicePlainUri()); Optional<MetaDataExtension.MetaData> meta = extension.meta(parameters); assertThat(meta).isPresent(); Object payload = meta.get().getPayload(); assertThat(payload).isInstanceOf(ODataMetadata.class); ODataMetadata odataMetadata = (ODataMetadata) payload; assertThat(odataMetadata.getEntityNames().size()).isEqualTo(1); assertThat(odataMetadata.getEntityNames().iterator().next()).isEqualTo(defaultTestServer.resourcePath()); } @Test public void testMetaDataExtensionRetrievalSSL() throws Exception { ODataMetaDataExtension extension = new ODataMetaDataExtension(context); Map<String, Object> parameters = new HashMap<>(); parameters.put(SERVICE_URI, sslTestServer.serviceSSLUri()); parameters.put(SERVER_CERTIFICATE, ODataTestServer.serverCertificate()); Optional<MetaDataExtension.MetaData> meta = extension.meta(parameters); assertThat(meta).isPresent(); Object payload = meta.get().getPayload(); assertThat(payload).isInstanceOf(ODataMetadata.class); ODataMetadata odataMetadata = (ODataMetadata) payload; assertThat(odataMetadata.getEntityNames().size()).isEqualTo(1); assertThat(odataMetadata.getEntityNames().iterator().next()).isEqualTo(sslTestServer.resourcePath()); } @Test public void testMetaDataExtensionRetrievalOnceResourcePathSet() throws Exception { ODataMetaDataExtension extension = new ODataMetaDataExtension(context); Map<String, Object> parameters = new HashMap<>(); parameters.put(SERVICE_URI, defaultTestServer.servicePlainUri()); parameters.put(RESOURCE_PATH, "Products"); Optional<MetaDataExtension.MetaData> meta = extension.meta(parameters); assertThat(meta).isPresent(); Object payload = meta.get().getPayload(); assertThat(payload).isInstanceOf(ODataMetadata.class); ODataMetadata odataMetadata = (ODataMetadata) payload; assertThat(odataMetadata.getEntityNames().size()).isEqualTo(1); assertThat(odataMetadata.getEntityNames().iterator().next()).isEqualTo(defaultTestServer.resourcePath()); }
### 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: DebeziumMySQLDatashapeStrategy implements DebeziumDatashapeStrategy { static String convertDDLtoJsonSchema(final String ddl, final String tableName) { int firstParentheses = ddl.indexOf('('); final Matcher matcher = PATTERN.matcher(ddl.substring(firstParentheses)); final List<String> properties = new ArrayList<>(); while (matcher.find()) { final String field = matcher.group(1); final String type = getType(matcher.group(2)); properties.add("\"" + field + "\":{\"type\":\"" + type + "\"}"); } return buildJsonSchema(tableName, properties); } @Override DataShape getDatashape(Map<String, Object> params); }### Answer: @Test public void shouldConvertDDLtoJsonSchema() { final String ddl = "CREATE TABLE `roles` (\n" + "`id` varchar(32) NOT NULL,\n" + "`name` varchar(100) NOT NULL,\n" + "`context` varchar(20) NOT NULL,\n" + "`organization_id` int(11) DEFAULT NULL,\n" + "`client_id` varchar(32) NOT NULL,\n" + "`scope_action_ids` text NOT NULL,\n" + "PRIMARY KEY (`id`),\n" + "FULLTEXT KEY `scope_action_ids_idx` (`scope_action_ids`)\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8;"; final String generated = DebeziumMySQLDatashapeStrategy.convertDDLtoJsonSchema(ddl, "roles"); final String expected = "{\n" + " \"$schema\":\"http: " \"title\":\"roles\",\n" + " \"type\":\"object\",\n" + " \"properties\":{\n" + " \"id\":{\n" + " \"type\":\"string\"\n" + " },\n" + " \"name\":{\n" + " \"type\":\"string\"\n" + " },\n" + " \"context\":{\n" + " \"type\":\"string\"\n" + " },\n" + " \"organization_id\":{\n" + " \"type\":\"integer\"\n" + " },\n" + " \"client_id\":{\n" + " \"type\":\"string\"\n" + " },\n" + " \"scope_action_ids\":{\n" + " \"type\":\"string\"\n" + " }\n" + " }\n" + "}"; assertThatJson(generated).isEqualTo(expected); }
### Question: KafkaConnectionCustomizer implements ComponentProxyCustomizer, CamelContextAware { @Override public void customize(ComponentProxyComponent component, Map<String, Object> options) { KafkaConfiguration configuration = new KafkaConfiguration(); if (ConnectorOptions.extractOption(options, CERTIFICATE_OPTION) != null) { LOG.info("Setting SSLContextParameters configuration as a self-signed certificate was provided"); SSLContextParameters sslContextParameters = createSSLContextParameters( ConnectorOptions.extractOption(options, CERTIFICATE_OPTION)); configuration.setSslContextParameters(sslContextParameters); configuration.setSecurityProtocol("SSL"); configuration.setSslEndpointAlgorithm(""); } String extraOptions = options.getOrDefault("extraOptions", "[]").toString(); try { @SuppressWarnings("unchecked") List<Map<String, String>> attributes = MAPPER.readValue(extraOptions, List.class); for (Map<String, String> attribute : attributes) { final String key = attribute.get("key").trim(); if (!key.isEmpty()) { final String value = attribute.get("value"); final String property = getCanonicalPropertyName(key); options.put(property, value); configuration.getAdditionalProperties().put("additionalProperties." + property, value); } } PropertyBindingSupport.bindProperties(this.getCamelContext(), configuration, options); } catch (JsonProcessingException e) { LOG.error(e.getMessage(), e); } options.put("configuration", configuration); } KafkaConnectionCustomizer(CamelContext context); @Override CamelContext getCamelContext(); @Override final void setCamelContext(CamelContext camelContext); @Override void customize(ComponentProxyComponent component, Map<String, Object> options); static final ObjectMapper MAPPER; }### Answer: @Test public void shouldAssertIfSelfSignedCertificate() { KafkaConnectionCustomizer kafkaConnectionCustomizer = new KafkaConnectionCustomizer(new DefaultCamelContext()); Map<String, Object> options = new HashMap<>(); options.put("brokers", "test:9092"); options.put("brokerCertificate", TEST_CERT); kafkaConnectionCustomizer.customize(null, options); assertThat(options).containsKey("configuration"); KafkaConfiguration kafkaConfiguration = (KafkaConfiguration) options.get("configuration"); assertThat(kafkaConfiguration.getSslContextParameters()).isNotNull(); assertThat(kafkaConfiguration.getSecurityProtocol()).isEqualTo("SSL"); assertThat(kafkaConfiguration.getSslEndpointAlgorithm()).isEqualTo(""); } @Test public void testExtraOptions() { KafkaConnectionCustomizer kafkaConnectionCustomizer = new KafkaConnectionCustomizer(new DefaultCamelContext()); Map<String, Object> options = new HashMap<>(); options.put("brokers", "test:9092"); options.put("extraOptions", "[{\"key\":\"AAA\",\"value\":\"BBB\"}," + " {\"key\":\"autoOffsetReset\"," + "\"value\":\"earliest\"}," + "{\"key\":\"checkCrcs\",\"value\":\"false\"}, " + "{\"key\":\"auto.commit.interval.ms\",\"value\":\"5\"}]"); kafkaConnectionCustomizer.customize(null, options); assertThat(options).containsKey("configuration"); KafkaConfiguration kafkaConfiguration = (KafkaConfiguration) options.get("configuration"); assertThat(kafkaConfiguration.getAdditionalProperties()).containsEntry("additionalProperties.AAA", "BBB"); assertThat(kafkaConfiguration.getAutoOffsetReset()).isEqualTo("earliest"); assertThat(kafkaConfiguration.getCheckCrcs()).isEqualTo(false); assertThat(kafkaConfiguration.getAutoCommitIntervalMs()).isEqualTo(5); } @Test public void testExtraOptionsEmpty() { KafkaConnectionCustomizer kafkaConnectionCustomizer = new KafkaConnectionCustomizer(new DefaultCamelContext()); Map<String, Object> options = new HashMap<>(); options.put("brokers", "test:9092"); options.put("extraOptions", "[]"); kafkaConnectionCustomizer.customize(null, options); assertThat(options).containsKey("configuration"); KafkaConfiguration kafkaConfiguration = (KafkaConfiguration) options.get("configuration"); assertThat(kafkaConfiguration.getAdditionalProperties()).isEmpty(); }
### 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: KafkaMetaDataRetrieval extends ComponentMetadataRetrieval { @Override public SyndesisMetadataProperties fetchProperties(CamelContext context, String componentId, Map<String, Object> properties) { List<PropertyPair> brokers = new ArrayList<>(); try (KubernetesClient client = createKubernetesClient()) { KafkaResourceList kafkaList = client.customResources(KAFKA_CRD, Kafka.class, KafkaResourceList.class, KafkaResourceDoneable.class).inAnyNamespace().list(); kafkaList.getItems().forEach(kafka -> processKafkaResource(brokers, kafka)); } catch (Exception t) { LOG.warn("Couldn't auto discover any kafka broker.", t); } Map<String, List<PropertyPair>> dynamicProperties = new HashMap<>(); dynamicProperties.put("brokers", brokers); return new SyndesisMetadataProperties(dynamicProperties); } @Override SyndesisMetadataProperties fetchProperties(CamelContext context, String componentId, Map<String, Object> properties); }### Answer: @Test public void shouldFetchPropertiesFromKafkaCustomResources() { final KubernetesClient client = mock(KubernetesClient.class); final KafkaMetaDataRetrieval metaDataRetrieval = new KafkaMetaDataRetrieval() { @Override KubernetesClient createKubernetesClient() { return client; } }; @SuppressWarnings("unchecked") final MixedOperation<Kafka, KafkaResourceList, KafkaResourceDoneable, Resource<Kafka, KafkaResourceDoneable>> operation = mock( MixedOperation.class); when(client.customResources(KAFKA_CRD, Kafka.class, KafkaResourceList.class, KafkaResourceDoneable.class)).thenReturn(operation); when(operation.inAnyNamespace()).thenReturn(operation); when(operation.list()).thenReturn(KAFKAS); final SyndesisMetadataProperties properties = metaDataRetrieval.fetchProperties(null, null, null); final Map<String, List<PropertyPair>> expected = new HashMap<>(); expected.put("brokers", Arrays.asList( new PropertyPair("my-cluster-kafka-bootstrap.zregvart.svc:9092", "zregvart::my-cluster (plain)"), new PropertyPair("my-cluster-kafka-bootstrap.zregvart.svc:9093", "zregvart::my-cluster (tls)"), new PropertyPair("zorans-cluster-kafka-bootstrap.zregvart.svc:9092", "zregvart::zorans-cluster (plain)"), new PropertyPair("zorans-cluster-kafka-bootstrap.zregvart.svc:9093", "zregvart::zorans-cluster (tls)") )); assertThat(properties.getProperties()).containsExactlyEntriesOf(expected); }
### 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: AWSSQSMetaDataExtension extends AbstractMetaDataExtension { @Override public Optional<MetaData> meta(Map<String, Object> parameters) { final String accessKey = ConnectorOptions.extractOption(parameters, "accessKey"); final String secretKey = ConnectorOptions.extractOption(parameters, "secretKey"); final String region = ConnectorOptions.extractOption(parameters, "region"); AmazonSQSClientBuilder clientBuilder; AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials); clientBuilder = AmazonSQSClientBuilder.standard().withCredentials(credentialsProvider); clientBuilder = clientBuilder.withRegion(Regions.valueOf(region)); AmazonSQS sqsClient = clientBuilder.build(); List<String> attributeNames = new ArrayList<String>(); attributeNames.add("All"); try { ListQueuesResult result = sqsClient.listQueues(); Set<String> setQueue = new HashSet<String>(); if (result.getQueueUrls() != null) { for (String entry : result.getQueueUrls()) { GetQueueAttributesRequest req = new GetQueueAttributesRequest(); req.setQueueUrl(entry); req.setAttributeNames(attributeNames); GetQueueAttributesResult c = sqsClient.getQueueAttributes(req); setQueue.add(c.getAttributes().get(QueueAttributeName.QueueArn.name())); } } return Optional.of(MetaDataBuilder.on(getCamelContext()).withAttribute(MetaData.CONTENT_TYPE, "text/plain").withAttribute(MetaData.JAVA_TYPE, String.class) .withPayload(setQueue).build()); } catch (Exception e) { throw new IllegalStateException("Get information about existing queues with has failed.", e); } } AWSSQSMetaDataExtension(CamelContext context); @Override Optional<MetaData> meta(Map<String, Object> parameters); }### Answer: @Test public void retrieveQueuesListTest() { CamelContext context = new DefaultCamelContext(); AWSSQSMetaDataExtension extension = new AWSSQSMetaDataExtension(context); Map<String, Object> properties = new HashMap<>(); properties.put("accessKey", "accessKey"); properties.put("secretKey", "secretKey"); properties.put("region", "region"); Optional<MetaDataExtension.MetaData> meta = extension.meta(properties); assertThat(meta).isPresent(); assertThat(meta.get().getPayload()).isInstanceOf(HashSet.class); assertThat(meta.get().getAttributes()).hasEntrySatisfying(MetaDataExtension.MetaData.JAVA_TYPE, new Condition<Object>() { @Override public boolean matches(Object val) { return Objects.equals(String.class, val); } }); assertThat(meta.get().getAttributes()).hasEntrySatisfying(MetaDataExtension.MetaData.CONTENT_TYPE, new Condition<Object>() { @Override public boolean matches(Object val) { return Objects.equals("text/plain", val); } }); } @Test public void noChannelTest() { CamelContext context = new DefaultCamelContext(); AWSSQSMetaDataExtension extension = new AWSSQSMetaDataExtension(context); Map<String, Object> properties = new HashMap<>(); properties.put("webhookurl", "token"); Optional<MetaDataExtension.MetaData> meta = extension.meta(properties); assertThat(meta).isEmpty(); }