Search in sources :

Example 16 with ApiVersionBean

use of io.apiman.manager.api.beans.apis.ApiVersionBean in project apiman by apiman.

the class ContractService method fireContractApprovalRequest.

private void fireContractApprovalRequest(String requesterId, ContractBean contract) {
    LOGGER.debug("Firing contract approval request from requester {0} on contract {1}", requesterId, contract);
    UserDto requester = UserMapper.INSTANCE.toDto(tryAction(() -> storage.getUser(requesterId)));
    ApimanEventHeaders headers = ApimanEventHeaders.builder().setId(UUID.randomUUID().toString()).setSource(URI.create("/apiman/events/contracts/approvals")).setSubject("request").build();
    PlanVersionBean plan = contract.getPlan();
    ClientVersionBean cvb = contract.getClient();
    ApiVersionBean avb = contract.getApi();
    OrganizationBean orgA = avb.getApi().getOrganization();
    OrganizationBean orgC = cvb.getClient().getOrganization();
    var approvalRequestEvent = ContractCreatedEvent.builder().setHeaders(headers).setUser(requester).setClientOrgId(orgC.getId()).setClientId(cvb.getClient().getId()).setClientVersion(cvb.getVersion()).setApiOrgId(orgA.getId()).setApiId(avb.getApi().getId()).setApiVersion(avb.getVersion()).setContractId(String.valueOf(contract.getId())).setPlanId(plan.getPlan().getId()).setPlanVersion(plan.getVersion()).setApprovalRequired(true).build();
    LOGGER.debug("Sending approval request event {0}", approvalRequestEvent);
    eventService.fireEvent(approvalRequestEvent);
}
Also used : ClientVersionBean(io.apiman.manager.api.beans.clients.ClientVersionBean) UserDto(io.apiman.manager.api.beans.idm.UserDto) ApimanEventHeaders(io.apiman.manager.api.beans.events.ApimanEventHeaders) OrganizationBean(io.apiman.manager.api.beans.orgs.OrganizationBean) ApiVersionBean(io.apiman.manager.api.beans.apis.ApiVersionBean) PlanVersionBean(io.apiman.manager.api.beans.plans.PlanVersionBean)

Example 17 with ApiVersionBean

use of io.apiman.manager.api.beans.apis.ApiVersionBean in project apiman by apiman.

the class ContractService method createContractInternal.

/**
 * Creates a contract.
 */
protected ContractBean createContractInternal(String clientOrgId, String clientId, String clientVersion, NewContractBean bean) throws Exception {
    ClientVersionBean cvb = clientAppService.getClientVersion(clientOrgId, clientId, clientVersion);
    if (cvb.getStatus() == ClientStatus.Retired) {
        throw ExceptionFactory.invalidClientStatusException();
    }
    ApiVersionBean avb = storage.getApiVersion(bean.getApiOrgId(), bean.getApiId(), bean.getApiVersion());
    if (avb == null) {
        throw ExceptionFactory.apiNotFoundException(bean.getApiId());
    }
    if (avb.getStatus() != ApiStatus.Published) {
        throw ExceptionFactory.invalidApiStatusException();
    }
    Set<ApiPlanBean> plans = Optional.ofNullable(avb.getPlans()).orElse(Collections.emptySet());
    ApiPlanBean apiPlanBean = plans.stream().filter(apb -> apb.getPlanId().equals(bean.getPlanId())).findFirst().orElseThrow(() -> ExceptionFactory.planNotFoundException(bean.getPlanId()));
    PlanVersionBean pvb = planService.getPlanVersion(bean.getApiOrgId(), bean.getPlanId(), apiPlanBean.getVersion());
    if (pvb.getStatus() != PlanStatus.Locked) {
        throw ExceptionFactory.invalidPlanStatusException();
    }
    ContractBean contract = new ContractBean();
    contract.setClient(cvb);
    contract.setApi(avb);
    contract.setPlan(pvb);
    contract.setCreatedBy(securityContext.getCurrentUser());
    contract.setCreatedOn(new Date());
    OrganizationBean planOrg = pvb.getPlan().getOrganization();
    if (!apiPlanBean.isRequiresApproval() || securityContext.hasPermission(planAdmin, planOrg.getId())) {
        LOGGER.debug("Contract valid immediately ✅: {0}", contract);
        contract.setStatus(Created);
    } else {
        LOGGER.debug("Contract requires approval ✋: {0}", contract);
        contract.setStatus(ContractStatus.AwaitingApproval);
    }
    try {
        storage.createContract(contract);
    } catch (IllegalStateException ise) {
        throw ExceptionFactory.contractDuplicateException();
    }
    storage.createAuditEntry(AuditUtils.contractCreatedFromClient(contract, securityContext));
    storage.createAuditEntry(AuditUtils.contractCreatedToApi(contract, securityContext));
    // Determine what status of CVB should be now
    ClientStatus oldStatus = cvb.getStatus();
    ClientStatus newStatus = clientValidator.determineStatus(cvb);
    if (oldStatus != newStatus) {
        cvb.setStatus(newStatus);
        clientAppService.fireClientStatusChangeEvent(cvb, oldStatus);
    }
    // Update the version with new meta-data (e.g. modified-by)
    cvb.setModifiedBy(securityContext.getCurrentUser());
    cvb.setModifiedOn(new Date());
    storage.updateClientVersion(cvb);
    return contract;
}
Also used : ClientVersionBean(io.apiman.manager.api.beans.clients.ClientVersionBean) ClientStatus(io.apiman.manager.api.beans.clients.ClientStatus) ApiPlanBean(io.apiman.manager.api.beans.apis.ApiPlanBean) OrganizationBean(io.apiman.manager.api.beans.orgs.OrganizationBean) ApiVersionBean(io.apiman.manager.api.beans.apis.ApiVersionBean) Date(java.util.Date) PlanVersionBean(io.apiman.manager.api.beans.plans.PlanVersionBean) NewContractBean(io.apiman.manager.api.beans.contracts.NewContractBean) ContractBean(io.apiman.manager.api.beans.contracts.ContractBean)

