Search in sources :

Example 1 with DynamicProperty

use of io.gravitee.rest.api.services.dynamicproperties.model.DynamicProperty in project gravitee-management-rest-api by gravitee-io.

the class DynamicPropertyUpdater method update.

private void update(Collection<DynamicProperty> dynamicProperties) {
    // Get latest changes
    ApiEntity latestApi = apiService.findById(api.getId());
    List<Property> properties = (latestApi.getProperties() != null) ? latestApi.getProperties().getProperties() : Collections.emptyList();
    List<Property> userDefinedProperties = properties.stream().filter(property -> !property.isDynamic()).collect(Collectors.toList());
    Map<String, Property> propertyMap = properties.stream().collect(Collectors.toMap(Property::getKey, property -> property));
    List<Property> updatedProperties = new ArrayList<>();
    boolean needToBeSaved = false;
    for (DynamicProperty dynamicProperty : dynamicProperties) {
        Property property = propertyMap.get(dynamicProperty.getKey());
        if (property == null || property.isDynamic()) {
            updatedProperties.add(dynamicProperty);
        }
        // save properties only if there's something new
        if (property == null || (property.isDynamic() && !property.getValue().equals(dynamicProperty.getValue()))) {
            needToBeSaved = true;
        }
    }
    if (needToBeSaved) {
        // Add previous user-defined properties
        updatedProperties.addAll(userDefinedProperties);
        // Sort properties alphabetically to avoid redeploy if just the order has changed.
        List<Property> sortedUpdatedProperties = updatedProperties.stream().sorted(Comparator.comparing(Property::getKey)).collect(Collectors.toList());
        // Create properties container
        Properties apiProperties = new Properties();
        try {
            apiProperties.setProperties(sortedUpdatedProperties);
        } catch (RuntimeException e) {
            logger.error(e.getMessage(), e);
        }
        latestApi.setProperties(apiProperties);
        boolean isSync = apiService.isSynchronized(api.getId());
        // Update API
        apiService.update(latestApi.getId(), ApiService.convert(latestApi));
        // Do not deploy if there are manual changes to push
        if (isSync) {
            // Publish API only in case of changes
            if (!updatedProperties.containsAll(properties) || !properties.containsAll(updatedProperties)) {
                ApiDeploymentEntity deployEntity = new ApiDeploymentEntity();
                deployEntity.setDeploymentLabel("Dynamic properties sync");
                apiService.deploy(latestApi.getId(), "dynamic-property-updater", EventType.PUBLISH_API, deployEntity);
            }
        }
    }
}
Also used : ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) java.util(java.util) Logger(org.slf4j.Logger) Properties(io.gravitee.definition.model.Properties) Property(io.gravitee.definition.model.Property) Provider(io.gravitee.rest.api.services.dynamicproperties.provider.Provider) LoggerFactory(org.slf4j.LoggerFactory) DynamicProperty(io.gravitee.rest.api.services.dynamicproperties.model.DynamicProperty) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Collectors(java.util.stream.Collectors) ApiService(io.gravitee.rest.api.service.ApiService) GrantedAuthority(org.springframework.security.core.GrantedAuthority) EventType(io.gravitee.rest.api.model.EventType) SecurityContext(org.springframework.security.core.context.SecurityContext) Handler(io.vertx.core.Handler) Authentication(org.springframework.security.core.Authentication) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) ApiDeploymentEntity(io.gravitee.rest.api.model.api.ApiDeploymentEntity) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) SystemRole(io.gravitee.rest.api.model.permissions.SystemRole) DynamicProperty(io.gravitee.rest.api.services.dynamicproperties.model.DynamicProperty) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) ApiDeploymentEntity(io.gravitee.rest.api.model.api.ApiDeploymentEntity) Properties(io.gravitee.definition.model.Properties) Property(io.gravitee.definition.model.Property) DynamicProperty(io.gravitee.rest.api.services.dynamicproperties.model.DynamicProperty)

Example 2 with DynamicProperty

use of io.gravitee.rest.api.services.dynamicproperties.model.DynamicProperty in project gravitee-management-rest-api by gravitee-io.

the class DynamicPropertyUpdaterTest method shouldUpdateProperties.

@Test
public void shouldUpdateProperties() {
    Mockito.when(provider.get()).thenReturn(CompletableFuture.supplyAsync(() -> {
        DynamicProperty property = new DynamicProperty("my-key", "my-value");
        return Collections.singletonList(property);
    }));
    poller.handle(1L);
}
Also used : DynamicProperty(io.gravitee.rest.api.services.dynamicproperties.model.DynamicProperty) Test(org.junit.Test)

Example 3 with DynamicProperty

