All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.sphere.internal.request.QueryRequestMapping Maven / Gradle / Ivy

There is a newer version: 0.72.1
Show newest version
package io.sphere.internal.request;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.sphere.client.QueryRequest;
import io.sphere.client.SortDirection;
import io.sphere.client.model.QueryResult;
import io.sphere.internal.util.Util;

import java.util.List;

/**
 * Converts a {@code QueryRequest} in a {@code QueryRequest}.
 */
public abstract class QueryRequestMapping implements QueryRequest {
    private final QueryRequest delegate;

    protected QueryRequestMapping(QueryRequest delegate) {
        this.delegate = delegate;
    }

    @Override
    public final QueryResult fetch() {
        return Util.sync(fetchAsync());
    }

    @Override
    public ListenableFuture> fetchAsync() {
        return Futures.transform(delegate.fetchAsync(), new Function, QueryResult>() {
            @Override
            public QueryResult apply(QueryResult a) {
                List bList = Lists.transform(a.getResults(), new Function() {
                    @Override
                    public B apply(final A a) {
                        return QueryRequestMapping.this.convert(a);
                    }
                });
                return new QueryResult(a.getOffset(), a.getCount(), a.getTotal(), bList);
            }
        });
    }

    /**
     * Override this method to convert elements from A to B.
     *
     * @param a The single element that should be converted to B.
     * @return The converted a as B.
     */
    protected abstract B convert(A a);

    @Override
    public QueryRequest where(String predicate) {
        delegate.where(predicate);
        return this;
    }

    @Override
    public QueryRequest sort(String fieldName, SortDirection sortDirection) {
        delegate.sort(fieldName, sortDirection);
        return this;
    }

    @Override
    public QueryRequest page(int page) {
        delegate.page(page);
        return this;
    }

    @Override
    public QueryRequest pageSize(int pageSize) {
        delegate.pageSize(pageSize);
        return this;
    }

    @Override
    public QueryRequest expand(String... paths) {
        delegate.expand(paths);
        return this;
    }
}