Example 18 with ApiVersionBean

use of io.apiman.manager.api.beans.apis.ApiVersionBean in project apiman by apiman.

the class PolicyService method createPolicy.

/**
 * Creates a policy for the given entity (supports creating policies for clients,
 * APIs, and plans).
 *
 * @param organizationId
 * @param entityId
 * @param entityVersion
 * @param bean
 * @return the stored policy bean (with updated information)
 */
public PolicyBean createPolicy(String organizationId, String entityId, String entityVersion, NewPolicyBean bean, PolicyType type) throws PolicyDefinitionNotFoundException {
    return tryAction(() -> {
        if (bean.getDefinitionId() == null) {
            // $NON-NLS-1$
            throw ExceptionFactory.policyDefNotFoundException("null");
        }
        PolicyDefinitionBean def = storage.getPolicyDefinition(bean.getDefinitionId());
        if (def == null) {
            throw ExceptionFactory.policyDefNotFoundException(bean.getDefinitionId());
        }
        int newIdx = query.getMaxPolicyOrderIndex(organizationId, entityId, entityVersion, type) + 1;
        PolicyBean policy = new PolicyBean();
        policy.setId(null);
        policy.setDefinition(def);
        policy.setName(def.getName());
        policy.setConfiguration(bean.getConfiguration());
        policy.setCreatedBy(securityContext.getCurrentUser());
        policy.setCreatedOn(new Date());
        policy.setModifiedBy(securityContext.getCurrentUser());
        policy.setModifiedOn(new Date());
        policy.setOrganizationId(organizationId);
        policy.setEntityId(entityId);
        policy.setEntityVersion(entityVersion);
        policy.setType(type);
        policy.setOrderIndex(newIdx);
        if (type == PolicyType.Client) {
            ClientVersionBean cvb = storage.getClientVersion(organizationId, entityId, entityVersion);
            cvb.setModifiedBy(securityContext.getCurrentUser());
            cvb.setModifiedOn(new Date());
            storage.updateClientVersion(cvb);
        } else if (type == PolicyType.Api) {
            ApiVersionBean avb = storage.getApiVersion(organizationId, entityId, entityVersion);
            avb.setModifiedBy(securityContext.getCurrentUser());
            avb.setModifiedOn(new Date());
            storage.updateApiVersion(avb);
        } else if (type == PolicyType.Plan) {
            PlanVersionBean pvb = storage.getPlanVersion(organizationId, entityId, entityVersion);
            pvb.setModifiedBy(securityContext.getCurrentUser());
            pvb.setModifiedOn(new Date());
            storage.updatePlanVersion(pvb);
        }
        storage.createPolicy(policy);
        storage.createAuditEntry(AuditUtils.policyAdded(policy, type, securityContext));
        PolicyTemplateUtil.generatePolicyDescription(policy);
        // $NON-NLS-1$
        LOGGER.debug(String.format("Created client policy: %s", policy));
        return policy;
    });
}
Also used : ClientVersionBean(io.apiman.manager.api.beans.clients.ClientVersionBean) PolicyDefinitionBean(io.apiman.manager.api.beans.policies.PolicyDefinitionBean) PolicyBean(io.apiman.manager.api.beans.policies.PolicyBean) NewPolicyBean(io.apiman.manager.api.beans.policies.NewPolicyBean) ApiVersionBean(io.apiman.manager.api.beans.apis.ApiVersionBean) Date(java.util.Date) PlanVersionBean(io.apiman.manager.api.beans.plans.PlanVersionBean)

