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

com.recombee.api_client.RecombeeClient Maven / Gradle / Ivy

There is a newer version: 4.1.5
Show newest version
package com.recombee.api_client;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;

import org.apache.commons.codec.binary.Hex;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.text.SimpleDateFormat;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import com.recombee.api_client.api_requests.Request;
import com.recombee.api_client.exceptions.ApiException;
import com.recombee.api_client.exceptions.ApiTimeoutException;
import com.recombee.api_client.exceptions.ResponseException;
import com.recombee.api_client.util.NetworkApplicationProtocol;

import com.recombee.api_client.bindings.Recommendation;
import com.recombee.api_client.api_requests.Batch;

/* Start of the generated code */
import com.recombee.api_client.bindings.*;
import com.recombee.api_client.api_requests.GetItemValues;
import com.recombee.api_client.api_requests.ListItems;
import com.recombee.api_client.api_requests.GetItemPropertyInfo;
import com.recombee.api_client.api_requests.ListItemProperties;
import com.recombee.api_client.api_requests.ListSeries;
import com.recombee.api_client.api_requests.ListSeriesItems;
import com.recombee.api_client.api_requests.ListGroups;
import com.recombee.api_client.api_requests.ListGroupItems;
import com.recombee.api_client.api_requests.GetUserValues;
import com.recombee.api_client.api_requests.ListUsers;
import com.recombee.api_client.api_requests.GetUserPropertyInfo;
import com.recombee.api_client.api_requests.ListUserProperties;
import com.recombee.api_client.api_requests.ListItemDetailViews;
import com.recombee.api_client.api_requests.ListUserDetailViews;
import com.recombee.api_client.api_requests.ListItemPurchases;
import com.recombee.api_client.api_requests.ListUserPurchases;
import com.recombee.api_client.api_requests.ListItemRatings;
import com.recombee.api_client.api_requests.ListUserRatings;
import com.recombee.api_client.api_requests.ListItemCartAdditions;
import com.recombee.api_client.api_requests.ListUserCartAdditions;
import com.recombee.api_client.api_requests.ListItemBookmarks;
import com.recombee.api_client.api_requests.ListUserBookmarks;
import com.recombee.api_client.api_requests.ListItemViewPortions;
import com.recombee.api_client.api_requests.ListUserViewPortions;
import com.recombee.api_client.api_requests.RecommendItemsToUser;
import com.recombee.api_client.api_requests.RecommendUsersToUser;
import com.recombee.api_client.api_requests.RecommendItemsToItem;
import com.recombee.api_client.api_requests.RecommendUsersToItem;
import com.recombee.api_client.api_requests.SearchItems;
import com.recombee.api_client.api_requests.UserBasedRecommendation;
import com.recombee.api_client.api_requests.ItemBasedRecommendation;

/* End of the generated code */
/**
* Client for sending requests to Recombee and getting replies
*/
public class RecombeeClient {

    String databaseId;
    String token;

    NetworkApplicationProtocol defaultProtocol = NetworkApplicationProtocol.HTTPS;
    String baseUri = "rapi.recombee.com";
    ObjectMapper mapper;

    final int BATCH_MAX_SIZE = 10000; //Maximal number of requests within one batch request

    final String USER_AGENT = "recombee-java-api-client/3.0.0";

    private final OkHttpClient httpClient = new OkHttpClient();

    public RecombeeClient(String databaseId, String token) {
        this.databaseId = databaseId;
        this.token = token;
        this.mapper = new ObjectMapper();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        this.mapper.setDateFormat(df);

        if (System.getenv("RAPI_URI") != null)
            this.baseUri = System.getenv("RAPI_URI");
    }

    public NetworkApplicationProtocol getDefaultProtocol() {
        return defaultProtocol;
    }

