Search in sources :

Example 1 with IAsyncResultHandler

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);
}
Also used : IApimanBuffer(io.apiman.gateway.engine.io.IApimanBuffer) IEngineResult(io.apiman.gateway.engine.IEngineResult) IEngine(io.apiman.gateway.engine.IEngine) IAsyncResultHandler(io.apiman.gateway.engine.async.IAsyncResultHandler) ApiRequest(io.apiman.gateway.engine.beans.ApiRequest) IApiConnectionResponse(io.apiman.gateway.engine.IApiConnectionResponse) ApiResponse(io.apiman.gateway.engine.beans.ApiResponse) RequiredAuthType(io.apiman.gateway.engine.auth.RequiredAuthType) IConnectorFactory(io.apiman.gateway.engine.IConnectorFactory) Client(io.apiman.gateway.engine.beans.Client) IApiRequestExecutor(io.apiman.gateway.engine.IApiRequestExecutor) IPluginRegistry(io.apiman.gateway.engine.IPluginRegistry) InOrder(org.mockito.InOrder) IConnectorConfig(io.apiman.gateway.engine.IConnectorConfig) ISignalWriteStream(io.apiman.gateway.engine.io.ISignalWriteStream) IApiConnector(io.apiman.gateway.engine.IApiConnector) Api(io.apiman.gateway.engine.beans.Api) Contract(io.apiman.gateway.engine.beans.Contract) Test(org.junit.Test)

Example 2 with IAsyncResultHandler

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());
        }
    });
}
Also used : EndpointHelper(io.apiman.gateway.platforms.vertx3.helpers.EndpointHelper) IPolicy(io.apiman.gateway.engine.policy.IPolicy) ApiEndpoint(io.apiman.gateway.engine.beans.ApiEndpoint) VertxEngineConfig(io.apiman.gateway.platforms.vertx3.common.config.VertxEngineConfig) NotAuthorizedException(io.apiman.gateway.api.rest.exceptions.NotAuthorizedException) Client(io.apiman.gateway.engine.beans.Client) IAsyncResultHandler(io.apiman.gateway.engine.async.IAsyncResultHandler) IPolicyProbe(io.apiman.gateway.engine.policy.IPolicyProbe) PublishingException(io.apiman.gateway.engine.beans.exceptions.PublishingException) Status(javax.ws.rs.core.Response.Status) ApimanLoggerFactory(io.apiman.common.logging.ApimanLoggerFactory) ProbeContext(io.apiman.gateway.engine.policy.ProbeContext) IPolicyProbeResponse(io.apiman.gateway.engine.beans.IPolicyProbeResponse) Policy(io.apiman.gateway.engine.beans.Policy) RegistrationException(io.apiman.gateway.engine.beans.exceptions.RegistrationException) IApiResource(io.apiman.gateway.api.rest.IApiResource) AsyncResponse(javax.ws.rs.container.AsyncResponse) PolicyContextImpl(io.apiman.gateway.engine.policy.PolicyContextImpl) ProbeRegistry(io.apiman.gateway.engine.policies.probe.ProbeRegistry) Suspended(javax.ws.rs.container.Suspended) Api(io.apiman.gateway.engine.beans.Api) IApimanLogger(io.apiman.common.logging.IApimanLogger) IEngine(io.apiman.gateway.engine.IEngine) Response(javax.ws.rs.core.Response) IRegistry(io.apiman.gateway.engine.IRegistry) ApiContract(io.apiman.gateway.engine.beans.ApiContract) IPolicyFactory(io.apiman.gateway.engine.policy.IPolicyFactory) Api(io.apiman.gateway.engine.beans.Api)

