Search in sources :

Example 1 with ApiResponse

use of io.apiman.gateway.engine.beans.ApiResponse in project apiman-plugins by apiman.

the class JsonpPolicy method getResponseDataHandler.

/**
 * @see io.apiman.gateway.engine.policy.IDataPolicy#getResponseDataHandler(io.apiman.gateway.engine.beans.ApiResponse, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object)
 */
@Override
public IReadWriteStream<ApiResponse> getResponseDataHandler(final ApiResponse response, IPolicyContext context, Object policyConfiguration) {
    final String callbackFunctionName = (String) context.getAttribute(CALLBACK_FUNCTION_NAME, null);
    if (callbackFunctionName != null) {
        HttpHeaders httpHeaders = new HttpHeaders(response.getHeaders());
        final String encoding = httpHeaders.getCharsetFromContentType(StandardCharsets.UTF_8.name());
        final int additionalContentLength = callbackFunctionName.length() + OPEN_PARENTHESES.length() + CLOSE_PARENTHESES.length();
        // JSONP responses should have the Content-Type header set to "application/javascript"
        httpHeaders.setContentType(APPLICATION_JAVASCRIPT);
        // the Content-Length will need to be longer
        httpHeaders.incrementContentLength(additionalContentLength);
        final IBufferFactoryComponent bufferFactory = context.getComponent(IBufferFactoryComponent.class);
        return new AbstractStream<ApiResponse>() {

            private boolean firstChunk = true;

            @Override
            public ApiResponse getHead() {
                return response;
            }

            @Override
            protected void handleHead(ApiResponse head) {
            }

            @Override
            public void write(IApimanBuffer chunk) {
                if (firstChunk) {
                    IApimanBuffer buffer = bufferFactory.createBuffer(callbackFunctionName.length() + OPEN_PARENTHESES.length());
                    try {
                        buffer.append(callbackFunctionName, encoding);
                        buffer.append(OPEN_PARENTHESES, encoding);
                    } catch (UnsupportedEncodingException e) {
                        // TODO Review the exception handling. A better approach might be throwing an IOException.
                        throw new RuntimeException(e);
                    }
                    // Write callbackFunctionName(
                    super.write(buffer);
                    firstChunk = false;
                }
                super.write(chunk);
            }

            @Override
            public void end() {
                // Write close parenth ) on end if something has been written
                if (!firstChunk) {
                    IApimanBuffer buffer = bufferFactory.createBuffer(CLOSE_PARENTHESES.length());
                    try {
                        buffer.append(CLOSE_PARENTHESES, encoding);
                    } catch (UnsupportedEncodingException e) {
                        // TODO Review the exception handling. A better approach might be throwing an IOException.
                        throw new RuntimeException(e);
                    }
                    super.write(buffer);
                }
                super.end();
            }
        };
    }
    return null;
}
Also used : HttpHeaders(io.apiman.plugins.jsonp_policy.http.HttpHeaders) IApimanBuffer(io.apiman.gateway.engine.io.IApimanBuffer) IBufferFactoryComponent(io.apiman.gateway.engine.components.IBufferFactoryComponent) AbstractStream(io.apiman.gateway.engine.io.AbstractStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ApiResponse(io.apiman.gateway.engine.beans.ApiResponse)

Example 2 with ApiResponse

use of io.apiman.gateway.engine.beans.ApiResponse in project apiman-plugins by apiman.

the class TransformationPolicy method getResponseDataHandler.

/**
 * @see io.apiman.gateway.engine.policy.IDataPolicy#getResponseDataHandler(io.apiman.gateway.engine.beans.ApiResponse, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object)
 */
@Override
public IReadWriteStream<ApiResponse> getResponseDataHandler(final ApiResponse response, IPolicyContext context, Object policyConfiguration) {
    final DataFormat clientFormat = (DataFormat) context.getAttribute(CLIENT_FORMAT, null);
    final DataFormat serverFormat = (DataFormat) context.getAttribute(SERVER_FORMAT, null);
    if (isValidTransformation(clientFormat, serverFormat)) {
        final IBufferFactoryComponent bufferFactory = context.getComponent(IBufferFactoryComponent.class);
        final int contentLength = response.getHeaders().containsKey(CONTENT_LENGTH) ? Integer.parseInt(response.getHeaders().get(CONTENT_LENGTH)) : 0;
        return new AbstractStream<ApiResponse>() {

            private IApimanBuffer readBuffer = bufferFactory.createBuffer(contentLength);

            @Override
            public ApiResponse getHead() {
                return response;
            }

            @Override
            protected void handleHead(ApiResponse head) {
            }

            @Override
            public void write(IApimanBuffer chunk) {
                byte[] bytes = chunk.getBytes();
                readBuffer.append(bytes);
            }

            @Override
            public void end() {
                if (readBuffer.length() > 0) {
                    DataTransformer dataTransformer = DataTransformerFactory.getDataTransformer(serverFormat, clientFormat);
                    IApimanBuffer writeBuffer = bufferFactory.createBuffer(readBuffer.length());
                    String data = dataTransformer.transform(new String(readBuffer.getBytes()));
                    writeBuffer.append(data);
                    super.write(writeBuffer);
                }
                super.end();
            }
        };
    }
    return null;
}
Also used : IApimanBuffer(io.apiman.gateway.engine.io.IApimanBuffer) IBufferFactoryComponent(io.apiman.gateway.engine.components.IBufferFactoryComponent) DataTransformer(io.apiman.plugins.transformation_policy.transformer.DataTransformer) DataFormat(io.apiman.plugins.transformation_policy.beans.DataFormat) AbstractStream(io.apiman.gateway.engine.io.AbstractStream) ApiResponse(io.apiman.gateway.engine.beans.ApiResponse)

Example 3 with ApiResponse

use of io.apiman.gateway.engine.beans.ApiResponse in project apiman-plugins by apiman.

the class SimpleHeaderPolicyTest method setup.

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    policy = new SimpleHeaderPolicy();
    config = new SimpleHeaderPolicyDefBean();
    request = new ApiRequest();
    response = new ApiResponse();
}
Also used : ApiRequest(io.apiman.gateway.engine.beans.ApiRequest) SimpleHeaderPolicyDefBean(io.apiman.plugins.simpleheaderpolicy.beans.SimpleHeaderPolicyDefBean) ApiResponse(io.apiman.gateway.engine.beans.ApiResponse) Before(org.junit.Before)