    public RecombeeClient setDefaultProtocol(NetworkApplicationProtocol defaultProtocol) {
        this.defaultProtocol = defaultProtocol;
        return this;
    }
    public RecombeeClient setBaseUri(String baseUri)
    {
        this.baseUri = baseUri;
        return this;
    }
    /* Start of the generated code */
    public PropertyInfo send(GetItemPropertyInfo request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, PropertyInfo.class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public PropertyInfo[] send(ListItemProperties request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, PropertyInfo[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public Series[] send(ListSeries request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, Series[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public SeriesItem[] send(ListSeriesItems request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, SeriesItem[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public Group[] send(ListGroups request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, Group[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public GroupItem[] send(ListGroupItems request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, GroupItem[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public PropertyInfo send(GetUserPropertyInfo request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, PropertyInfo.class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public PropertyInfo[] send(ListUserProperties request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, PropertyInfo[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public DetailView[] send(ListItemDetailViews request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, DetailView[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public DetailView[] send(ListUserDetailViews request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, DetailView[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public Purchase[] send(ListItemPurchases request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, Purchase[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public Purchase[] send(ListUserPurchases request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, Purchase[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public Rating[] send(ListItemRatings request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, Rating[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public Rating[] send(ListUserRatings request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, Rating[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public CartAddition[] send(ListItemCartAdditions request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, CartAddition[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public CartAddition[] send(ListUserCartAdditions request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, CartAddition[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public Bookmark[] send(ListItemBookmarks request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, Bookmark[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public Bookmark[] send(ListUserBookmarks request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, Bookmark[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public ViewPortion[] send(ListItemViewPortions request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, ViewPortion[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public ViewPortion[] send(ListUserViewPortions request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, ViewPortion[].class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public RecommendationResponse send(RecommendItemsToUser request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, RecommendationResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public RecommendationResponse send(RecommendUsersToUser request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, RecommendationResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public RecommendationResponse send(RecommendItemsToItem request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, RecommendationResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public RecommendationResponse send(RecommendUsersToItem request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, RecommendationResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    public SearchResponse send(SearchItems request) throws ApiException {
        String responseStr = sendRequest(request);
        try {
            return this.mapper.readValue(responseStr, SearchResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
         }
         return null;
    }

    /* End of the generated code */

    public BatchResponse[] send(Batch batchRequest) throws ApiException {

        if(batchRequest.getRequests().size() > this.BATCH_MAX_SIZE) {
            return sendMultipartBatchRequest(batchRequest);
        }

        String responseStr = sendRequest(batchRequest);

        try {
            Object[] responses = this.mapper.readValue(responseStr, Object[].class);
            BatchResponse[] result = new BatchResponse[responses.length];
            for(int i=0;i response = (Map) responses[i];
                int status = (Integer) response.get("code");
                Object parsedResponse = response.get("json");
                Request request = batchRequest.getRequests().get(i);

                if(status!=200 && status!=201)
                {
                    Map exceptionMap = (Map) parsedResponse;
                    parsedResponse = new ResponseException(request, status, (String)exceptionMap.get("error"));
                }
                else
                {
                    if ((request instanceof ItemBasedRecommendation) || (request instanceof UserBasedRecommendation))
                    {
                        boolean returnProperties = false;
                        if (request instanceof ItemBasedRecommendation) returnProperties = ((ItemBasedRecommendation) request).getReturnProperties();
                        if (request instanceof UserBasedRecommendation) returnProperties = ((UserBasedRecommendation) request).getReturnProperties();

                        if(returnProperties)
                        {
                            ArrayList> array = (ArrayList>) parsedResponse;
                            Recommendation[] ar = new Recommendation[array.size()];
                            for(int j=0;j array = (ArrayList) parsedResponse;
                            Recommendation[] ar = new Recommendation[array.size()];
                            for(int j=0;j> array = (ArrayList>) parsedResponse;
                            Item[] ar = new Item[array.size()];
                            for(int j=0;j array = (ArrayList) parsedResponse;
                            Item[] ar = new Item[array.size()];
                            for(int j=0;j> array = (ArrayList>) parsedResponse;
                            User[] ar = new User[array.size()];
                            for(int j=0;j array = (ArrayList) parsedResponse;
                            User[] ar = new User[array.size()];
                            for(int j=0;j obj = (Map) parsedResponse;
                        parsedResponse = new PropertyInfo(obj);
                    }

                    else if (request instanceof ListItemProperties)
                    {
                        ArrayList> array = (ArrayList>) parsedResponse;
                        PropertyInfo[] ar = new PropertyInfo[array.size()];
                        for(int j=0;j array = (ArrayList) parsedResponse;
                        Series[] ar = new Series[array.size()];
                        for(int j=0;j> array = (ArrayList>) parsedResponse;
                        SeriesItem[] ar = new SeriesItem[array.size()];
                        for(int j=0;j array = (ArrayList) parsedResponse;
                        Group[] ar = new Group[array.size()];
                        for(int j=0;j> array = (ArrayList>) parsedResponse;
                        GroupItem[] ar = new GroupItem[array.size()];
                        for(int j=0;j obj = (Map) parsedResponse;
                        parsedResponse = new PropertyInfo(obj);
                    }

                    else if (request instanceof ListUserProperties)
                    {
                        ArrayList> array = (ArrayList>) parsedResponse;
                        PropertyInfo[] ar = new PropertyInfo[array.size()];
                        for(int j=0;j> array = (ArrayList>) parsedResponse;
                        DetailView[] ar = new DetailView[array.size()];
                        for(int j=0;j> array = (ArrayList>) parsedResponse;
                        DetailView[] ar = new DetailView[array.size()];
                        for(int j=0;j> array = (ArrayList>) parsedResponse;
                        Purchase[] ar = new Purchase[array.size()];
                        for(int j=0;j> array = (ArrayList>) parsedResponse;
                        Purchase[] ar = new Purchase[array.size()];
                        for(int j=0;j> array = (ArrayList>) parsedResponse;
                        Rating[] ar = new Rating[array.size()];
                        for(int j=0;j> array = (ArrayList>) parsedResponse;
                        Rating[] ar = new Rating[array.size()];
                        for(int j=0;j> array = (ArrayList>) parsedResponse;
                        CartAddition[] ar = new CartAddition[array.size()];
                        for(int j=0;j> array = (ArrayList>) parsedResponse;
                        CartAddition[] ar = new CartAddition[array.size()];
                        for(int j=0;j> array = (ArrayList>) parsedResponse;
                        Bookmark[] ar = new Bookmark[array.size()];
                        for(int j=0;j> array = (ArrayList>) parsedResponse;
                        Bookmark[] ar = new Bookmark[array.size()];
                        for(int j=0;j> array = (ArrayList>) parsedResponse;
                        ViewPortion[] ar = new ViewPortion[array.size()];
                        for(int j=0;j> array = (ArrayList>) parsedResponse;
                        ViewPortion[] ar = new ViewPortion[array.size()];
                        for(int j=0;j> requestChunks = getRequestsChunks(batchRequest);
        ArrayList responses = new ArrayList();

        for(List rqs: requestChunks)
            responses.add(send(new Batch(rqs)));

        return concatenateResponses(responses);
    }

    private List> getRequestsChunks(Batch batchRequest) {

        ArrayList> result = new ArrayList>();
        List requests = batchRequest.getRequests();
        int fullparts = requests.size() / this.BATCH_MAX_SIZE;

        for(int i=0;i responses)
    {
        int size = 0, i = 0;

        for(BatchResponse[] rsps: responses) {
            size += rsps.length;
        }

        BatchResponse[] result = new BatchResponse[size];

        for(BatchResponse[] rsps: responses) {
            for(BatchResponse rsp: rsps)
                result[i++] = rsp;
        }
        return result;
    }    /* End of the generated code */

    public Map send(GetItemValues request) throws ApiException {
        String responseStr = sendRequest(request);

        TypeReference> typeRef 
                = new TypeReference>() {};
        try {
            return this.mapper.readValue(responseStr, typeRef);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public Map send(GetUserValues request) throws ApiException {
        String responseStr = sendRequest(request);

        TypeReference> typeRef 
                = new TypeReference>() {};
        try {
            return this.mapper.readValue(responseStr, typeRef);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public Recommendation[] send(UserBasedRecommendation request) throws ApiException {
        return sendDeprecatedRecomm(request);
    }

    public Recommendation[] send(ItemBasedRecommendation request) throws ApiException {
        return sendDeprecatedRecomm(request);
    }

    protected Recommendation[] sendDeprecatedRecomm(Request request) throws ApiException {
        String responseStr = sendRequest(request);

        try {
            return this.mapper.readValue(responseStr, Recommendation[].class);
        } catch (IOException e) {
            //might have failed because it returned also the item properties
            TypeReference[]> typeRef 
                    = new TypeReference[]>() {};
            try {
                Map[] valsArray = this.mapper.readValue(responseStr, typeRef);
                Recommendation [] recomms = new Recommendation[valsArray.length];
                for(int i=0;i[]> typeRef 
                    = new TypeReference[]>() {};
            try {
                Map[] valsArray = this.mapper.readValue(responseStr, typeRef);
                Item [] recomms = new Item[valsArray.length];
                for(int i=0;i[]> typeRef 
                    = new TypeReference[]>() {};
            try {
                Map[] valsArray = this.mapper.readValue(responseStr, typeRef);
                User [] recomms = new User[valsArray.length];
                for(int i=0;i pair : request.getQueryParameters().entrySet()) {
            uri += uri.contains("?") ? "&" : "?";
            uri += pair.getKey() + "=" + formatQueryParameterValue(pair.getValue());
        }
        return uri;
    }

    private String formatQueryParameterValue(Object val) {
        try {
            return URLEncoder.encode(val.toString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    private okhttp3.Request.Builder put(okhttp3.Request.Builder reqBuilder, Request req) {
        try {
            String json = this.mapper.writeValueAsString(req.getBodyParameters());
            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            reqBuilder.put(RequestBody.create(JSON, json))
            .addHeader("Content-Type", "application/json; charset=utf-8");
            return reqBuilder;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private okhttp3.Request.Builder post(okhttp3.Request.Builder reqBuilder, Request req) {
        try {
            String json = this.mapper.writeValueAsString(req.getBodyParameters());
            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            reqBuilder.post(RequestBody.create(JSON, json))
                    .addHeader("Content-Type", "application/json; charset=utf-8");
            return reqBuilder;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void checkErrors(Response response, Request request) throws ResponseException {
        if(response.code() == 200 || response.code() == 201) return;
        try {
            throw new ResponseException(request, response.code(), response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
            throw new ResponseException(request, response.code(), "Failed to read the error from response");
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy