Search in sources :

Example 56 with TechnicalException

use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-management-rest-api by gravitee-io.

the class ApiKeyServiceImpl method findBySubscription.

@Override
public Set<ApiKeyEntity> findBySubscription(String subscription) {
    try {
        LOGGER.debug("Find API Keys for subscription {}", subscription);
        SubscriptionEntity subscriptionEntity = subscriptionService.findById(subscription);
        Set<ApiKey> keys = apiKeyRepository.findBySubscription(subscriptionEntity.getId());
        return keys.stream().map(ApiKeyServiceImpl::convert).collect(Collectors.toSet());
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while finding API keys for subscription {}", subscription, ex);
        throw new TechnicalManagementException(String.format("An error occurs while finding API keys for subscription %s", subscription), ex);
    }
}
Also used : ApiKey(io.gravitee.repository.management.model.ApiKey) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 57 with TechnicalException

use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-gateway by gravitee-io.

the class CheckSubscriptionPolicy method onRequest.

@Override
protected void onRequest(Request request, Response response, PolicyChain policyChain, ExecutionContext executionContext) throws PolicyException {
    SubscriptionRepository subscriptionRepository = executionContext.getComponent(SubscriptionRepository.class);
    // Get plan and client_id from execution context
    String plan = (String) executionContext.getAttribute(ExecutionContext.ATTR_PLAN);
    String clientId = (String) executionContext.getAttribute(CONTEXT_ATTRIBUTE_CLIENT_ID);
    try {
        List<Subscription> subscriptions = subscriptionRepository.search(new SubscriptionCriteria.Builder().plans(Collections.singleton(plan)).clientId(clientId).status(Subscription.Status.ACCEPTED).build());
        if (subscriptions != null && !subscriptions.isEmpty()) {
            Subscription subscription = subscriptions.get(0);
            if (subscription.getClientId().equals(clientId) && (subscription.getEndingAt() == null || subscription.getEndingAt().after(Date.from(request.timestamp())))) {
                executionContext.setAttribute(ExecutionContext.ATTR_APPLICATION, subscription.getApplication());
                executionContext.setAttribute(ExecutionContext.ATTR_USER_ID, subscription.getId());
                policyChain.doNext(request, response);
                return;
            }
        }
        // As per https://tools.ietf.org/html/rfc6749#section-4.1.2.1
        sendUnauthorized(policyChain, OAUTH2_ERROR_ACCESS_DENIED);
    } catch (TechnicalException te) {
        // As per https://tools.ietf.org/html/rfc6749#section-4.1.2.1
        sendUnauthorized(policyChain, OAUTH2_ERROR_SERVER_ERROR);
    }
}
Also used : SubscriptionRepository(io.gravitee.repository.management.api.SubscriptionRepository) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) SubscriptionCriteria(io.gravitee.repository.management.api.search.SubscriptionCriteria) Subscription(io.gravitee.repository.management.model.Subscription)

Example 58 with TechnicalException

use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-gateway by gravitee-io.

the class CheckSubscriptionPolicy method onRequest.