Example 4 with ApiResponse

use of io.apiman.gateway.engine.beans.ApiResponse in project apiman-plugins by apiman.

the class ProduceJsonBackEndApi method invoke.

@Override
public PolicyTestBackEndApiResponse invoke(ApiRequest apiRequest, byte[] requestBody) {
    try {
        String responseBody = "{\"name\":\"apiman\"}";
        ApiResponse apiResponse = new ApiResponse();
        apiResponse.getHeaders().put("Content-Type", "application/json");
        apiResponse.getHeaders().put("Content-Length", String.valueOf(responseBody.getBytes("UTF-8").length));
        return new PolicyTestBackEndApiResponse(apiResponse, responseBody);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
Also used : PolicyTestBackEndApiResponse(io.apiman.test.policies.PolicyTestBackEndApiResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ApiResponse(io.apiman.gateway.engine.beans.ApiResponse) PolicyTestBackEndApiResponse(io.apiman.test.policies.PolicyTestBackEndApiResponse)

Example 5 with ApiResponse

use of io.apiman.gateway.engine.beans.ApiResponse 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)

Aggregations

ApiResponse (io.apiman.gateway.engine.beans.ApiResponse)21 IApimanBuffer (io.apiman.gateway.engine.io.IApimanBuffer)7 ApiRequest (io.apiman.gateway.engine.beans.ApiRequest)5 PolicyTestBackEndApiResponse (io.apiman.test.policies.PolicyTestBackEndApiResponse)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 AbstractStream (io.apiman.gateway.engine.io.AbstractStream)4 ISignalWriteStream (io.apiman.gateway.engine.io.ISignalWriteStream)4 Test (org.junit.Test)4 IPolicyContext (io.apiman.gateway.engine.policy.IPolicyContext)3 IOException (java.io.IOException)3 IApiRequestExecutor (io.apiman.gateway.engine.IApiRequestExecutor)2 IEngine (io.apiman.gateway.engine.IEngine)2 IEngineResult (io.apiman.gateway.engine.IEngineResult)2 IAsyncResultHandler (io.apiman.gateway.engine.async.IAsyncResultHandler)2 ComponentNotFoundException (io.apiman.gateway.engine.beans.exceptions.ComponentNotFoundException)2 IBufferFactoryComponent (io.apiman.gateway.engine.components.IBufferFactoryComponent)2 ICacheStoreComponent (io.apiman.gateway.engine.components.ICacheStoreComponent)2 ByteBuffer (io.apiman.gateway.engine.io.ByteBuffer)2 JsonpConfigBean (io.apiman.plugins.jsonp_policy.beans.JsonpConfigBean)2 IApiConnectionResponse (io.apiman.gateway.engine.IApiConnectionResponse)1