Search in sources :

Example 1 with ISignalReadStream

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

the class InMemoryCacheStoreComponent method getBinary.

/**
 * @see io.apiman.gateway.engine.components.ICacheStoreComponent#getBinary(java.lang.String, java.lang.Class, io.apiman.gateway.engine.async.IAsyncResultHandler)
 */
@Override
public <T> void getBinary(String cacheKey, Class<T> type, IAsyncResultHandler<ISignalReadStream<T>> handler) {
    boolean expired = false;
    ISignalReadStream<T> rval;
    Object object;
    IApimanBuffer buffer;
    synchronized (mapMutex) {
        object = objectCache.get(cacheKey);
        if (object != null) {
            Long expiresOn = expireOnMap.get(cacheKey);
            if (System.currentTimeMillis() > expiresOn) {
                expired = true;
            }
        }
        buffer = dataCache.get(cacheKey);
        if (buffer == null) {
            object = null;
        }
    }
    if (object == null) {
        rval = null;
    } else if (expired) {
        synchronized (cacheSizeMutex) {
            synchronized (mapMutex) {
                objectCache.remove(cacheKey);
                expireOnMap.remove(cacheKey);
                dataCache.remove(cacheKey);
                cacheSize -= buffer.length();
            }
        }
        rval = null;
    } else {
        @SuppressWarnings("unchecked") final T head = (T) object;
        final IApimanBuffer data = buffer;
        rval = new ISignalReadStream<T>() {

            IAsyncHandler<IApimanBuffer> bodyHandler;

            IAsyncHandler<Void> endHandler;

            boolean finished = false;

            @Override
            public void bodyHandler(IAsyncHandler<IApimanBuffer> bodyHandler) {
                this.bodyHandler = bodyHandler;
            }

            @Override
            public void endHandler(IAsyncHandler<Void> endHandler) {
                this.endHandler = endHandler;
            }

            @Override
            public T getHead() {
                return head;
            }

            @Override
            public boolean isFinished() {
                return finished;
            }

            @Override
            public void abort(Throwable t) {
                finished = true;
            }

            @Override
            public void transmit() {
                bodyHandler.handle(data);
                endHandler.handle(null);
            }
        };
    }
    handler.handle(AsyncResultImpl.create(rval));
}
Also used : IApimanBuffer(io.apiman.gateway.engine.io.IApimanBuffer) ISignalReadStream(io.apiman.gateway.engine.io.ISignalReadStream) IAsyncHandler(io.apiman.gateway.engine.async.IAsyncHandler)

Example 2 with ISignalReadStream

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

the class CachingPolicy method doApply.

/**
 * If the request is cached an {@link IConnectorInterceptor} is set in order to prevent the back-end connection to be established.
 * Otherwise an empty {@link CachedResponse} will be added to the context, this will be used to cache the response once it has been
 * received from the back-end API
 *
 * @see io.apiman.gateway.engine.policies.AbstractMappedPolicy#doApply(io.apiman.gateway.engine.beans.ApiRequest, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object, io.apiman.gateway.engine.policy.IPolicyChain)
 */
@Deprecated
@Override
protected void doApply(final ApiRequest request, final IPolicyContext context, final CachingConfig config, final IPolicyChain<ApiRequest> chain) {
    if (config.getTtl() > 0) {
        // Check to see if there is a cache entry for this request.  If so, we need to
        // short-circuit the connector factory by providing a connector interceptor
        String cacheId = buildCacheID(request, config);
        context.setAttribute(CACHE_ID_ATTR, cacheId);
        ICacheStoreComponent cache = context.getComponent(ICacheStoreComponent.class);
        cache.getBinary(cacheId, ApiResponse.class, new IAsyncResultHandler<ISignalReadStream<ApiResponse>>() {

            @Override
            public void handle(IAsyncResult<ISignalReadStream<ApiResponse>> result) {
                if (result.isError()) {
                    chain.throwError(result.getError());
                } else {
                    ISignalReadStream<ApiResponse> cacheEntry = result.getResult();
                    if (cacheEntry != null) {
                        context.setConnectorInterceptor(new CacheConnectorInterceptor(cacheEntry));
                        context.setAttribute(SHOULD_CACHE_ATTR, Boolean.FALSE);
                        context.setAttribute(CACHED_RESPONSE, cacheEntry.getHead());
                    } else {
                        context.setAttribute(SHOULD_CACHE_ATTR, Boolean.TRUE);
                    }
                    chain.doApply(request);
                }
            }
        });
    } else {
        context.setAttribute(SHOULD_CACHE_ATTR, Boolean.FALSE);
        chain.doApply(request);
    }
}
Also used : CacheConnectorInterceptor(io.apiman.gateway.engine.policies.caching.CacheConnectorInterceptor) ISignalReadStream(io.apiman.gateway.engine.io.ISignalReadStream) ICacheStoreComponent(io.apiman.gateway.engine.components.ICacheStoreComponent)

Example 3 with ISignalReadStream

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

the class CachingResourcesPolicy method doApply.

/**
 * If the request is cached an {@link IConnectorInterceptor} is set in order to prevent the back-end connection to be established.
 * Otherwise an empty {@link CachedResponse} will be added to the context, this will be used to cache the response once it has been
 * received from the back-end API
 *
 * @see io.apiman.gateway.engine.policies.AbstractMappedPolicy#doApply(io.apiman.gateway.engine.beans.ApiRequest, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object, io.apiman.gateway.engine.policy.IPolicyChain)
 */
@Override
protected void doApply(final ApiRequest request, final IPolicyContext context, final CachingResourcesConfig config, final IPolicyChain<ApiRequest> chain) {
    List<CachingResourcesSettingsEntry> possibleMatchingEntries = new ArrayList<CachingResourcesSettingsEntry>();
    if (config.getTtl() > 0) {
        for (CachingResourcesSettingsEntry entry : config.getCachingResourcesSettingsEntries()) {
            // check if caching policy allows wildcards for http method or path pattern or check if the corresponding policy entry matches the request http method or path pattern.
            if (matchesHttpMethod(entry.getHttpMethod(), request.getType()) && matchesPolicyEntryVsActualValue(entry.getPathPattern(), request.getDestination())) {
                possibleMatchingEntries.add(entry);
            }
        }
        context.setAttribute(CACHE_POSSIBLE_MATCHING_ENTRIES, possibleMatchingEntries);
    }
    if (possibleMatchingEntries.size() > 0) {
        // Check to see if there is a cache entry for this request.
        // If so, we deliver the cached result by CacheConnectorInterceptor
        String cacheId = buildCacheID(request, context);
        context.setAttribute(CACHE_ID_ATTR, cacheId);
        ICacheStoreComponent cache = context.getComponent(ICacheStoreComponent.class);
        cache.getBinary(cacheId, ApiResponse.class, new IAsyncResultHandler<ISignalReadStream<ApiResponse>>() {

            @Override
            public void handle(IAsyncResult<ISignalReadStream<ApiResponse>> result) {
                if (result.isError()) {
                    chain.throwError(result.getError());
                } else {
                    ISignalReadStream<ApiResponse> cacheEntry = result.getResult();
                    if (cacheEntry != null) {
                        markCacheEntryAsCached(cacheEntry, config);
                        context.setConnectorInterceptor(new CacheConnectorInterceptor(cacheEntry));
                        context.setAttribute(SHOULD_CACHE_ATTR, Boolean.FALSE);
                        context.setAttribute(CACHED_RESPONSE, cacheEntry.getHead());
                    } else {
                        context.setAttribute(SHOULD_CACHE_ATTR, Boolean.TRUE);
                    }
                    chain.doApply(request);
                }
            }
        });
    } else {
        context.setAttribute(SHOULD_CACHE_ATTR, Boolean.FALSE);
        chain.doApply(request);
    }
}
Also used : CachingResourcesSettingsEntry(io.apiman.gateway.engine.policies.config.CachingResourcesSettingsEntry) CacheConnectorInterceptor(io.apiman.gateway.engine.policies.caching.CacheConnectorInterceptor) ArrayList(java.util.ArrayList) ISignalReadStream(io.apiman.gateway.engine.io.ISignalReadStream) ICacheStoreComponent(io.apiman.gateway.engine.components.ICacheStoreComponent)

