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