Example 3 with IAsyncResultHandler

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));
    });
}
Also used : CircuitBreakerOptions(io.vertx.circuitbreaker.CircuitBreakerOptions) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) VertxEngineConfig(io.apiman.gateway.platforms.vertx3.common.config.VertxEngineConfig) CircuitBreaker(io.vertx.circuitbreaker.CircuitBreaker) AsyncResultImpl(io.apiman.gateway.engine.async.AsyncResultImpl) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) IAsyncResultHandler(io.apiman.gateway.engine.async.IAsyncResultHandler) Map(java.util.Map) HttpProxy(io.apiman.gateway.platforms.vertx3.engine.proxy.HttpProxy) JsonObject(io.vertx.core.json.JsonObject) URI(java.net.URI) HttpClientOptions(io.vertx.core.http.HttpClientOptions) ApimanLoggerFactory(io.apiman.common.logging.ApimanLoggerFactory) ProxyOptions(io.vertx.core.net.ProxyOptions) Files(java.nio.file.Files) InheritingHttpClientOptions(io.apiman.gateway.platforms.vertx3.common.config.InheritingHttpClientOptions) Promise(io.vertx.core.Promise) StandardOpenOption(java.nio.file.StandardOpenOption) Vertx(io.vertx.core.Vertx) HttpHeaders(io.vertx.core.http.HttpHeaders) IOException(java.io.IOException) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) SysPropsProxySelector(io.apiman.gateway.platforms.vertx3.engine.proxy.SysPropsProxySelector) Base64(java.util.Base64) IApimanLogger(io.apiman.common.logging.IApimanLogger) BadResponseCodeError(io.apiman.gateway.engine.vertx.polling.exceptions.BadResponseCodeError) Buffer(io.vertx.core.buffer.Buffer) ProxyType(io.vertx.core.net.ProxyType) DefaultPluginRegistry(io.apiman.gateway.engine.impl.DefaultPluginRegistry) Handler(io.vertx.core.Handler) InheritingHttpClientOptionsConverter(io.apiman.gateway.platforms.vertx3.common.config.InheritingHttpClientOptionsConverter) Messages(io.apiman.gateway.platforms.vertx3.i18n.Messages) HttpClient(io.vertx.core.http.HttpClient) CircuitBreaker(io.vertx.circuitbreaker.CircuitBreaker) HttpClient(io.vertx.core.http.HttpClient) CircuitBreakerOptions(io.vertx.circuitbreaker.CircuitBreakerOptions) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) File(java.io.File) HttpClientOptions(io.vertx.core.http.HttpClientOptions) InheritingHttpClientOptions(io.apiman.gateway.platforms.vertx3.common.config.InheritingHttpClientOptions)

Example 4 with IAsyncResultHandler

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);
}
Also used : IJdbcResultSet(io.apiman.gateway.engine.components.jdbc.IJdbcResultSet) IAsyncResultHandler(io.apiman.gateway.engine.async.IAsyncResultHandler) IAsyncResult(io.apiman.gateway.engine.async.IAsyncResult)

Example 5 with IAsyncResultHandler

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));
        }
    }
}
Also used : IAsyncResultHandler(io.apiman.gateway.engine.async.IAsyncResultHandler) LdapResultCode(io.apiman.gateway.engine.components.ldap.result.LdapResultCode) NamingException(javax.naming.NamingException) IAsyncResult(io.apiman.gateway.engine.async.IAsyncResult) LdapException(io.apiman.gateway.engine.components.ldap.result.LdapException)

Aggregations

IAsyncResultHandler (io.apiman.gateway.engine.async.IAsyncResultHandler)12 IAsyncResult (io.apiman.gateway.engine.async.IAsyncResult)6 Api (io.apiman.gateway.engine.beans.Api)4 ApiContract (io.apiman.gateway.engine.beans.ApiContract)4 Client (io.apiman.gateway.engine.beans.Client)4 IRegistry (io.apiman.gateway.engine.IRegistry)3 AsyncResultImpl (io.apiman.gateway.engine.async.AsyncResultImpl)3 Contract (io.apiman.gateway.engine.beans.Contract)3 ApiNotFoundException (io.apiman.gateway.engine.beans.exceptions.ApiNotFoundException)3 Vertx (io.vertx.core.Vertx)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 ApimanLoggerFactory (io.apiman.common.logging.ApimanLoggerFactory)2 IApimanLogger (io.apiman.common.logging.IApimanLogger)2 IApiConnector (io.apiman.gateway.engine.IApiConnector)2 IConnectorConfig (io.apiman.gateway.engine.IConnectorConfig)2 IEngine (io.apiman.gateway.engine.IEngine)2 IEngineConfig (io.apiman.gateway.engine.IEngineConfig)2 IEngineResult (io.apiman.gateway.engine.IEngineResult)2 ApiRequest (io.apiman.gateway.engine.beans.ApiRequest)2