Example 19 with ApiVersionBean

use of io.apiman.manager.api.beans.apis.ApiVersionBean in project apiman by apiman.

the class OpenApi3 method rewrite.

@Override
public void rewrite(ProviderContext ctx, Document schema) throws StorageException, GatewayAuthenticationException {
    // Prepare the data we need to extract to build the servers
    ApiVersionBean avb = ctx.getAvb();
    String orgId = avb.getApi().getOrganization().getId();
    String apiId = avb.getApi().getId();
    String apiVersion = avb.getVersion();
    // Find IDs of all GWs this ApiVersion is published onto.
    Set<String> gatewayIds = avb.getGateways().stream().map(ApiGatewayBean::getGatewayId).collect(Collectors.toUnmodifiableSet());
    Set<ApiEndpointWithDescription> endpoints = new HashSet<>(gatewayIds.size());
    for (GatewayBean gateway : ctx.getStorage().getGateways(gatewayIds)) {
        IGatewayLink link = ctx.getGatewayLinkFactory().create(gateway);
        endpoints.add(new ApiEndpointWithDescription(link.getApiEndpoint(orgId, apiId, apiVersion).getEndpoint(), gateway.getName(), gateway.getDescription()));
    }
    // We can guarantee it's an OAS3.x doc.
    Oas30Document oas3 = (Oas30Document) schema;
    // For now, we just ditch the inbuilt servers and list ours. Later we may do something more intelligent with the user's input.
    if (oas3.servers != null) {
        oas3.servers.clear();
    }
    // Generate new server endpoints with each GW the API Version is published into inserted into the list.
    for (ApiEndpointWithDescription endpoint : endpoints) {
        String nameAndDesc = endpoint.getName();
        if (StringUtils.isNotBlank(endpoint.getDescription())) {
            nameAndDesc += ": " + endpoint.getDescription();
        }
        oas3.addServer(endpoint.getEndpoint(), nameAndDesc);
    }
}
Also used : Oas30Document(io.apicurio.datamodels.openapi.v3.models.Oas30Document) GatewayBean(io.apiman.manager.api.beans.gateways.GatewayBean) ApiGatewayBean(io.apiman.manager.api.beans.apis.ApiGatewayBean) ApiVersionBean(io.apiman.manager.api.beans.apis.ApiVersionBean) IGatewayLink(io.apiman.manager.api.gateway.IGatewayLink) HashSet(java.util.HashSet)

Example 20 with ApiVersionBean

use of io.apiman.manager.api.beans.apis.ApiVersionBean in project apiman by apiman.

the class ActionService method approveContract.