@Override
protected void onRequest(Request request, Response response, PolicyChain policyChain, ExecutionContext executionContext) throws PolicyException {
    SubscriptionRepository subscriptionRepository = executionContext.getComponent(SubscriptionRepository.class);
    // Get plan and client_id from execution context
    String clientId = (String) executionContext.getAttribute(CONTEXT_ATTRIBUTE_CLIENT_ID);
    if (clientId == null || clientId.trim().isEmpty()) {
        sendError(response, policyChain, "invalid_client", "No client_id was supplied");
        return;
    }
    String plan = (String) executionContext.getAttribute(ExecutionContext.ATTR_PLAN);
    try {
        List<Subscription> subscriptions = subscriptionRepository.search(new SubscriptionCriteria.Builder().plans(Collections.singleton(plan)).clientId(clientId).status(Subscription.Status.ACCEPTED).build());
        if (subscriptions != null && !subscriptions.isEmpty()) {
            Subscription subscription = subscriptions.get(0);
            if (subscription.getClientId().equals(clientId) && (subscription.getEndingAt() == null || subscription.getEndingAt().after(Date.from(request.timestamp())))) {
                executionContext.setAttribute(ExecutionContext.ATTR_APPLICATION, subscription.getApplication());
                executionContext.setAttribute(ExecutionContext.ATTR_USER_ID, subscription.getId());
                policyChain.doNext(request, response);
                return;
            }
        }
        // As per https://tools.ietf.org/html/rfc6749#section-4.1.2.1
        sendUnauthorized(policyChain, OAUTH2_ERROR_ACCESS_DENIED);
    } catch (TechnicalException te) {
        // As per https://tools.ietf.org/html/rfc6749#section-4.1.2.1
        sendUnauthorized(policyChain, OAUTH2_ERROR_SERVER_ERROR);
    }
}
Also used : SubscriptionRepository(io.gravitee.repository.management.api.SubscriptionRepository) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) SubscriptionCriteria(io.gravitee.repository.management.api.search.SubscriptionCriteria) Subscription(io.gravitee.repository.management.model.Subscription)

Example 59 with TechnicalException

use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-gateway by gravitee-io.

the class SyncManager method refresh.

public void refresh() {
    logger.debug("Synchronization #{} started at {}", counter.incrementAndGet(), Instant.now().toString());
    logger.debug("Refreshing gateway state...");
    try {
        // Extract all registered APIs
        Map<String, io.gravitee.repository.management.model.Api> apis = apiRepository.findAll().stream().collect(Collectors.toMap(io.gravitee.repository.management.model.Api::getId, api -> api));
        long nextLastRefreshAt = System.currentTimeMillis();
        // Get last event by API
        Map<String, Event> events = new HashMap<>();
        apis.forEach((id, api) -> {
            Event event = getLastEvent(id, nextLastRefreshAt);
            if (event != null) {
                events.put(id, event);
            }
        });
        // Extract definition for each event
        Map<String, Api> definitions = new HashMap<>();
        events.values().forEach(event -> {
            try {
                // Read API definition from event
                io.gravitee.repository.management.model.Api eventPayload = objectMapper.readValue(event.getPayload(), io.gravitee.repository.management.model.Api.class);
                Api definition = objectMapper.readValue(eventPayload.getDefinition(), Api.class);
                io.gravitee.repository.management.model.Api api = apis.get(definition.getId());
                // Update definition with required information for deployment phase
                definition.setEnabled(api.getLifecycleState() == LifecycleState.STARTED);
                definition.setDeployedAt(eventPayload.getDeployedAt());
                definitions.put(definition.getId(), definition);
            } catch (IOException ioe) {
                logger.error("Error while determining deployed APIs store into events payload", ioe);
            }
        });
        // Determine APIs to undeploy because of deployment tags
        Set<String> apisToRemove = definitions.values().stream().filter(api -> !hasMatchingTags(api)).map(Api::getId).collect(Collectors.toSet());
        // Undeploy APIs not relative to this gateway instance (different deployment tags)
        apisToRemove.forEach(apiId -> {
            apiManager.undeploy(apiId);
            apis.remove(apiId);
            events.remove(apiId);
            definitions.remove(apiId);
        });
        // Determine API which must be stopped and stop them
        events.entrySet().stream().filter(apiEvent -> {
            Event event = apiEvent.getValue();
            return event.getType() == EventType.STOP_API || event.getType() == EventType.UNPUBLISH_API;
        }).forEach(apiEvent -> apiManager.undeploy(apiEvent.getKey()));
        // Determine API which must be deployed
        events.entrySet().stream().filter(apiEvent -> {
            Event event = apiEvent.getValue();
            return event.getType() == EventType.START_API || event.getType() == EventType.PUBLISH_API;
        }).forEach(apiEvent -> {
            // Read API definition from event
            Api definition = definitions.get(apiEvent.getKey());
            // API to deploy
            enhanceWithData(definition);
            if (definition != null) {
                // Get deployed API
                Api deployedApi = apiManager.get(definition.getId());
                // API is not yet deployed, so let's do it !
                if (deployedApi == null) {
                    apiManager.deploy(definition);
                } else if (deployedApi.getDeployedAt().before(definition.getDeployedAt())) {
                    apiManager.update(definition);
                }
            }
        });
        lastRefreshAt = nextLastRefreshAt;
    } catch (TechnicalException te) {
        logger.error("Unable to sync instance", te);
    }
    logger.debug("Synchronization #{} ended at {}", counter.get(), Instant.now().toString());
}
Also used : java.util(java.util) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) EventCriteria(io.gravitee.repository.management.api.search.EventCriteria) Plan(io.gravitee.gateway.handlers.api.definition.Plan) EventType(io.gravitee.repository.management.model.EventType) ApiRepository(io.gravitee.repository.management.api.ApiRepository) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Collator(java.text.Collator) EventRepository(io.gravitee.repository.management.api.EventRepository) Logger(org.slf4j.Logger) Event(io.gravitee.repository.management.model.Event) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ApiManager(io.gravitee.gateway.handlers.api.manager.ApiManager) IOException(java.io.IOException) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) PlanRepository(io.gravitee.repository.management.api.PlanRepository) LifecycleState(io.gravitee.repository.management.model.LifecycleState) AtomicLong(java.util.concurrent.atomic.AtomicLong) Api(io.gravitee.gateway.handlers.api.definition.Api) Path(io.gravitee.definition.model.Path) GatewayConfiguration(io.gravitee.gateway.env.GatewayConfiguration) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) IOException(java.io.IOException) Event(io.gravitee.repository.management.model.Event) Api(io.gravitee.gateway.handlers.api.definition.Api)