use of io.gravitee.rest.api.services.dynamicproperties.model.DynamicProperty in project gravitee-management-rest-api by gravitee-io.

the class JoltMapper method map.

public Collection<DynamicProperty> map(String source) {
    // Default value is equal to the input json value (in case empty jolt specs)
    String jsonProperties = source;
    ArrayList transformed;
    if (jsonProperties != null && jsonProperties.charAt(0) == '[') {
        transformed = (ArrayList) chainr.transform(JsonUtils.jsonToList(source));
    } else {
        transformed = (ArrayList) chainr.transform(JsonUtils.jsonToMap(source));
    }
    jsonProperties = JsonUtils.toJsonString(transformed);
    List<Object> items = JsonUtils.jsonToList(jsonProperties);
    Object collect = items.stream().map(item -> {
        Map<String, String> mapItem = (Map<String, String>) item;
        Object key = mapItem.get("key");
        if (key instanceof Number) {
            return new DynamicProperty(key.toString(), mapItem.get("value"));
        } else {
            return new DynamicProperty((String) key, mapItem.get("value"));
        }
    }).collect(Collectors.toList());
    return (Collection<DynamicProperty>) collect;
}
Also used : java.util(java.util) Logger(org.slf4j.Logger) JsonUtils(com.bazaarvoice.jolt.JsonUtils) ProcessingException(com.github.fge.jsonschema.core.exceptions.ProcessingException) LoggerFactory(org.slf4j.LoggerFactory) DynamicProperty(io.gravitee.rest.api.services.dynamicproperties.model.DynamicProperty) IOException(java.io.IOException) ProcessingReport(com.github.fge.jsonschema.core.report.ProcessingReport) Collectors(java.util.stream.Collectors) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) IOUtils(org.apache.commons.io.IOUtils) Chainr(com.bazaarvoice.jolt.Chainr) JsonLoader(com.github.fge.jackson.JsonLoader) JsonNode(com.fasterxml.jackson.databind.JsonNode) JsonSchemaFactory(com.github.fge.jsonschema.main.JsonSchemaFactory) JsonSchema(com.github.fge.jsonschema.main.JsonSchema) ChainrBuilder(com.bazaarvoice.jolt.chainr.ChainrBuilder) InputStream(java.io.InputStream) DynamicProperty(io.gravitee.rest.api.services.dynamicproperties.model.DynamicProperty)

Example 4 with DynamicProperty

use of io.gravitee.rest.api.services.dynamicproperties.model.DynamicProperty in project gravitee-management-rest-api by gravitee-io.

the class JoltMapperTest method test.

@Test
public void test() throws IOException {
    mapper = new JoltMapper(read("/jolt/specification.json"));
    String input = IOUtils.toString(read("/jolt/custom-response.json"), Charset.defaultCharset());
    Collection<DynamicProperty> properties = mapper.map(input);
    assertFalse(properties.isEmpty());
}
Also used : DynamicProperty(io.gravitee.rest.api.services.dynamicproperties.model.DynamicProperty) JoltMapper(io.gravitee.rest.api.services.dynamicproperties.provider.http.mapper.JoltMapper) Test(org.junit.Test)

Example 5 with DynamicProperty

use of io.gravitee.rest.api.services.dynamicproperties.model.DynamicProperty in project gravitee-management-rest-api by gravitee-io.

the class HttpProvider method get.