public void approveContract(ContractActionDto action, String approverId) {
    // Must exist
    ContractBean contract = tryAction(() -> storage.getContract(action.getContractId()));
    if (contract == null) {
        throw ExceptionFactory.actionException(Messages.i18n.format("ContractDoesNotExist"));
    }
    // Must be in AwaitingApproval state (no need to approve otherwise!)
    if (contract.getStatus() != ContractStatus.AwaitingApproval) {
        throw ExceptionFactory.invalidContractStatus(ContractStatus.AwaitingApproval, contract.getStatus());
    }
    // We probably need an optimised query :-).
    ClientVersionBean cvb = contract.getClient();
    ApiVersionBean avb = contract.getApi();
    OrganizationBean org = avb.getApi().getOrganization();
    PlanVersionBean plan = contract.getPlan();
    OrganizationBean orgA = avb.getApi().getOrganization();
    OrganizationBean orgC = cvb.getClient().getOrganization();
    UserBean approver = tryAction(() -> storage.getUser(approverId));
    // Set the contract to approved state and send approved event.
    contract.setStatus(ContractStatus.Created);
    LOGGER.debug("{0} approved a contract: {1} -> {2}", approverId, contract, action);
    // In the second phase we need to check the other contracts to see whether they are all in the 'ready' state
    // If so, then it's ready to publish.
    List<ContractBean> contracts = tryAction(() -> Streams.stream((storage.getAllContracts(org.getId(), cvb.getClient().getId(), cvb.getVersion())))).collect(Collectors.toList());
    List<ContractBean> awaitingApprovalList = contracts.stream().filter(c -> c.getStatus().equals(ContractStatus.AwaitingApproval)).collect(Collectors.toList());
    if (awaitingApprovalList.size() > 0) {
        LOGGER.debug("A contract was approved, but {0} other contracts are still awaiting approval, " + "so client version {1} will remain in its pending state until the remaining contract approvals " + "are granted: {2}.", awaitingApprovalList.size(), cvb.getVersion(), awaitingApprovalList);
    } else {
        LOGGER.debug("All contracts for {0} have been approved", cvb.getVersion());
        tryAction(() -> {
            if (clientValidator.isReady(cvb)) {
                // Set client to ready status and fire change status event
                LOGGER.debug("Client set to ready as all contracts have been approved");
                cvb.setStatus(ClientStatus.Ready);
                clientAppService.fireClientStatusChangeEvent(cvb, ClientStatus.AwaitingApproval);
                // If auto-promote, then we immediately register.
                if (action.isAutoPromote()) {
                    LOGGER.debug("Auto approving: {0}", cvb);
                    registerClient(orgC.getId(), cvb.getClient().getId(), cvb.getVersion());
                }
            }
        });
    }
    // storage.flush();
    fireContractApprovedEvent(approver, contract, orgC, cvb, orgA, avb, plan);
}
Also used : ClientVersionBean(io.apiman.manager.api.beans.clients.ClientVersionBean) ContractApprovalEvent(io.apiman.manager.api.beans.events.ContractApprovalEvent) ApiGatewayBean(io.apiman.manager.api.beans.apis.ApiGatewayBean) Date(java.util.Date) ApiVersionNotFoundException(io.apiman.manager.api.rest.exceptions.ApiVersionNotFoundException) StorageException(io.apiman.manager.api.core.exceptions.StorageException) ApiVersionBean(io.apiman.manager.api.beans.apis.ApiVersionBean) ISecurityContext(io.apiman.manager.api.security.ISecurityContext) GatewayNotFoundException(io.apiman.manager.api.rest.exceptions.GatewayNotFoundException) IGatewayLinkFactory(io.apiman.manager.api.gateway.IGatewayLinkFactory) ApimanEventHeaders(io.apiman.manager.api.beans.events.ApimanEventHeaders) UserBean(io.apiman.manager.api.beans.idm.UserBean) Client(io.apiman.gateway.engine.beans.Client) ApiBean(io.apiman.manager.api.beans.apis.ApiBean) UserMapper(io.apiman.manager.api.beans.idm.UserMapper) IClientValidator(io.apiman.manager.api.core.IClientValidator) Map(java.util.Map) URI(java.net.URI) ApimanLoggerFactory(io.apiman.common.logging.ApimanLoggerFactory) Contract(io.apiman.gateway.engine.beans.Contract) OrganizationBean(io.apiman.manager.api.beans.orgs.OrganizationBean) Policy(io.apiman.gateway.engine.beans.Policy) Transactional(javax.transaction.Transactional) IGatewayLink(io.apiman.manager.api.gateway.IGatewayLink) EventService(io.apiman.manager.api.events.EventService) Set(java.util.Set) UUID(java.util.UUID) Streams(com.google.common.collect.Streams) Collectors(java.util.stream.Collectors) ContractStatus(io.apiman.manager.api.beans.contracts.ContractStatus) NotAuthorizedException(io.apiman.manager.api.rest.exceptions.NotAuthorizedException) List(java.util.List) IApimanLogger(io.apiman.common.logging.IApimanLogger) PolicySummaryBean(io.apiman.manager.api.beans.summary.PolicySummaryBean) ContractActionDto(io.apiman.manager.api.beans.actions.ContractActionDto) ApplicationScoped(javax.enterprise.context.ApplicationScoped) ActionException(io.apiman.manager.api.rest.exceptions.ActionException) HashMap(java.util.HashMap) ApiStatus(io.apiman.manager.api.beans.apis.ApiStatus) PolicyBean(io.apiman.manager.api.beans.policies.PolicyBean) AuditUtils(io.apiman.manager.api.rest.impl.audit.AuditUtils) ArrayList(java.util.ArrayList) ContractBean(io.apiman.manager.api.beans.contracts.ContractBean) HashSet(java.util.HashSet) Inject(javax.inject.Inject) PlanVersionNotFoundException(io.apiman.manager.api.rest.exceptions.PlanVersionNotFoundException) PublishingException(io.apiman.gateway.engine.beans.exceptions.PublishingException) IStorageQuery(io.apiman.manager.api.core.IStorageQuery) DataAccessUtilMixin(io.apiman.manager.api.rest.impl.util.DataAccessUtilMixin) PlanVersionBean(io.apiman.manager.api.beans.plans.PlanVersionBean) Iterator(java.util.Iterator) GatewayBean(io.apiman.manager.api.beans.gateways.GatewayBean) ClientStatus(io.apiman.manager.api.beans.clients.ClientStatus) ContractSummaryBean(io.apiman.manager.api.beans.summary.ContractSummaryBean) IStorage(io.apiman.manager.api.core.IStorage) ClientVersionBean(io.apiman.manager.api.beans.clients.ClientVersionBean) ClientVersionNotFoundException(io.apiman.manager.api.rest.exceptions.ClientVersionNotFoundException) Api(io.apiman.gateway.engine.beans.Api) PolicyType(io.apiman.manager.api.beans.policies.PolicyType) Messages(io.apiman.manager.api.rest.exceptions.i18n.Messages) PlanStatus(io.apiman.manager.api.beans.plans.PlanStatus) ExceptionFactory(io.apiman.manager.api.rest.exceptions.util.ExceptionFactory) UserBean(io.apiman.manager.api.beans.idm.UserBean) OrganizationBean(io.apiman.manager.api.beans.orgs.OrganizationBean) ApiVersionBean(io.apiman.manager.api.beans.apis.ApiVersionBean) ContractBean(io.apiman.manager.api.beans.contracts.ContractBean) PlanVersionBean(io.apiman.manager.api.beans.plans.PlanVersionBean)