Example 60 with TechnicalException

use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-management-rest-api by gravitee-io.

the class ApiKeyServiceImpl method findByKey.

@Override
public ApiKeyEntity findByKey(String apiKey) {
    try {
        LOGGER.debug("Find an API Key by key: {}", apiKey);
        Optional<ApiKey> optApiKey = apiKeyRepository.findById(apiKey);
        if (optApiKey.isPresent()) {
            return convert(optApiKey.get());
        }
        throw new ApiKeyNotFoundException();
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to find an API Key by key {}", apiKey, ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to find an API Key by key: %s", apiKey), ex);
    }
}
Also used : ApiKey(io.gravitee.repository.management.model.ApiKey) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) ApiKeyNotFoundException(io.gravitee.management.service.exceptions.ApiKeyNotFoundException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Aggregations

TechnicalException (io.gravitee.repository.exceptions.TechnicalException)102 TechnicalManagementException (io.gravitee.management.service.exceptions.TechnicalManagementException)80 Logger (org.slf4j.Logger)22 LoggerFactory (org.slf4j.LoggerFactory)22 Autowired (org.springframework.beans.factory.annotation.Autowired)22 Component (org.springframework.stereotype.Component)20 java.util (java.util)18 Collectors (java.util.stream.Collectors)18 io.gravitee.management.model (io.gravitee.management.model)16 AuditService (io.gravitee.management.service.AuditService)12 UUID (io.gravitee.common.utils.UUID)11 Date (java.util.Date)11 IdGenerator (io.gravitee.common.utils.IdGenerator)9 IOException (java.io.IOException)9 io.gravitee.management.service (io.gravitee.management.service)8 ApiRatingUnavailableException (io.gravitee.management.service.exceptions.ApiRatingUnavailableException)8 Metadata (io.gravitee.repository.management.model.Metadata)8 Rating (io.gravitee.repository.management.model.Rating)8 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)7 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)7