Search in sources :

Example 1 with GatewayBean

use of io.apiman.manager.api.beans.gateways.GatewayBean in project apiman by apiman.

the class OrganizationResourceImpl method getApiRegistry.

/**
 * Gets the API registry.
 * @param organizationId
 * @param clientId
 * @param version
 * @throws ClientVersionNotFoundException
 */
private ApiRegistryBean getApiRegistry(String organizationId, String clientId, String version) throws ClientVersionNotFoundException {
    // Try to get the client first - will throw a ClientVersionNotFoundException if not found.
    ClientVersionBean clientVersion = getClientVersionInternal(organizationId, clientId, version);
    Map<String, IGatewayLink> gatewayLinks = new HashMap<>();
    Map<String, GatewayBean> gateways = new HashMap<>();
    boolean txStarted = false;
    try {
        ApiRegistryBean apiRegistry = query.getApiRegistry(organizationId, clientId, version);
        apiRegistry.setApiKey(clientVersion.getApikey());
        List<ApiEntryBean> apis = apiRegistry.getApis();
        storage.beginTx();
        txStarted = true;
        for (ApiEntryBean api : apis) {
            String gatewayId = api.getGatewayId();
            // Don't return the gateway id.
            api.setGatewayId(null);
            GatewayBean gateway = gateways.get(gatewayId);
            if (gateway == null) {
                gateway = storage.getGateway(gatewayId);
                gateways.put(gatewayId, gateway);
            }
            IGatewayLink link = gatewayLinks.get(gatewayId);
            if (link == null) {
                link = gatewayLinkFactory.create(gateway);
                gatewayLinks.put(gatewayId, link);
            }
            ApiEndpoint se = link.getApiEndpoint(api.getApiOrgId(), api.getApiId(), api.getApiVersion());
            String apiEndpoint = se.getEndpoint();
            api.setHttpEndpoint(apiEndpoint);
        }
        return apiRegistry;
    } catch (StorageException | GatewayAuthenticationException e) {
        throw new SystemErrorException(e);
    } finally {
        if (txStarted) {
            storage.rollbackTx();
        }
        for (IGatewayLink link : gatewayLinks.values()) {
            link.close();
        }
    }
}
Also used : NewClientVersionBean(io.apiman.manager.api.beans.clients.NewClientVersionBean) ClientVersionBean(io.apiman.manager.api.beans.clients.ClientVersionBean) SystemErrorException(io.apiman.manager.api.rest.exceptions.SystemErrorException) ApiRegistryBean(io.apiman.manager.api.beans.summary.ApiRegistryBean) HashMap(java.util.HashMap) ApiEndpoint(io.apiman.gateway.engine.beans.ApiEndpoint) IGatewayLink(io.apiman.manager.api.gateway.IGatewayLink) GatewayAuthenticationException(io.apiman.manager.api.gateway.GatewayAuthenticationException) ApiEntryBean(io.apiman.manager.api.beans.summary.ApiEntryBean) ApiGatewayBean(io.apiman.manager.api.beans.apis.ApiGatewayBean) GatewayBean(io.apiman.manager.api.beans.gateways.GatewayBean) StorageException(io.apiman.manager.api.core.exceptions.StorageException)

Example 2 with GatewayBean

use of io.apiman.manager.api.beans.gateways.GatewayBean in project apiman by apiman.

the class EsMarshalling method unmarshallGateway.

/**
 * Unmarshals the given map source into a bean.
 * @param source the source
 * @return the gateway bean
 */
public static GatewayBean unmarshallGateway(Map<String, Object> source) {
    if (source == null) {
        return null;
    }
    GatewayBean bean = new GatewayBean();
    bean.setId(asString(source.get("id")));
    bean.setName(asString(source.get("name")));
    bean.setDescription(asString(source.get("description")));
    bean.setType(asEnum(source.get("type"), GatewayType.class));
    bean.setConfiguration(asString(source.get("configuration")));
    bean.setCreatedBy(asString(source.get("createdBy")));
    bean.setCreatedOn(asDate(source.get("createdOn")));
    bean.setModifiedBy(asString(source.get("modifiedBy")));
    bean.setModifiedOn(asDate(source.get("modifiedOn")));
    postMarshall(bean);
    return bean;
}
Also used : GatewayType(io.apiman.manager.api.beans.gateways.GatewayType) ApiGatewayBean(io.apiman.manager.api.beans.apis.ApiGatewayBean) GatewayBean(io.apiman.manager.api.beans.gateways.GatewayBean)