Aggregations

ApiVersionBean (io.apiman.manager.api.beans.apis.ApiVersionBean)68 StorageException (io.apiman.manager.api.core.exceptions.StorageException)34 Date (java.util.Date)29 NewApiVersionBean (io.apiman.manager.api.beans.apis.NewApiVersionBean)28 UpdateApiVersionBean (io.apiman.manager.api.beans.apis.UpdateApiVersionBean)28 ApiVersionNotFoundException (io.apiman.manager.api.rest.exceptions.ApiVersionNotFoundException)25 GatewayNotFoundException (io.apiman.manager.api.rest.exceptions.GatewayNotFoundException)25 NotAuthorizedException (io.apiman.manager.api.rest.exceptions.NotAuthorizedException)25 ApiGatewayBean (io.apiman.manager.api.beans.apis.ApiGatewayBean)23 ClientVersionNotFoundException (io.apiman.manager.api.rest.exceptions.ClientVersionNotFoundException)22 PlanVersionNotFoundException (io.apiman.manager.api.rest.exceptions.PlanVersionNotFoundException)22 PolicyBean (io.apiman.manager.api.beans.policies.PolicyBean)20 SystemErrorException (io.apiman.manager.api.rest.exceptions.SystemErrorException)20 ApiBean (io.apiman.manager.api.beans.apis.ApiBean)19 PlanVersionBean (io.apiman.manager.api.beans.plans.PlanVersionBean)18 GatewayAuthenticationException (io.apiman.manager.api.gateway.GatewayAuthenticationException)17 IGatewayLink (io.apiman.manager.api.gateway.IGatewayLink)16 ApiAlreadyExistsException (io.apiman.manager.api.rest.exceptions.ApiAlreadyExistsException)16 ApiDefinitionNotFoundException (io.apiman.manager.api.rest.exceptions.ApiDefinitionNotFoundException)16 ApiNotFoundException (io.apiman.manager.api.rest.exceptions.ApiNotFoundException)16