Search in sources :

Example 6 with IAsyncHandler

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

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

Example 8 with IAsyncHandler

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

IAsyncHandler (io.apiman.gateway.engine.async.IAsyncHandler)8 IApimanBuffer (io.apiman.gateway.engine.io.IApimanBuffer)6 IApiRequestExecutor (io.apiman.gateway.engine.IApiRequestExecutor)3 IEngineResult (io.apiman.gateway.engine.IEngineResult)3 ApiRequest (io.apiman.gateway.engine.beans.ApiRequest)3 HashSet (java.util.HashSet)3 List (java.util.List)3 ApiResponse (io.apiman.gateway.engine.beans.ApiResponse)2 PolicyFailure (io.apiman.gateway.engine.beans.PolicyFailure)2 ILdapResult (io.apiman.gateway.engine.components.ldap.ILdapResult)2 ILdapSearchEntry (io.apiman.gateway.engine.components.ldap.ILdapSearchEntry)2 LdapException (io.apiman.gateway.engine.components.ldap.result.LdapException)2 ByteBuffer (io.apiman.gateway.engine.io.ByteBuffer)2 ISignalReadStream (io.apiman.gateway.engine.io.ISignalReadStream)2 ISignalWriteStream (io.apiman.gateway.engine.io.ISignalWriteStream)2 CacheEntry (io.apiman.gateway.engine.storage.model.CacheEntry)2 ApimanStrLookup (io.apiman.common.util.ApimanStrLookup)1 GatewayConfigProperties (io.apiman.gateway.engine.GatewayConfigProperties)1 IApiConnection (io.apiman.gateway.engine.IApiConnection)1 IApiConnectionResponse (io.apiman.gateway.engine.IApiConnectionResponse)1