Example 4 with ISignalReadStream

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

the class AbstractCacheStoreComponent method getBinary.

/**
 * @see ICacheStoreComponent#getBinary(String, Class, IAsyncResultHandler)
 */
@Override
public <T> void getBinary(final String cacheKey, final Class<T> type, final IAsyncResultHandler<ISignalReadStream<T>> handler) {
    try {
        final CacheEntry cacheEntry = getStore().get(cacheKey, CacheEntry.class);
        // Did the fetch succeed? If not, return null.
        if (null == cacheEntry) {
            handler.handle(AsyncResultImpl.create((ISignalReadStream<T>) null));
            return;
        }
        // Is the cache entry expired?  If so return null.
        if (System.currentTimeMillis() > cacheEntry.getExpiresOn()) {
            // Cache item has expired.  Return null instead of the cached data.
            handler.handle(AsyncResultImpl.create((ISignalReadStream<T>) null));
            return;
        }
        try {
            @SuppressWarnings("unchecked") final T head = (T) JSON_MAPPER.readValue(cacheEntry.getHead(), type);
            final String b64Data = cacheEntry.getData();
            final IApimanBuffer data = bufferFactory.createBuffer(Base64.decodeBase64(b64Data));
            final ISignalReadStream<T> rval = new ISignalReadStream<T>() {

                IAsyncHandler<IApimanBuffer> bodyHandler;

                IAsyncHandler<Void> endHandler;

                boolean finished = false;

                boolean aborted = false;

                @Override
                public void bodyHandler(IAsyncHandler<IApimanBuffer> bodyHandler) {
                    this.bodyHandler = bodyHandler;
                }

                @Override
                public void endHandler(IAsyncHandler<Void> endHandler) {
                    this.endHandler = endHandler;
                }

                @Override
                public T getHead() {
                    return head;
                }

                @Override
                public boolean isFinished() {
                    return finished;
                }

                @Override
                public void abort(Throwable t) {
                    finished = true;
                    aborted = true;
                }

                @Override
                public void transmit() {
                    if (!aborted) {
                        bodyHandler.handle(data);
                        endHandler.handle(null);
                    }
                    finished = true;
                }
            };
            handler.handle(AsyncResultImpl.create(rval));
        } catch (Throwable e) {
            LOGGER.error("Error reading binary cache entry with key: {}", cacheKey, e);
            handler.handle(AsyncResultImpl.create((ISignalReadStream<T>) null));
        }
    } catch (Throwable e) {
        handler.handle(AsyncResultImpl.create((ISignalReadStream<T>) null));
    }
}
Also used : IApimanBuffer(io.apiman.gateway.engine.io.IApimanBuffer) ISignalReadStream(io.apiman.gateway.engine.io.ISignalReadStream) CacheEntry(io.apiman.gateway.engine.storage.model.CacheEntry) IAsyncHandler(io.apiman.gateway.engine.async.IAsyncHandler)

Example 5 with ISignalReadStream

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

the class EsCacheStoreComponent method getBinary.

/**
 * @see io.apiman.gateway.engine.components.ICacheStoreComponent#getBinary(java.lang.String, java.lang.Class, io.apiman.gateway.engine.async.IAsyncResultHandler)
 */