Example 3 with GatewayBean

use of io.apiman.manager.api.beans.gateways.GatewayBean in project apiman by apiman.

the class EsMarshallingTest method testMarshallGatewayBean.

/**
 * Test method for {@link io.apiman.manager.api.es.EsMarshalling#marshall(io.apiman.manager.api.beans.gateways.GatewayBean)}.
 */
@Test
public void testMarshallGatewayBean() throws Exception {
    GatewayBean bean = createBean(GatewayBean.class);
    XContentBuilder builder = EsMarshalling.marshall(bean);
    Assert.assertEquals("{\"id\":\"ID\",\"name\":\"NAME\",\"description\":\"DESCRIPTION\",\"type\":\"REST\",\"configuration\":\"CONFIGURATION\",\"createdBy\":\"CREATEDBY\",\"createdOn\":1,\"modifiedBy\":\"MODIFIEDBY\",\"modifiedOn\":1}", Strings.toString(builder));
}
Also used : GatewayBean(io.apiman.manager.api.beans.gateways.GatewayBean) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) Test(org.junit.Test)

Example 4 with GatewayBean

use of io.apiman.manager.api.beans.gateways.GatewayBean 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()));
}
Also used : ClientVersionBean(io.apiman.manager.api.beans.clients.ClientVersionBean) ClientVersionNotFoundException(io.apiman.manager.api.rest.exceptions.ClientVersionNotFoundException) HashMap(java.util.HashMap) Date(java.util.Date) IGatewayLink(io.apiman.manager.api.gateway.IGatewayLink) ApiVersionNotFoundException(io.apiman.manager.api.rest.exceptions.ApiVersionNotFoundException) StorageException(io.apiman.manager.api.core.exceptions.StorageException) GatewayNotFoundException(io.apiman.manager.api.rest.exceptions.GatewayNotFoundException) NotAuthorizedException(io.apiman.manager.api.rest.exceptions.NotAuthorizedException) ActionException(io.apiman.manager.api.rest.exceptions.ActionException) PlanVersionNotFoundException(io.apiman.manager.api.rest.exceptions.PlanVersionNotFoundException) PublishingException(io.apiman.gateway.engine.beans.exceptions.PublishingException) ClientVersionNotFoundException(io.apiman.manager.api.rest.exceptions.ClientVersionNotFoundException) ApiGatewayBean(io.apiman.manager.api.beans.apis.ApiGatewayBean) PublishingException(io.apiman.gateway.engine.beans.exceptions.PublishingException) ApiGatewayBean(io.apiman.manager.api.beans.apis.ApiGatewayBean) GatewayBean(io.apiman.manager.api.beans.gateways.GatewayBean) ContractSummaryBean(io.apiman.manager.api.beans.summary.ContractSummaryBean) Client(io.apiman.gateway.engine.beans.Client) StorageException(io.apiman.manager.api.core.exceptions.StorageException) Contract(io.apiman.gateway.engine.beans.Contract) ApiVersionBean(io.apiman.manager.api.beans.apis.ApiVersionBean) HashSet(java.util.HashSet)

Example 5 with GatewayBean

use of io.apiman.manager.api.beans.gateways.GatewayBean in project apiman by apiman.

the class ContractService method probePolicy.