@Override
public CompletableFuture<Collection<DynamicProperty>> get() {
    Promise<Buffer> promise = Promise.promise();
    URI requestUri = URI.create(dpConfiguration.getUrl());
    boolean ssl = HTTPS_SCHEME.equalsIgnoreCase(requestUri.getScheme());
    final HttpClientOptions clientOptions = new HttpClientOptions().setSsl(ssl).setTrustAll(true).setMaxPoolSize(1).setKeepAlive(false).setTcpKeepAlive(false).setConnectTimeout(2000);
    final HttpClient httpClient = vertx.createHttpClient(clientOptions);
    final int port = requestUri.getPort() != -1 ? requestUri.getPort() : (HTTPS_SCHEME.equals(requestUri.getScheme()) ? 443 : 80);
    String relativeUri = (requestUri.getRawQuery() == null) ? requestUri.getRawPath() : requestUri.getRawPath() + '?' + requestUri.getRawQuery();
    RequestOptions options = new RequestOptions().setMethod(HttpMethod.valueOf(dpConfiguration.getMethod().name())).setHost(requestUri.getHost()).setPort(port).setURI(relativeUri);
    // headers
    options.putHeader(HttpHeaders.USER_AGENT, NodeUtils.userAgent(node));
    options.putHeader("X-Gravitee-Request-Id", UuidString.generateRandom());
    if (dpConfiguration.getHeaders() != null) {
        dpConfiguration.getHeaders().forEach(httpHeader -> options.putHeader(httpHeader.getName(), httpHeader.getValue()));
    }
    httpClient.request(options).onFailure(new Handler<Throwable>() {

        @Override
        public void handle(Throwable event) {
            promise.fail(event);
            // Close client
            httpClient.close();
        }
    }).onSuccess(new Handler<HttpClientRequest>() {

        @Override
        public void handle(HttpClientRequest request) {
            request.response(new Handler<AsyncResult<HttpClientResponse>>() {

                @Override
                public void handle(AsyncResult<HttpClientResponse> asyncResponse) {
                    if (asyncResponse.failed()) {
                        promise.fail(asyncResponse.cause());
                        // Close client
                        httpClient.close();
                    } else {
                        final HttpClientResponse response = asyncResponse.result();
                        if (response.statusCode() == HttpStatusCode.OK_200) {
                            response.bodyHandler(buffer -> {
                                promise.complete(buffer);
                                // Close client
                                httpClient.close();
                            });
                        } else {
                            promise.complete(null);
                            // Close client
                            httpClient.close();
                        }
                    }
                }
            }).exceptionHandler(new Handler<Throwable>() {

                @Override
                public void handle(Throwable throwable) {
                    promise.fail(throwable);
                    // Close client
                    httpClient.close();
                }
            });
            if (!StringUtils.isEmpty(dpConfiguration.getBody())) {
                request.end(dpConfiguration.getBody());
            } else {
                request.end();
            }
        }
    });
    return promise.future().map(new Function<Buffer, Collection<DynamicProperty>>() {

        @Override
        public Collection<DynamicProperty> apply(Buffer buffer) {
            if (buffer == null) {
                return null;
            }
            return mapper.map(buffer.toString());
        }
    }).toCompletionStage().toCompletableFuture();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Node(io.gravitee.node.api.Node) UuidString(io.gravitee.rest.api.service.common.UuidString) HttpHeaders(io.gravitee.common.http.HttpHeaders) Promise(io.vertx.core.Promise) Collection(java.util.Collection) Provider(io.gravitee.rest.api.services.dynamicproperties.provider.Provider) Vertx(io.vertx.core.Vertx) DynamicProperty(io.gravitee.rest.api.services.dynamicproperties.model.DynamicProperty) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) DynamicPropertyService(io.gravitee.definition.model.services.dynamicproperty.DynamicPropertyService) io.vertx.core.http(io.vertx.core.http) HttpStatusCode(io.gravitee.common.http.HttpStatusCode) Objects(java.util.Objects) NodeUtils(io.gravitee.node.api.utils.NodeUtils) Buffer(io.vertx.core.buffer.Buffer) HttpDynamicPropertyProviderConfiguration(io.gravitee.definition.model.services.dynamicproperty.http.HttpDynamicPropertyProviderConfiguration) JoltMapper(io.gravitee.rest.api.services.dynamicproperties.provider.http.mapper.JoltMapper) AsyncResult(io.vertx.core.AsyncResult) URI(java.net.URI) Handler(io.vertx.core.Handler) StringUtils(org.springframework.util.StringUtils) Handler(io.vertx.core.Handler) UuidString(io.gravitee.rest.api.service.common.UuidString) URI(java.net.URI) Collection(java.util.Collection) AsyncResult(io.vertx.core.AsyncResult)

Aggregations

DynamicProperty (io.gravitee.rest.api.services.dynamicproperties.model.DynamicProperty)5 Provider (io.gravitee.rest.api.services.dynamicproperties.provider.Provider)2 JoltMapper (io.gravitee.rest.api.services.dynamicproperties.provider.http.mapper.JoltMapper)2 Handler (io.vertx.core.Handler)2 java.util (java.util)2 Collectors (java.util.stream.Collectors)2 Test (org.junit.Test)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 Chainr (com.bazaarvoice.jolt.Chainr)1 JsonUtils (com.bazaarvoice.jolt.JsonUtils)1 ChainrBuilder (com.bazaarvoice.jolt.chainr.ChainrBuilder)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 JsonLoader (com.github.fge.jackson.JsonLoader)1 ProcessingException (com.github.fge.jsonschema.core.exceptions.ProcessingException)1 ProcessingReport (com.github.fge.jsonschema.core.report.ProcessingReport)1 JsonSchema (com.github.fge.jsonschema.main.JsonSchema)1 JsonSchemaFactory (com.github.fge.jsonschema.main.JsonSchemaFactory)1 HttpHeaders (io.gravitee.common.http.HttpHeaders)1