use of io.apiman.gateway.engine.beans.Client in project apiman by apiman.
the class ActionResourceImpl method registerClient.
/**
* Registers an client (along with all of its contracts) to the gateway.
* @param action
*/
private void registerClient(ActionBean action) throws ActionException, NotAuthorizedException {
securityContext.checkPermissions(PermissionType.clientAdmin, action.getOrganizationId());
ClientVersionBean versionBean;
List<ContractSummaryBean> contractBeans;
try {
versionBean = orgs.getClientVersion(action.getOrganizationId(), action.getEntityId(), action.getEntityVersion());
} catch (ClientVersionNotFoundException e) {
// $NON-NLS-1$
throw ExceptionFactory.actionException(Messages.i18n.format("clientVersionDoesNotExist", action.getEntityId(), action.getEntityVersion()));
}
try {
contractBeans = query.getClientContracts(action.getOrganizationId(), action.getEntityId(), action.getEntityVersion());
} catch (StorageException e) {
// $NON-NLS-1$
throw ExceptionFactory.actionException(Messages.i18n.format("ClientNotFound"), e);
}
boolean isReregister = false;
// Validate that it's ok to perform this action
if (versionBean.getStatus() == ClientStatus.Registered) {
Date modOn = versionBean.getModifiedOn();
Date publishedOn = versionBean.getPublishedOn();
int c = modOn.compareTo(publishedOn);
if (c <= 0) {
// $NON-NLS-1$
throw ExceptionFactory.actionException(Messages.i18n.format("ClientReRegisterNotRequired"));
}
isReregister = true;
}
Client client = new Client();
client.setOrganizationId(versionBean.getClient().getOrganization().getId());
client.setClientId(versionBean.getClient().getId());
client.setVersion(versionBean.getVersion());
client.setApiKey(versionBean.getApikey());
Set<Contract> contracts = new HashSet<>();
for (ContractSummaryBean contractBean : contractBeans) {
Contract contract = new Contract();
contract.setPlan(contractBean.getPlanId());
contract.setApiId(contractBean.getApiId());
contract.setApiOrgId(contractBean.getApiOrganizationId());
contract.setApiVersion(contractBean.getApiVersion());
contract.getPolicies().addAll(aggregateContractPolicies(contractBean));
contracts.add(contract);
}
client.setContracts(contracts);
// Each of those gateways must be told about the client.
try {
storage.beginTx();
Map<String, IGatewayLink> links = new HashMap<>();
for (Contract contract : client.getContracts()) {
ApiVersionBean svb = storage.getApiVersion(contract.getApiOrgId(), contract.getApiId(), contract.getApiVersion());
Set<ApiGatewayBean> gateways = svb.getGateways();
if (gateways == null) {
// $NON-NLS-1$
throw new PublishingException("No gateways specified for API: " + svb.getApi().getName());
}
for (ApiGatewayBean apiGatewayBean : gateways) {
if (!links.containsKey(apiGatewayBean.getGatewayId())) {
IGatewayLink gatewayLink = createGatewayLink(apiGatewayBean.getGatewayId());
links.put(apiGatewayBean.getGatewayId(), gatewayLink);
}
}
}
if (isReregister) {
// Once we figure out which gateways to register with, make sure we also "unregister"
// the client app from all other gateways. This is necessary because we may have broken
// contracts we previously had on APIs that are published to other gateways. And thus
// it's possible we need to remove a contract from a Gateway that is not otherwise/currently
// referenced.
//
// This is a fix for: https://issues.jboss.org/browse/APIMAN-895
Iterator<GatewayBean> gateways = storage.getAllGateways();
while (gateways.hasNext()) {
GatewayBean gbean = gateways.next();
if (!links.containsKey(gbean.getId())) {
IGatewayLink gatewayLink = createGatewayLink(gbean.getId());
try {
gatewayLink.unregisterClient(client);
} catch (Exception e) {
// We need to catch the error, but ignore it,
// in the event that the gateway is invalid.
}
gatewayLink.close();
}
}
}
for (IGatewayLink gatewayLink : links.values()) {
gatewayLink.registerClient(client);
gatewayLink.close();
}
storage.commitTx();
} catch (Exception e) {
storage.rollbackTx();
// $NON-NLS-1$
throw ExceptionFactory.actionException(Messages.i18n.format("RegisterError"), e);
}
versionBean.setStatus(ClientStatus.Registered);
versionBean.setPublishedOn(new Date());
try {
storage.beginTx();
storage.updateClientVersion(versionBean);
storage.createAuditEntry(AuditUtils.clientRegistered(versionBean, securityContext));
storage.commitTx();
} catch (Exception e) {
storage.rollbackTx();
// $NON-NLS-1$
throw ExceptionFactory.actionException(Messages.i18n.format("RegisterError"), e);
}
log.debug(// $NON-NLS-1$
String.format(// $NON-NLS-1$
"Successfully registered Client %s on specified gateways: %s", versionBean.getClient().getName(), versionBean.getClient()));
}
use of io.apiman.gateway.engine.beans.Client 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);
}
use of io.apiman.gateway.engine.beans.Client in project apiman by apiman.
the class ActionService method unregisterClient.
/**
* De-registers an client that is currently registered with the gateway.
*/
public void unregisterClient(String orgId, String clientId, String clientVersion) throws ActionException, NotAuthorizedException {
ClientVersionBean versionBean;
List<ContractSummaryBean> contractBeans;
try {
versionBean = clientAppService.getClientVersion(orgId, clientId, clientVersion);
} catch (ClientVersionNotFoundException e) {
// $NON-NLS-1$
throw ExceptionFactory.actionException(Messages.i18n.format("ClientNotFound"));
}
try {
contractBeans = query.getClientContracts(orgId, clientId, clientVersion).stream().peek(c -> {
if (c.getStatus() != ContractStatus.Created) {
LOGGER.debug("Will not try to delete contract {0} from gateway(s) as it is not in 'Created' state", c);
}
}).filter(c -> c.getStatus() == ContractStatus.Created).collect(Collectors.toList());
} catch (StorageException e) {
// $NON-NLS-1$
throw ExceptionFactory.actionException(Messages.i18n.format("ClientNotFound"), e);
}
// Validate that it's ok to perform this action - client must be either registered or awaiting approval (or there's nothing to unregister)
if (versionBean.getStatus() != ClientStatus.Registered && versionBean.getStatus() != ClientStatus.AwaitingApproval) {
// $NON-NLS-1$
throw ExceptionFactory.actionException(Messages.i18n.format("InvalidClientStatus"));
}
Client client = new Client();
client.setOrganizationId(versionBean.getClient().getOrganization().getId());
client.setClientId(versionBean.getClient().getId());
client.setVersion(versionBean.getVersion());
// Each of those gateways must be told about the client.
try {
Map<String, IGatewayLink> links = new HashMap<>();
for (ContractSummaryBean contractBean : contractBeans) {
ApiVersionBean svb = storage.getApiVersion(contractBean.getApiOrganizationId(), contractBean.getApiId(), contractBean.getApiVersion());
Set<ApiGatewayBean> gateways = svb.getGateways();
if (gateways == null) {
// $NON-NLS-1$
throw new PublishingException("No gateways specified for API: " + svb.getApi().getName());
}
for (ApiGatewayBean apiGatewayBean : gateways) {
if (!links.containsKey(apiGatewayBean.getGatewayId())) {
IGatewayLink gatewayLink = createGatewayLink(apiGatewayBean.getGatewayId());
links.put(apiGatewayBean.getGatewayId(), gatewayLink);
}
}
}
for (IGatewayLink gatewayLink : links.values()) {
gatewayLink.unregisterClient(client);
gatewayLink.close();
}
} catch (Exception e) {
// $NON-NLS-1$
throw ExceptionFactory.actionException(Messages.i18n.format("UnregisterError"), e);
}
ClientStatus oldStatus = versionBean.getStatus();
versionBean.setStatus(ClientStatus.Retired);
versionBean.setRetiredOn(new Date());
clientAppService.fireClientStatusChangeEvent(versionBean, oldStatus);
try {
storage.updateClientVersion(versionBean);
storage.createAuditEntry(AuditUtils.clientUnregistered(versionBean, securityContext));
} catch (Exception e) {
// $NON-NLS-1$
throw ExceptionFactory.actionException(Messages.i18n.format("UnregisterError"), e);
}
LOGGER.debug(// $NON-NLS-1$
String.format(// $NON-NLS-1$
"Successfully registered Client %s on specified gateways: %s", versionBean.getClient().getName(), versionBean.getClient()));
}
use of io.apiman.gateway.engine.beans.Client in project apiman by apiman.
the class CachingEsRegistry method getContract.
/**
* @see io.apiman.gateway.engine.jdbc.EsRegistry#getContract(java.lang.String, java.lang.String, java.lang.String, java.lang.String, io.apiman.gateway.engine.async.IAsyncResultHandler)
*/
@Override
public void getContract(String apiOrganizationId, String apiId, String apiVersion, String apiKey, IAsyncResultHandler<ApiContract> handler) {
Client client = null;
Api api = null;
try {
synchronized (mutex) {
client = getClient(apiKey);
api = getApi(apiOrganizationId, apiId, apiVersion);
}
if (client == null) {
// $NON-NLS-1$
Exception error = new ClientNotFoundException(Messages.i18n.format("EsRegistry.NoClientForAPIKey", apiKey));
handler.handle(AsyncResultImpl.create(error, ApiContract.class));
return;
}
if (api == null) {
throw new ApiRetiredException(// $NON-NLS-1$
Messages.i18n.format(// $NON-NLS-1$
"EsRegistry.ApiWasRetired", apiId, apiOrganizationId));
}
Contract matchedContract = null;
for (Contract contract : client.getContracts()) {
if (contract.matches(apiOrganizationId, apiId, apiVersion)) {
matchedContract = contract;
break;
}
}
if (matchedContract == null) {
throw new NoContractFoundException(// $NON-NLS-1$
Messages.i18n.format(// $NON-NLS-1$
"EsRegistry.NoContractFound", client.getClientId(), api.getApiId()));
}
ApiContract contract = new ApiContract(api, client, matchedContract.getPlan(), matchedContract.getPolicies());
handler.handle(AsyncResultImpl.create(contract));
} catch (Exception e) {
handler.handle(AsyncResultImpl.create(e, ApiContract.class));
}
}
use of io.apiman.gateway.engine.beans.Client in project apiman by apiman.
the class EsRegistry method unregisterClient.
/**
* @see io.apiman.gateway.engine.IRegistry#unregisterClient(io.apiman.gateway.engine.beans.Client, io.apiman.gateway.engine.async.IAsyncResultHandler)
*/
@Override
public void unregisterClient(final Client client, final IAsyncResultHandler<Void> handler) {
try {
final Client lclient = lookupClient(client.getOrganizationId(), client.getClientId(), client.getVersion());
final String id = getClientId(lclient);
DeleteRequest deleteRequest = new DeleteRequest(getIndexPrefixWithJoiner() + EsConstants.INDEX_CLIENTS).id(id).setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
DeleteResponse response = getClient().delete(deleteRequest, RequestOptions.DEFAULT);
if (response.status().equals(RestStatus.OK)) {
handler.handle(AsyncResultImpl.create((Void) null));
} else {
// $NON-NLS-1$
handler.handle(AsyncResultImpl.create(new ApiNotFoundException(Messages.i18n.format("EsRegistry.ClientNotFound"))));
}
} catch (IOException e) {
// $NON-NLS-1$
handler.handle(AsyncResultImpl.create(new PublishingException(Messages.i18n.format("EsRegistry.ErrorUnregisteringClient"), e), Void.class));
} catch (RuntimeException e) {
handler.handle(AsyncResultImpl.create(e));
}
}
Aggregations