@Override
public <T> void getBinary(final String cacheKey, final Class<T> type, final IAsyncResultHandler<ISignalReadStream<T>> handler) {
    try {
        GetResponse response = getClient().get(new GetRequest(getFullIndexName()).id(cacheKey), RequestOptions.DEFAULT);
        // Did the GET succeed?  If not, return null.
        if (!response.isExists()) {
            handler.handle(AsyncResultImpl.create((ISignalReadStream<T>) null));
            return;
        }
        // Is the cache entry expired?  If so return null.
        String sourceAsString = response.getSourceAsString();
        CacheEntry cacheEntry = JSON_MAPPER.readValue(sourceAsString, CacheEntry.class);
        if (System.currentTimeMillis() > cacheEntry.getExpiresOn()) {
            // Cache item has expired.  Return null instead of the cached data.
            handler.handle(AsyncResultImpl.create((ISignalReadStream<T>) null));
            return;
        }
        try {
            final T head = (T) JSON_MAPPER.reader(type).readValue(cacheEntry.getHead());
            String b64Data = cacheEntry.getData();
            final IApimanBuffer data = bufferFactory.createBuffer(Base64.decodeBase64(b64Data));
            ISignalReadStream<T> rval = new ISignalReadStream<T>() {

                IAsyncHandler<IApimanBuffer> bodyHandler;

                IAsyncHandler<Void> endHandler;

                boolean finished = false;

                boolean aborted = false;

                @Override
                public void bodyHandler(IAsyncHandler<IApimanBuffer> bodyHandler) {
                    this.bodyHandler = bodyHandler;
                }

                @Override
                public void endHandler(IAsyncHandler<Void> endHandler) {
                    this.endHandler = endHandler;
                }

                @Override
                public T getHead() {
                    return head;
                }

                @Override
                public boolean isFinished() {
                    return finished;
                }

                @Override
                public void abort(Throwable t) {
                    finished = true;
                    aborted = true;
                }

                @Override
                public void transmit() {
                    if (!aborted) {
                        bodyHandler.handle(data);
                        endHandler.handle(null);
                    }
                    finished = true;
                }
            };
            handler.handle(AsyncResultImpl.create(rval));
        } catch (Throwable e) {
            LOGGER.error(e, "Error attempting to stream cached binary on key {0}", cacheKey);
            handler.handle(AsyncResultImpl.create((ISignalReadStream<T>) null));
        }
    } catch (Throwable e) {
        LOGGER.error(e, "Error attempting to GET cached binary on key {0}", cacheKey);
        handler.handle(AsyncResultImpl.create((ISignalReadStream<T>) null));
    }
}
Also used : IApimanBuffer(io.apiman.gateway.engine.io.IApimanBuffer) GetRequest(org.elasticsearch.action.get.GetRequest) ISignalReadStream(io.apiman.gateway.engine.io.ISignalReadStream) CacheEntry(io.apiman.gateway.engine.storage.model.CacheEntry) GetResponse(org.elasticsearch.action.get.GetResponse) IAsyncHandler(io.apiman.gateway.engine.async.IAsyncHandler)

Aggregations

ISignalReadStream (io.apiman.gateway.engine.io.ISignalReadStream)5 IAsyncHandler (io.apiman.gateway.engine.async.IAsyncHandler)3 IApimanBuffer (io.apiman.gateway.engine.io.IApimanBuffer)3 ICacheStoreComponent (io.apiman.gateway.engine.components.ICacheStoreComponent)2 CacheConnectorInterceptor (io.apiman.gateway.engine.policies.caching.CacheConnectorInterceptor)2 CacheEntry (io.apiman.gateway.engine.storage.model.CacheEntry)2 CachingResourcesSettingsEntry (io.apiman.gateway.engine.policies.config.CachingResourcesSettingsEntry)1 ArrayList (java.util.ArrayList)1 GetRequest (org.elasticsearch.action.get.GetRequest)1 GetResponse (org.elasticsearch.action.get.GetResponse)1