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);
}
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;
}
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;
});
}
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);
}
}
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);
}
Aggregations