Search in sources :

Example 1 with IPolicy

use of io.apiman.gateway.engine.policy.IPolicy in project apiman by apiman.

the class ApiRequestExecutorImpl method loadPolicies.

/**
 * Get/resolve the list of policies into a list of policies with config.  This operation is
 * done asynchronously so that plugins can be downloaded if needed.  Any errors in resolving
 * the policies will be reported back via the policyErrorHandler.
 */
private void loadPolicies(final IAsyncHandler<List<PolicyWithConfiguration>> handler) {
    final Set<Integer> totalCounter = new HashSet<>();
    final Set<Integer> errorCounter = new TreeSet<>();
    final List<PolicyWithConfiguration> rval = new ArrayList<>(policies.size());
    final List<Throwable> errors = new ArrayList<>(policies.size());
    final int numPolicies = policies.size();
    int index = 0;
    // If there aren't any policies, then no need to asynchronously load them!
    if (policies.isEmpty()) {
        handler.handle(policyImpls);
        return;
    }
    for (final Policy policy : policies) {
        rval.add(null);
        errors.add(null);
        final int localIdx = index++;
        policyFactory.loadPolicy(policy.getPolicyImpl(), (IAsyncResult<IPolicy> result) -> {
            if (result.isSuccess()) {
                IPolicy policyImpl = result.getResult();
                // Test whether pipeline contains any data policies. Connectors can use this for Content-Length pass-through.
                if (policyImpl instanceof IDataPolicy) {
                    hasDataPolicy = true;
                }
                try {
                    Object policyConfig = policyFactory.loadConfig(policyImpl, policy.getPolicyImpl(), policy.getPolicyJsonConfig());
                    PolicyWithConfiguration pwc = new PolicyWithConfiguration(policyImpl, policyConfig);
                    rval.set(localIdx, pwc);
                } catch (Throwable t) {
                    errors.set(localIdx, t);
                    errorCounter.add(localIdx);
                }
            } else {
                Throwable error = result.getError();
                errors.set(localIdx, error);
                errorCounter.add(localIdx);
            }
            totalCounter.add(localIdx);
            // Have we done them all?
            if (totalCounter.size() == numPolicies) {
                // the fully resolved list of policies.
                if (!errorCounter.isEmpty()) {
                    int errorIdx = errorCounter.iterator().next();
                    Throwable error = errors.get(errorIdx);
                    // TODO add some logging here to indicate which policy error'd out
                    // Policy errorPolicy = policies.get(errorIdx);
                    policyErrorHandler.handle(error);
                } else {
                    handler.handle(rval);
                }
            }
        });
    }
}
Also used : IDataPolicy(io.apiman.gateway.engine.policy.IDataPolicy) Policy(io.apiman.gateway.engine.beans.Policy) IPolicy(io.apiman.gateway.engine.policy.IPolicy) IPolicy(io.apiman.gateway.engine.policy.IPolicy) ArrayList(java.util.ArrayList) TreeSet(java.util.TreeSet) IDataPolicy(io.apiman.gateway.engine.policy.IDataPolicy) IAsyncResult(io.apiman.gateway.engine.async.IAsyncResult) PolicyWithConfiguration(io.apiman.gateway.engine.policy.PolicyWithConfiguration) HashSet(java.util.HashSet)

Example 2 with IPolicy

use of io.apiman.gateway.engine.policy.IPolicy in project apiman by apiman.

the class PolicyChainTest method shouldEndChainImmediatelyWhenSkipCalled.

@Test
public void shouldEndChainImmediatelyWhenSkipCalled() {
    IPolicy skipPolicy = spy(new IPolicy() {

        @Override
        public Object parseConfiguration(String jsonConfiguration) throws ConfigurationParseException {
            return null;
        }

        @Override
        public void apply(ApiRequest request, IPolicyContext context, Object config, IPolicyChain<ApiRequest> chain) {
            chain.doSkip(request);
        }

        @Override
        public void apply(ApiResponse response, IPolicyContext context, Object config, IPolicyChain<ApiResponse> chain) {
            chain.doSkip(response);
        }
    });
    PolicyWithConfiguration pwcSkip = new PolicyWithConfiguration(skipPolicy, null);
    policies.add(pwcSkip);
    policies.add(pwcTwo);
    requestChain = new RequestChain(policies, mockContext);
    requestChain.bodyHandler(mockBodyHandler);
    requestChain.endHandler(mockEndHandler);
    requestChain.doApply(mockRequest);
    requestChain.end();
    verify(mockEndHandler, times(1)).handle((Void) null);
    // Should only be called once, as the second is skipped
    verify(skipPolicy, times(1)).apply(mockRequest, mockContext, null, requestChain);
    verify(policyOne, never()).apply(mockRequest, mockContext, null, requestChain);
}
Also used : IPolicy(io.apiman.gateway.engine.policy.IPolicy) IPolicyContext(io.apiman.gateway.engine.policy.IPolicyContext) ConfigurationParseException(io.apiman.gateway.engine.beans.exceptions.ConfigurationParseException) RequestChain(io.apiman.gateway.engine.policy.RequestChain) ApiRequest(io.apiman.gateway.engine.beans.ApiRequest) PolicyWithConfiguration(io.apiman.gateway.engine.policy.PolicyWithConfiguration) ApiResponse(io.apiman.gateway.engine.beans.ApiResponse) Test(org.junit.Test)

