Search in sources :

Example 1 with IApiRequestExecutor

use of io.apiman.gateway.engine.IApiRequestExecutor 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 IApiRequestExecutor

use of io.apiman.gateway.engine.IApiRequestExecutor in project apiman by apiman.

the class GatewayServlet method doAction.

/**
 * Generic handler for all types of http actions/verbs.
 * @param req
 * @param resp
 * @param action
 */
protected void doAction(final HttpServletRequest req, final HttpServletResponse resp, String action) {
    // Read the request.
    ApiRequest srequest;
    try {
        srequest = readRequest(req);
        srequest.setType(action);
    } catch (Exception e) {
        writeError(null, resp, e);
        return;
    }
    final CountDownLatch latch = new CountDownLatch(1);
    final ApiRequest finalRequest = srequest;
    // Now execute the request via the apiman engine
    IApiRequestExecutor executor = getEngine().executor(srequest, new IAsyncResultHandler<IEngineResult>() {

        @Override
        public void handle(IAsyncResult<IEngineResult> asyncResult) {
            if (asyncResult.isSuccess()) {
                IEngineResult engineResult = asyncResult.getResult();
                if (engineResult.isResponse()) {
                    try {
                        writeResponse(resp, engineResult.getApiResponse());
                        final ServletOutputStream outputStream = resp.getOutputStream();
                        engineResult.bodyHandler(new IAsyncHandler<IApimanBuffer>() {

                            @Override
                            public void handle(IApimanBuffer chunk) {
                                try {
                                    if (chunk instanceof ByteBuffer) {
                                        byte[] buffer = (byte[]) chunk.getNativeBuffer();
                                        outputStream.write(buffer, 0, chunk.length());
                                    } else {
                                        outputStream.write(chunk.getBytes());
                                    }
                                } catch (IOException e) {
                                    // connection to the back-end API.
                                    throw new RuntimeException(e);
                                }
                            }
                        });
                        engineResult.endHandler(new IAsyncHandler<Void>() {

                            @Override
                            public void handle(Void result) {
                                try {
                                    resp.flushBuffer();
                                } catch (IOException e) {
                                    // connection to the back-end API.
                                    throw new RuntimeException(e);
                                } finally {
                                    latch.countDown();
                                }
                            }
                        });
                    } catch (IOException e) {
                        // this would mean we couldn't get the output stream from the response, so we
                        // need to abort the engine result (which will let the back-end connection
                        // close down).
                        engineResult.abort(e);
                        latch.countDown();
                        throw new RuntimeException(e);
                    }
                } else {
                    writeFailure(finalRequest, resp, engineResult.getPolicyFailure());
                    latch.countDown();
                }
            } else {
                writeError(finalRequest, resp, asyncResult.getError());
                latch.countDown();
            }
        }
    });
    executor.streamHandler(new IAsyncHandler<ISignalWriteStream>() {

        @Override
        public void handle(ISignalWriteStream connectorStream) {
            try {
                final InputStream is = req.getInputStream();
                ByteBuffer buffer = new ByteBuffer(2048);
                int numBytes = buffer.readFrom(is);
                while (numBytes != -1) {
                    connectorStream.write(buffer);
                    numBytes = buffer.readFrom(is);
                }
                connectorStream.end();
            } catch (Throwable e) {
                connectorStream.abort(e);
            }
        }
    });
    executor.execute();
    try {
        latch.await();
    } catch (InterruptedException e) {
    }
}
Also used : IApimanBuffer(io.apiman.gateway.engine.io.IApimanBuffer) IEngineResult(io.apiman.gateway.engine.IEngineResult) ServletOutputStream(javax.servlet.ServletOutputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ApiRequest(io.apiman.gateway.engine.beans.ApiRequest) CountDownLatch(java.util.concurrent.CountDownLatch) ISignalWriteStream(io.apiman.gateway.engine.io.ISignalWriteStream) ByteBuffer(io.apiman.gateway.engine.io.ByteBuffer) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IAsyncHandler(io.apiman.gateway.engine.async.IAsyncHandler) IApiRequestExecutor(io.apiman.gateway.engine.IApiRequestExecutor)

Example 3 with IApiRequestExecutor

use of io.apiman.gateway.engine.IApiRequestExecutor in project apiman by apiman.

the class ApimanPolicyTest method send.

public PolicyTestResponse send(final PolicyTestRequest ptRequest) throws PolicyFailureError, Throwable {
    final Set<Throwable> errorHolder = new HashSet<>();
    final Set<PolicyFailure> failureHolder = new HashSet<>();
    final Set<ApiResponse> responseHolder = new HashSet<>();
    final StringBuilder responseBody = new StringBuilder();
    IEngine engine = tester.getEngine();
    ApiRequest srequest = tester.createApiRequest();
    // $NON-NLS-1$
    srequest.setUrl("http://localhost:8080" + ptRequest.resource());
    srequest.setDestination(ptRequest.resource());
    srequest.setType(ptRequest.method().name());
    srequest.getHeaders().putAll(ptRequest.headers());
    srequest.getQueryParams().putAll(ptRequest.queryParams());
    IApiRequestExecutor executor = engine.executor(srequest, new IAsyncResultHandler<IEngineResult>() {

        @Override
        public void handle(IAsyncResult<IEngineResult> result) {
            if (result.isError()) {
                errorHolder.add(result.getError());
            } else {
                IEngineResult engineResult = result.getResult();
                if (engineResult.isFailure()) {
                    failureHolder.add(engineResult.getPolicyFailure());
                } else {
                    responseHolder.add(engineResult.getApiResponse());
                    engineResult.bodyHandler(new IAsyncHandler<IApimanBuffer>() {

                        @Override
                        public void handle(IApimanBuffer result) {
                            responseBody.append(new String(result.getBytes()));
                        }
                    });
                    engineResult.endHandler(new IAsyncHandler<Void>() {

                        @Override
                        public void handle(Void result) {
                        }
                    });
                }
            }
        }
    });
    executor.streamHandler(new IAsyncHandler<ISignalWriteStream>() {

        @Override
        public void handle(ISignalWriteStream stream) {
            if (ptRequest.body() != null) {
                ByteBuffer buffer = new ByteBuffer(ptRequest.body());
                stream.write(buffer);
            }
            stream.end();
        }
    });
    // Push any context attributes into the Policy Context.
    IPolicyContext policyContext = getContext(executor);
    Map<String, Object> contextAttributes = ptRequest.contextAttributes();
    for (Entry<String, Object> entry : contextAttributes.entrySet()) {
        policyContext.setAttribute(entry.getKey(), entry.getValue());
    }
    // Execute the request.
    executor.execute();
    if (!errorHolder.isEmpty()) {
        throw errorHolder.iterator().next();
    }
    if (!failureHolder.isEmpty()) {
        throw new PolicyFailureError(failureHolder.iterator().next());
    }
    if (!responseHolder.isEmpty()) {
        ApiResponse response = responseHolder.iterator().next();
        return new PolicyTestResponse(response, responseBody.toString());
    }
    // $NON-NLS-1$
    throw new Exception("No response found from request!");
}
Also used : IApimanBuffer(io.apiman.gateway.engine.io.IApimanBuffer) IEngineResult(io.apiman.gateway.engine.IEngineResult) IEngine(io.apiman.gateway.engine.IEngine) ApiRequest(io.apiman.gateway.engine.beans.ApiRequest) ApiResponse(io.apiman.gateway.engine.beans.ApiResponse) IApiRequestExecutor(io.apiman.gateway.engine.IApiRequestExecutor) HashSet(java.util.HashSet) ISignalWriteStream(io.apiman.gateway.engine.io.ISignalWriteStream) ByteBuffer(io.apiman.gateway.engine.io.ByteBuffer) IPolicyContext(io.apiman.gateway.engine.policy.IPolicyContext) PolicyFailure(io.apiman.gateway.engine.beans.PolicyFailure) IAsyncHandler(io.apiman.gateway.engine.async.IAsyncHandler)

Aggregations

IApiRequestExecutor (io.apiman.gateway.engine.IApiRequestExecutor)3 IEngineResult (io.apiman.gateway.engine.IEngineResult)3 ApiRequest (io.apiman.gateway.engine.beans.ApiRequest)3 IApimanBuffer (io.apiman.gateway.engine.io.IApimanBuffer)3 ISignalWriteStream (io.apiman.gateway.engine.io.ISignalWriteStream)3 IEngine (io.apiman.gateway.engine.IEngine)2 IAsyncHandler (io.apiman.gateway.engine.async.IAsyncHandler)2 ApiResponse (io.apiman.gateway.engine.beans.ApiResponse)2 ByteBuffer (io.apiman.gateway.engine.io.ByteBuffer)2 IApiConnectionResponse (io.apiman.gateway.engine.IApiConnectionResponse)1 IApiConnector (io.apiman.gateway.engine.IApiConnector)1 IConnectorConfig (io.apiman.gateway.engine.IConnectorConfig)1 IConnectorFactory (io.apiman.gateway.engine.IConnectorFactory)1 IPluginRegistry (io.apiman.gateway.engine.IPluginRegistry)1 IAsyncResultHandler (io.apiman.gateway.engine.async.IAsyncResultHandler)1 RequiredAuthType (io.apiman.gateway.engine.auth.RequiredAuthType)1 Api (io.apiman.gateway.engine.beans.Api)1 Client (io.apiman.gateway.engine.beans.Client)1 Contract (io.apiman.gateway.engine.beans.Contract)1 PolicyFailure (io.apiman.gateway.engine.beans.PolicyFailure)1