Search in sources :

Example 1 with AbstractStream

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

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

the class TransformationPolicy method getRequestDataHandler.

/**
 * @see io.apiman.gateway.engine.policy.IDataPolicy#getRequestDataHandler(io.apiman.gateway.engine.beans.ApiRequest, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object)
 */
@Override
public IReadWriteStream<ApiRequest> getRequestDataHandler(final ApiRequest request, IPolicyContext context, Object policyConfiguration) {
    final IBufferFactoryComponent bufferFactory = context.getComponent(IBufferFactoryComponent.class);
    final int contentLength = request.getHeaders().containsKey(CONTENT_LENGTH) ? Integer.parseInt(request.getHeaders().get(CONTENT_LENGTH)) : 0;
    return new AbstractStream<ApiRequest>() {

        private IApimanBuffer readBuffer = bufferFactory.createBuffer(contentLength);

        @Override
        public ApiRequest getHead() {
            return request;
        }

        @Override
        protected void handleHead(ApiRequest head) {
        }

        @Override
        public void write(IApimanBuffer chunk) {
            readBuffer.append(chunk.getBytes());
        }

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

Example 3 with AbstractStream

use of io.apiman.gateway.engine.io.AbstractStream 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 4 with AbstractStream

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

the class CachingPolicy method responseDataHandler.

/**
 * @see io.apiman.gateway.engine.policies.AbstractMappedDataPolicy#responseDataHandler(io.apiman.gateway.engine.beans.ApiResponse, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object)
 */
@Deprecated
@Override
protected IReadWriteStream<ApiResponse> responseDataHandler(final ApiResponse response, IPolicyContext context, CachingConfig policyConfiguration) {
    // Possibly cache the response for future posterity.
    // Check the response code against list in config (empty/null list means cache all).
    final boolean shouldCache = (context.getAttribute(SHOULD_CACHE_ATTR, Boolean.FALSE) && ofNullable(policyConfiguration.getStatusCodes()).map(statusCodes -> statusCodes.isEmpty() || statusCodes.contains(String.valueOf(response.getCode()))).orElse(true));
    if (shouldCache) {
        try {
            String cacheId = context.getAttribute(CACHE_ID_ATTR, null);
            ICacheStoreComponent cache = context.getComponent(ICacheStoreComponent.class);
            final ISignalWriteStream writeStream = cache.putBinary(cacheId, response, policyConfiguration.getTtl());
            return new AbstractStream<ApiResponse>() {

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

                @Override
                protected void handleHead(ApiResponse head) {
                }

                @Override
                public void write(IApimanBuffer chunk) {
                    writeStream.write(chunk);
                    super.write(chunk);
                }

                @Override
                public void end() {
                    writeStream.end();
                    super.end();
                }
            };
        } catch (ComponentNotFoundException | IOException e) {
            // TODO log error
            return null;
        }
    } else {
        return null;
    }
}
Also used : IDataPolicy(io.apiman.gateway.engine.policy.IDataPolicy) ISignalReadStream(io.apiman.gateway.engine.io.ISignalReadStream) Optional.ofNullable(java.util.Optional.ofNullable) CacheConnectorInterceptor(io.apiman.gateway.engine.policies.caching.CacheConnectorInterceptor) IOException(java.io.IOException) ApiResponse(io.apiman.gateway.engine.beans.ApiResponse) CachingConfig(io.apiman.gateway.engine.policies.config.CachingConfig) IPolicyChain(io.apiman.gateway.engine.policy.IPolicyChain) ApiRequest(io.apiman.gateway.engine.beans.ApiRequest) IAsyncResult(io.apiman.gateway.engine.async.IAsyncResult) AbstractStream(io.apiman.gateway.engine.io.AbstractStream) IConnectorInterceptor(io.apiman.gateway.engine.policy.IConnectorInterceptor) IAsyncResultHandler(io.apiman.gateway.engine.async.IAsyncResultHandler) IApimanBuffer(io.apiman.gateway.engine.io.IApimanBuffer) ComponentNotFoundException(io.apiman.gateway.engine.beans.exceptions.ComponentNotFoundException) IReadWriteStream(io.apiman.gateway.engine.io.IReadWriteStream) IPolicyContext(io.apiman.gateway.engine.policy.IPolicyContext) ICacheStoreComponent(io.apiman.gateway.engine.components.ICacheStoreComponent) ISignalWriteStream(io.apiman.gateway.engine.io.ISignalWriteStream) CachedResponse(io.apiman.gateway.engine.impl.CachedResponse) IApimanBuffer(io.apiman.gateway.engine.io.IApimanBuffer) ComponentNotFoundException(io.apiman.gateway.engine.beans.exceptions.ComponentNotFoundException) AbstractStream(io.apiman.gateway.engine.io.AbstractStream) IOException(java.io.IOException) ISignalWriteStream(io.apiman.gateway.engine.io.ISignalWriteStream) ICacheStoreComponent(io.apiman.gateway.engine.components.ICacheStoreComponent) ApiResponse(io.apiman.gateway.engine.beans.ApiResponse)

Example 5 with AbstractStream

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

the class CachingResourcesPolicy method responseDataHandler.

/**
 * @see io.apiman.gateway.engine.policies.AbstractMappedDataPolicy#responseDataHandler(io.apiman.gateway.engine.beans.ApiResponse, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object)
 */
@Override
protected IReadWriteStream<ApiResponse> responseDataHandler(final ApiResponse response, IPolicyContext context, CachingResourcesConfig policyConfiguration) {
    if (response == null) {
        // if the response is empty because of a policy failure before we end here and return null
        return null;
    }
    List<CachingResourcesSettingsEntry> possibleMatchingCachingEntries = context.getAttribute(CACHE_POSSIBLE_MATCHING_ENTRIES, new ArrayList<CachingResourcesSettingsEntry>());
    boolean isAMatch = false;
    for (CachingResourcesSettingsEntry entry : possibleMatchingCachingEntries) {
        isAMatch = isAMatch || matchesPolicyEntryVsActualValue(entry.getStatusCode(), String.valueOf(response.getCode()));
    }
    // Possibly cache the response for future posterity.
    final boolean shouldCache = context.getAttribute(SHOULD_CACHE_ATTR, Boolean.FALSE) && isAMatch;
    if (shouldCache) {
        try {
            String cacheId = context.getAttribute(CACHE_ID_ATTR, null);
            ICacheStoreComponent cache = context.getComponent(ICacheStoreComponent.class);
            final ISignalWriteStream writeStream = cache.putBinary(cacheId, response, policyConfiguration.getTtl());
            return new AbstractStream<ApiResponse>() {

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

                @Override
                protected void handleHead(ApiResponse head) {
                }

                @Override
                public void write(IApimanBuffer chunk) {
                    writeStream.write(chunk);
                    super.write(chunk);
                }

                @Override
                public void end() {
                    writeStream.end();
                    super.end();
                }
            };
        } catch (ComponentNotFoundException | IOException e) {
            throw new RuntimeException(e);
        }
    }
    return null;
}
Also used : CachingResourcesSettingsEntry(io.apiman.gateway.engine.policies.config.CachingResourcesSettingsEntry) IApimanBuffer(io.apiman.gateway.engine.io.IApimanBuffer) AbstractStream(io.apiman.gateway.engine.io.AbstractStream) IOException(java.io.IOException) ISignalWriteStream(io.apiman.gateway.engine.io.ISignalWriteStream) ApiResponse(io.apiman.gateway.engine.beans.ApiResponse) ComponentNotFoundException(io.apiman.gateway.engine.beans.exceptions.ComponentNotFoundException) ICacheStoreComponent(io.apiman.gateway.engine.components.ICacheStoreComponent)

Aggregations

AbstractStream (io.apiman.gateway.engine.io.AbstractStream)6 IApimanBuffer (io.apiman.gateway.engine.io.IApimanBuffer)6 ApiResponse (io.apiman.gateway.engine.beans.ApiResponse)4 IBufferFactoryComponent (io.apiman.gateway.engine.components.IBufferFactoryComponent)4 ApiRequest (io.apiman.gateway.engine.beans.ApiRequest)3 ComponentNotFoundException (io.apiman.gateway.engine.beans.exceptions.ComponentNotFoundException)2 ICacheStoreComponent (io.apiman.gateway.engine.components.ICacheStoreComponent)2 ISignalWriteStream (io.apiman.gateway.engine.io.ISignalWriteStream)2 DataFormat (io.apiman.plugins.transformation_policy.beans.DataFormat)2 DataTransformer (io.apiman.plugins.transformation_policy.transformer.DataTransformer)2 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 IAsyncResult (io.apiman.gateway.engine.async.IAsyncResult)1 IAsyncResultHandler (io.apiman.gateway.engine.async.IAsyncResultHandler)1 CachedResponse (io.apiman.gateway.engine.impl.CachedResponse)1 IReadWriteStream (io.apiman.gateway.engine.io.IReadWriteStream)1 ISignalReadStream (io.apiman.gateway.engine.io.ISignalReadStream)1 CacheConnectorInterceptor (io.apiman.gateway.engine.policies.caching.CacheConnectorInterceptor)1 CachingConfig (io.apiman.gateway.engine.policies.config.CachingConfig)1 CachingResourcesSettingsEntry (io.apiman.gateway.engine.policies.config.CachingResourcesSettingsEntry)1