Example 3 with IPolicy

use of io.apiman.gateway.engine.policy.IPolicy in project apiman by apiman.

the class PolicyTester method publishApi.

/**
 * Publish a API configured with the correct policy and policy config.
 * @param method
 * @throws Throwable
 */
protected void publishApi(FrameworkMethod method) {
    version++;
    try {
        // Get the policy class under test.
        TestingPolicy tp = method.getMethod().getAnnotation(TestingPolicy.class);
        if (tp == null) {
            tp = getTestClass().getJavaClass().getAnnotation(TestingPolicy.class);
        }
        if (tp == null) {
            throw new Exception("Missing test annotation @TestingPolicy.");
        }
        Class<? extends IPolicy> policyUnderTest = tp.value();
        // Get the configuration JSON to use
        Configuration config = method.getMethod().getAnnotation(Configuration.class);
        if (config == null) {
            config = getTestClass().getJavaClass().getAnnotation(Configuration.class);
        }
        if (config == null) {
            throw new Exception("Missing test annotation @Configuration.");
        }
        // Get the back end API simulator to use
        BackEndApi backEnd = method.getMethod().getAnnotation(BackEndApi.class);
        if (backEnd == null) {
            backEnd = getTestClass().getJavaClass().getAnnotation(BackEndApi.class);
        }
        Class<? extends IPolicyTestBackEndApi> backEndApi;
        if (backEnd == null) {
            backEndApi = EchoBackEndApi.class;
        } else {
            backEndApi = backEnd.value();
        }
        final Set<Throwable> errorHolder = new HashSet<>();
        Policy policy = new Policy();
        policy.setPolicyImpl("class:" + policyUnderTest.getName());
        policy.setPolicyJsonConfig(getPolicyConfiguration(config));
        Api api = new Api();
        api.setEndpoint(backEndApi.getName());
        api.setEndpointType("TEST");
        api.setOrganizationId(orgId);
        api.setApiId(apiId);
        api.setVersion(String.valueOf(version));
        api.setPublicAPI(true);
        api.setApiPolicies(Collections.singletonList(policy));
        api.setParsePayload(true);
        getEngine().getRegistry().publishApi(api, new IAsyncResultHandler<Void>() {

            @Override
            public void handle(IAsyncResult<Void> result) {
                if (result.isError()) {
                    errorHolder.add(result.getError());
                }
            }
        });
        if (!errorHolder.isEmpty()) {
            throw errorHolder.iterator().next();
        }
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}
Also used : IPolicy(io.apiman.gateway.engine.policy.IPolicy) Policy(io.apiman.gateway.engine.beans.Policy) IOException(java.io.IOException) Api(io.apiman.gateway.engine.beans.Api) HashSet(java.util.HashSet)

Example 4 with IPolicy

use of io.apiman.gateway.engine.policy.IPolicy in project apiman by apiman.

the class ApiResourceImpl method getPolicy.

private void getPolicy(Api api, int policyIdx, String probeConfigRaw, AsyncResponse response) {
    if (policyIdx < api.getApiPolicies().size()) {
        // Get API policy by index
        Policy policyConfig = api.getApiPolicies().get(policyIdx);
        IPolicyFactory policyFactory = getEngine().getPolicyFactory();
        // Load the policy (may not have been loaded yet, but is usually cached).
        policyFactory.loadPolicy(policyConfig.getPolicyImpl(), policyLoad -> {
            // Generate & load appropriate config for policy (is cached, so OK to do repeatedly).
            IPolicy policy = policyLoad.getResult();
            PolicyContextImpl policyContext = new PolicyContextImpl(getEngine().getComponentRegistry());
            ProbeContext probeContext = buildProbeContext(api, null, null, api.getEndpointType());
            // Probe it!
            if (policy instanceof IPolicyProbe) {
                IPolicyProbe<?, ?> policyWithProbe = (IPolicyProbe<?, ?>) policy;
                policyWithProbe.probe(probeConfigRaw, policyConfig.getPolicyJsonConfig(), probeContext, policyContext, probeResult -> {
                    IPolicyProbeResponse probeResponse = probeResult.getResult();
                    LOGGER.debug("Probe response for config {0} -> {1}", probeConfigRaw, probeResponse);
                    response.resume(Response.ok(probeResponse).build());
                });
            } else {
                response.resume(Response.status(Status.NOT_IMPLEMENTED.getStatusCode(), "Requested policy does not implement a policy probe").build());
            }
        });
    } else {
        response.resume(new IllegalArgumentException("Provided policy index out of bounds: " + policyIdx));
    }
}
Also used : IPolicy(io.apiman.gateway.engine.policy.IPolicy) Policy(io.apiman.gateway.engine.beans.Policy) IPolicyProbeResponse(io.apiman.gateway.engine.beans.IPolicyProbeResponse) IPolicy(io.apiman.gateway.engine.policy.IPolicy) ProbeContext(io.apiman.gateway.engine.policy.ProbeContext) IPolicyFactory(io.apiman.gateway.engine.policy.IPolicyFactory) IPolicyProbe(io.apiman.gateway.engine.policy.IPolicyProbe) PolicyContextImpl(io.apiman.gateway.engine.policy.PolicyContextImpl)

Example 5 with IPolicy

use of io.apiman.gateway.engine.policy.IPolicy in project apiman by apiman.

the class ApiResourceImpl method getPolicy.

private void getPolicy(ApiContract contract, int policyIdx, String probeConfigRaw, AsyncResponse response) {
    if (policyIdx < contract.getPolicies().size()) {
        // Get API policy by index
        Policy policyConfig = contract.getPolicies().get(policyIdx);
        IPolicyFactory policyFactory = getEngine().getPolicyFactory();
        // Load the policy (may not have been loaded yet, but is usually cached).
        policyFactory.loadPolicy(policyConfig.getPolicyImpl(), policyLoad -> {
            // Generate & load appropriate config for policy (is cached, so OK to do repeatedly).
            IPolicy policy = policyLoad.getResult();
            PolicyContextImpl policyContext = new PolicyContextImpl(getEngine().getComponentRegistry());
            Api api = contract.getApi();
            Client client = contract.getClient();
            ProbeContext probeContext = buildProbeContext(contract.getApi(), contract, client.getApiKey(), api.getEndpointType());
            // Probe it!
            if (policy instanceof IPolicyProbe) {
                IPolicyProbe<?, ?> policyWithProbe = (IPolicyProbe<?, ?>) policy;
                policyWithProbe.probe(probeConfigRaw, policyConfig.getPolicyJsonConfig(), probeContext, policyContext, probeResult -> {
                    IPolicyProbeResponse probeResponse = probeResult.getResult();
                    LOGGER.debug("Probe response for config {0} -> {1}", probeConfigRaw, probeResponse);
                    response.resume(Response.ok(ProbeRegistry.serialize(probeResponse)).build());
                });
            } else {
                response.resume(Response.status(Status.NOT_IMPLEMENTED.getStatusCode(), "Requested policy does not implement a policy probe").build());
            }
        });
    } else {
        response.resume(new IllegalArgumentException("Provided policy index out of bounds: " + policyIdx));
    }
}
Also used : IPolicy(io.apiman.gateway.engine.policy.IPolicy) Policy(io.apiman.gateway.engine.beans.Policy) IPolicyProbeResponse(io.apiman.gateway.engine.beans.IPolicyProbeResponse) IPolicy(io.apiman.gateway.engine.policy.IPolicy) ProbeContext(io.apiman.gateway.engine.policy.ProbeContext) IPolicyFactory(io.apiman.gateway.engine.policy.IPolicyFactory) IPolicyProbe(io.apiman.gateway.engine.policy.IPolicyProbe) Api(io.apiman.gateway.engine.beans.Api) Client(io.apiman.gateway.engine.beans.Client) PolicyContextImpl(io.apiman.gateway.engine.policy.PolicyContextImpl)

Aggregations

IPolicy (io.apiman.gateway.engine.policy.IPolicy)7 Policy (io.apiman.gateway.engine.beans.Policy)6 IPolicyProbeResponse (io.apiman.gateway.engine.beans.IPolicyProbeResponse)4 IPolicyFactory (io.apiman.gateway.engine.policy.IPolicyFactory)4 IPolicyProbe (io.apiman.gateway.engine.policy.IPolicyProbe)4 PolicyContextImpl (io.apiman.gateway.engine.policy.PolicyContextImpl)4 ProbeContext (io.apiman.gateway.engine.policy.ProbeContext)4 Api (io.apiman.gateway.engine.beans.Api)3 Client (io.apiman.gateway.engine.beans.Client)2 PolicyWithConfiguration (io.apiman.gateway.engine.policy.PolicyWithConfiguration)2 HashSet (java.util.HashSet)2 IAsyncResult (io.apiman.gateway.engine.async.IAsyncResult)1 ApiRequest (io.apiman.gateway.engine.beans.ApiRequest)1 ApiResponse (io.apiman.gateway.engine.beans.ApiResponse)1 ConfigurationParseException (io.apiman.gateway.engine.beans.exceptions.ConfigurationParseException)1 IDataPolicy (io.apiman.gateway.engine.policy.IDataPolicy)1 IPolicyContext (io.apiman.gateway.engine.policy.IPolicyContext)1 RequestChain (io.apiman.gateway.engine.policy.RequestChain)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1