use of io.apiman.gateway.engine.async.IAsyncResultHandler in project apiman by apiman.
the class DefaultEngineFactoryTest method testCreateEngine.
/**
* Test method for {@link io.apiman.gateway.engine.impl.AbstractEngineFactory#createEngine()}.
* @throws ExecutionException
* @throws InterruptedException
*/
@Test
public void testCreateEngine() throws InterruptedException, ExecutionException {
DefaultEngineFactory factory = new DefaultEngineFactory() {
@Override
protected IComponentRegistry createComponentRegistry(IPluginRegistry pluginRegistry) {
return new DefaultComponentRegistry() {
@Override
protected void registerBufferFactoryComponent() {
addComponent(IBufferFactoryComponent.class, new ByteBufferFactoryComponent());
}
};
}
@Override
protected IConnectorFactory createConnectorFactory(IPluginRegistry pluginRegistry) {
return new IConnectorFactory() {
@Override
public IApiConnector createConnector(ApiRequest request, Api api, RequiredAuthType requiredAuthType, boolean hasDataPolicy, IConnectorConfig connectorConfig) {
Assert.assertEquals("test", api.getEndpointType());
Assert.assertEquals("test:endpoint", api.getEndpoint());
IApiConnector connector = new IApiConnector() {
/**
* @see io.apiman.gateway.engine.IApiConnector#connect(io.apiman.gateway.engine.beans.ApiRequest, io.apiman.gateway.engine.async.IAsyncResultHandler)
*/
@Override
public IApiConnection connect(ApiRequest request, IAsyncResultHandler<IApiConnectionResponse> handler) throws ConnectorException {
final ApiResponse response = new ApiResponse();
response.setCode(200);
// $NON-NLS-1$
response.setMessage("OK");
mockApiConnectionResponse = new MockApiConnectionResponse() {
@Override
public void write(IApimanBuffer chunk) {
handleBody(chunk);
}
@Override
protected void handleHead(ApiResponse head) {
return;
}
@Override
public ApiResponse getHead() {
return response;
}
@Override
public void end() {
handleEnd();
}
@Override
public void transmit() {
transmitHandler.handle((Void) null);
}
@Override
public void abort(Throwable t) {
}
};
IAsyncResult<IApiConnectionResponse> mockResponseResultHandler = mock(IAsyncResult.class);
given(mockResponseResultHandler.isSuccess()).willReturn(true);
given(mockResponseResultHandler.isError()).willReturn(false);
given(mockResponseResultHandler.getResult()).willReturn(mockApiConnectionResponse);
mockApiConnection = mock(MockApiConnection.class);
given(mockApiConnection.getHead()).willReturn(request);
// Handle head
handler.handle(mockResponseResultHandler);
return mockApiConnection;
}
};
return connector;
}
@Override
public IConnectorConfig createConnectorConfig(ApiRequest request, Api api) {
return new TestConnectorConfigImpl();
}
};
}
@Override
protected IDelegateFactory createLoggerFactory(IPluginRegistry pluginRegistry) {
return null;
}
@Override
protected IApiRequestPathParser createRequestPathParser(IPluginRegistry pluginRegistry) {
return new DefaultRequestPathParser(null);
}
@Override
protected void complete() {
}
};
IEngine engine = factory.createEngine();
Assert.assertNotNull(engine);
// create a api
Api api = new Api();
api.setEndpointType("test");
api.setEndpoint("test:endpoint");
api.setOrganizationId("TestOrg");
api.setApiId("TestApi");
api.setVersion("1.0");
// create a client
Client app = new Client();
app.setClientId("TestApp");
app.setOrganizationId("TestOrg");
app.setVersion("1.0");
app.setApiKey("client-12345");
Contract contract = new Contract();
contract.setPlan("Gold");
contract.setApiId("TestApi");
contract.setApiOrgId("TestOrg");
contract.setApiVersion("1.0");
contract.setPolicies(policyList);
app.addContract(contract);
// simple api/app config
engine.getRegistry().publishApi(api, new IAsyncResultHandler<Void>() {
@Override
public void handle(IAsyncResult<Void> result) {
}
});
engine.getRegistry().registerClient(app, new IAsyncResultHandler<Void>() {
@Override
public void handle(IAsyncResult<Void> result) {
}
});
ApiRequest request = new ApiRequest();
request.setApiKey("client-12345");
request.setApiId("TestApi");
request.setApiOrgId("TestOrg");
request.setApiVersion("1.0");
request.setDestination("/");
request.setUrl("http://localhost:9999/");
request.setType("TEST");
IApiRequestExecutor prExecutor = engine.executor(request, new IAsyncResultHandler<IEngineResult>() {
// At this point, we are either saying *fail* or *response connection is ready*
@Override
public void handle(IAsyncResult<IEngineResult> result) {
IEngineResult er = result.getResult();
// No exception occurred
Assert.assertTrue(result.isSuccess());
// The chain evaluation succeeded
Assert.assertNotNull(er);
Assert.assertTrue(!er.isFailure());
Assert.assertNotNull(er.getApiResponse());
// $NON-NLS-1$
Assert.assertEquals("OK", er.getApiResponse().getMessage());
er.bodyHandler(mockBodyHandler);
er.endHandler(mockEndHandler);
}
});
prExecutor.streamHandler(new IAsyncHandler<ISignalWriteStream>() {
@Override
public void handle(ISignalWriteStream streamWriter) {
streamWriter.write(mockBufferInbound);
streamWriter.end();
}
});
transmitHandler = new IAsyncHandler<Void>() {
@Override
public void handle(Void result) {
// NB: This is cheating slightly for testing purposes, we don't have real async here.
// Only now start writing stuff, so user has had opportunity to set handlers
mockApiConnectionResponse.write(mockBufferOutbound);
mockApiConnectionResponse.end();
}
};
prExecutor.execute();
// Request handler should receive the mock inbound buffer once only
verify(mockApiConnection, times(1)).write(mockBufferInbound);
// Ultimately user should receive the contrived response and end in order.
InOrder order = inOrder(mockBodyHandler, mockEndHandler);
order.verify(mockBodyHandler).handle(mockBufferOutbound);
order.verify(mockEndHandler).handle((Void) null);
}
use of io.apiman.gateway.engine.async.IAsyncResultHandler in project apiman by apiman.
the class ApiResourceImpl method retire.
@Override
public void retire(String organizationId, String apiId, String version) throws RegistrationException, NotAuthorizedException {
Api api = new Api();
api.setOrganizationId(organizationId);
api.setApiId(apiId);
api.setVersion(version);
registry.retireApi(api, (IAsyncResultHandler<Void>) result -> {
if (result.isError()) {
throwError(result.getError());
}
});
}
use of io.apiman.gateway.engine.async.IAsyncResultHandler in project apiman by apiman.
the class VertxPluginRegistry method downloadArtifactTo.
/**
* @see io.apiman.gateway.engine.impl.DefaultPluginRegistry#downloadArtifactTo(java.net.URL, java.io.File,
* io.apiman.gateway.engine.async.IAsyncResultHandler)
*/
@Override
protected void downloadArtifactTo(final URL artifactUrl, final File pluginFile, final IAsyncResultHandler<File> handler) {
URI artifactUri;
try {
artifactUri = artifactUrl.toURI();
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
int port = artifactUrl.getPort();
boolean isTls = false;
// Configure http client options following artifact url
if (artifactUrl.getProtocol().equalsIgnoreCase("https")) {
// If port is not defined, set to https default port 443
if (port == -1)
port = 443;
isTls = true;
} else {
// If port is not defined, set to http default port 80
if (port == -1)
port = 80;
}
HttpClientOptions options = createVertxClientOptions(artifactUri, isTls);
LOG.trace("Will attempt to download artifact {0} using options {1} to {2}", artifactUrl, options, pluginFile);
HttpClient client = vertx.createHttpClient(options);
CircuitBreaker breaker = CircuitBreaker.create("download-plugin-circuit-breaker", vertx, new CircuitBreakerOptions().setMaxFailures(// number of failure before opening the circuit
2).setTimeout(// consider a failure if the operation does not succeed in time
20000).setResetTimeout(// time spent in open state before attempting to re-try
10000)).retryPolicy(// Increase backoff on each retry
retryCount -> retryCount * 10L);
int finalPort = port;
breaker.<File>execute(promise -> {
LOG.info("Will attempt to download plugin from: {0}", artifactUrl);
tryDownloadingArtifact(client, finalPort, artifactUrl, pluginFile, promise);
}).onSuccess(file -> {
LOG.debug("Successfully downloaded plugin artifact: {0}", artifactUrl);
handler.handle(AsyncResultImpl.create(pluginFile));
}).onFailure(failure -> {
LOG.error("Failed to downloaded plugin artifact", failure);
handler.handle(AsyncResultImpl.create(failure));
});
}
use of io.apiman.gateway.engine.async.IAsyncResultHandler in project apiman by apiman.
the class JDBCIdentityValidator method validate.
/**
* @param connection
* @param query
* @param username
* @param context
* @param password
* @param config
* @param handler
*/
protected void validate(final IJdbcConnection connection, final String query, final String username, final String password, final IPolicyContext context, final JDBCIdentitySource config, final IAsyncResultHandler<Boolean> handler) {
IAsyncResultHandler<IJdbcResultSet> queryHandler = new IAsyncResultHandler<IJdbcResultSet>() {
@Override
public void handle(IAsyncResult<IJdbcResultSet> result) {
if (result.isError()) {
closeQuietly(connection);
handler.handle(AsyncResultImpl.create(result.getError(), Boolean.class));
} else {
boolean validated = false;
IJdbcResultSet resultSet = result.getResult();
if (resultSet.next()) {
validated = true;
}
resultSet.close();
if (validated && config.isExtractRoles()) {
extractRoles(connection, username, context, config, handler);
} else {
closeQuietly(connection);
handler.handle(AsyncResultImpl.create(validated));
}
}
}
};
connection.query(queryHandler, query, username, password);
}
use of io.apiman.gateway.engine.async.IAsyncResultHandler in project apiman by apiman.
the class LDAPIdentityValidator method handleLdapSearch.
private void handleLdapSearch(final ILdapClientConnection connection, List<ILdapSearchEntry> searchEntries, LDAPIdentitySource config, LdapConfigBean ldapConfigBean, ILdapComponent ldapComponent, IPolicyContext context, String username, String password, final IAsyncResultHandler<Boolean> handler) {
if (searchEntries.size() > 1) {
// $NON-NLS-1$
NamingException ex = new NamingException("Found multiple entries for the same username: " + username);
handler.handle(AsyncResultImpl.<Boolean>create(ex));
} else if (searchEntries.isEmpty()) {
handler.handle(AsyncResultImpl.create(Boolean.FALSE));
} else {
// Just one result
// First entry
String userDn = searchEntries.get(0).getDn();
if (userDn != null) {
ldapConfigBean.setBindDn(userDn);
ldapConfigBean.setBindPassword(password);
bind(config, ldapConfigBean, ldapComponent, context, new IAsyncResultHandler<ILdapResult>() {
@Override
public void handle(IAsyncResult<ILdapResult> result) {
if (result.isError()) {
if (result.getError() instanceof LdapException) {
LdapException ex = (LdapException) result.getError();
if (ex.getResultCode().isAuthFailure()) {
handler.handle(AsyncResultImpl.create(Boolean.FALSE));
} else {
handler.handle(AsyncResultImpl.<Boolean>create(ex));
}
connection.close(ex);
} else {
handler.handle(AsyncResultImpl.<Boolean>create(result.getError()));
connection.close();
}
} else {
LdapResultCode resultCode = result.getResult().getResultCode();
if (LdapResultCode.isSuccess(resultCode)) {
handler.handle(AsyncResultImpl.create(Boolean.TRUE));
} else {
// TODO handle errors better?
handler.handle(AsyncResultImpl.create(Boolean.FALSE));
}
connection.close();
}
}
});
} else {
handler.handle(AsyncResultImpl.create(Boolean.FALSE));
}
}
}
Aggregations