// TODO make properly optimised query for this
public List<IPolicyProbeResponse> probePolicy(Long contractId, long policyId, String rawPayload) throws ClientNotFoundException, ContractNotFoundException {
    ContractBean contract = getContract(contractId);
    ApiVersionBean avb = contract.getApi();
    OrganizationBean apiOrg = avb.getApi().getOrganization();
    String apiKey = contract.getClient().getApikey();
    Set<String> gatewayIds = contract.getApi().getGateways().stream().map(ApiGatewayBean::getGatewayId).collect(Collectors.toSet());
    if (gatewayIds.size() == 0) {
        return List.of();
    }
    List<PolicyBean> policyChain = aggregateContractPolicies(contract);
    int idxFound = -1;
    for (int i = 0, policyChainSize = policyChain.size(); i < policyChainSize; i++) {
        PolicyBean policy = policyChain.get(i);
        if (policy.getId().equals(policyId)) {
            idxFound = i;
        }
    }
    if (idxFound == -1) {
        throw new IllegalArgumentException("Provided policy ID not found in contract " + policyId);
    }
    List<GatewayBean> gateways = tryAction(() -> storage.getGateways(gatewayIds));
    LOGGER.debug("Gateways for contract {0}: {1}", contractId, gateways);
    List<IPolicyProbeResponse> probeResponses = new ArrayList<>(gateways.size());
    for (GatewayBean gateway : gateways) {
        IGatewayLink link = gatewayLinkFactory.create(gateway);
        try {
            probeResponses.add(link.probe(apiOrg.getId(), avb.getApi().getId(), avb.getVersion(), idxFound, apiKey, rawPayload));
        } catch (GatewayAuthenticationException e) {
            throw new SystemErrorException(e);
        }
    }
    LOGGER.debug("Probe responses for contract {0}: {1}", contractId, probeResponses);
    return probeResponses;
}
Also used : SystemErrorException(io.apiman.manager.api.rest.exceptions.SystemErrorException) IPolicyProbeResponse(io.apiman.gateway.engine.beans.IPolicyProbeResponse) PolicyBean(io.apiman.manager.api.beans.policies.PolicyBean) ArrayList(java.util.ArrayList) IGatewayLink(io.apiman.manager.api.gateway.IGatewayLink) GatewayAuthenticationException(io.apiman.manager.api.gateway.GatewayAuthenticationException) NewContractBean(io.apiman.manager.api.beans.contracts.NewContractBean) ContractBean(io.apiman.manager.api.beans.contracts.ContractBean) ApiGatewayBean(io.apiman.manager.api.beans.apis.ApiGatewayBean) GatewayBean(io.apiman.manager.api.beans.gateways.GatewayBean) OrganizationBean(io.apiman.manager.api.beans.orgs.OrganizationBean) ApiVersionBean(io.apiman.manager.api.beans.apis.ApiVersionBean)

Aggregations

GatewayBean (io.apiman.manager.api.beans.gateways.GatewayBean)22 IGatewayLink (io.apiman.manager.api.gateway.IGatewayLink)14 ApiGatewayBean (io.apiman.manager.api.beans.apis.ApiGatewayBean)13 StorageException (io.apiman.manager.api.core.exceptions.StorageException)13 GatewayNotFoundException (io.apiman.manager.api.rest.exceptions.GatewayNotFoundException)11 SystemErrorException (io.apiman.manager.api.rest.exceptions.SystemErrorException)11 GatewayAuthenticationException (io.apiman.manager.api.gateway.GatewayAuthenticationException)9 NotAuthorizedException (io.apiman.manager.api.rest.exceptions.NotAuthorizedException)9 ApiVersionBean (io.apiman.manager.api.beans.apis.ApiVersionBean)6 NewGatewayBean (io.apiman.manager.api.beans.gateways.NewGatewayBean)6 UpdateGatewayBean (io.apiman.manager.api.beans.gateways.UpdateGatewayBean)6 AbstractRestException (io.apiman.manager.api.rest.exceptions.AbstractRestException)6 GatewayAlreadyExistsException (io.apiman.manager.api.rest.exceptions.GatewayAlreadyExistsException)6 ApiEndpoint (io.apiman.gateway.engine.beans.ApiEndpoint)4 PublishingException (io.apiman.gateway.engine.beans.exceptions.PublishingException)4 ClientVersionBean (io.apiman.manager.api.beans.clients.ClientVersionBean)4 Date (java.util.Date)4 HashMap (java.util.HashMap)4 ActionException (io.apiman.manager.api.rest.exceptions.ActionException)3 ApiVersionNotFoundException (io.apiman.manager.api.rest.exceptions.ApiVersionNotFoundException)3