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

com.github.triceo.robozonky.common.remote.Zonky Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2017 The RoboZonky Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.triceo.robozonky.common.remote;

import java.util.Spliterator;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import com.github.triceo.robozonky.api.remote.ControlApi;
import com.github.triceo.robozonky.api.remote.EntityCollectionApi;
import com.github.triceo.robozonky.api.remote.LoanApi;
import com.github.triceo.robozonky.api.remote.ParticipationApi;
import com.github.triceo.robozonky.api.remote.PortfolioApi;
import com.github.triceo.robozonky.api.remote.WalletApi;
import com.github.triceo.robozonky.api.remote.entities.BlockedAmount;
import com.github.triceo.robozonky.api.remote.entities.Investment;
import com.github.triceo.robozonky.api.remote.entities.Loan;
import com.github.triceo.robozonky.api.remote.entities.Participation;
import com.github.triceo.robozonky.api.remote.entities.PurchaseRequest;
import com.github.triceo.robozonky.api.remote.entities.SellRequest;
import com.github.triceo.robozonky.api.remote.entities.Statistics;
import com.github.triceo.robozonky.api.remote.entities.Wallet;
import com.github.triceo.robozonky.internal.api.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Represents an instance of Zonky API that is fully authenticated and ready to perform operations on behalf of the
 * user. Consider {@link #logout()} when done, followed by {@link #close()}.
 */
public class Zonky implements AutoCloseable {

    private static final Logger LOGGER = LoggerFactory.getLogger(Zonky.class);

    private final Api controlApi;
    private final PaginatedApi loanApi;
    private final PaginatedApi participationApi;
    private final PaginatedApi portfolioApi;
    private final PaginatedApi walletApi;

    Zonky(final Api control, final PaginatedApi loans,
          final PaginatedApi participations,
          final PaginatedApi portfolio,
          final PaginatedApi wallet) {
        if (control == null || loans == null || participations == null || portfolio == null || wallet == null) {
            throw new IllegalArgumentException("No API may be null.");
        }
        this.controlApi = control;
        this.loanApi = loans;
        this.participationApi = participations;
        this.portfolioApi = portfolio;
        this.walletApi = wallet;
    }

    public void invest(final Investment investment) {
        LOGGER.info("Investing into loan #{}.", investment.getLoanId());
        controlApi.execute(api -> {
            api.invest(investment);
        });
    }

    public void cancel(final Investment investment) {
        LOGGER.info("Cancelling offer to sell investment in loan #{}.", investment.getLoanId());
        controlApi.execute(api -> {
            api.cancel(investment.getId());
        });
    }

    public void purchase(final Participation participation) {
        LOGGER.info("Purchasing participation #{} in loan #{}.", participation.getId(), participation.getLoanId());
        controlApi.execute(api -> {
            api.purchase(participation.getId(), new PurchaseRequest(participation));
        });
    }

    public void sell(final Investment investment) {
        LOGGER.info("Offering to sell investment in loan #{}.", investment.getLoanId());
        controlApi.execute(api -> {
            api.offer(new SellRequest(investment));
        });
    }

    public Wallet getWallet() {
        return walletApi.execute(WalletApi::wallet);
    }

    private static > Stream getStream(final PaginatedApi api) {
        return Zonky.getStream(api, Sort.unspecified());
    }

    private static > Stream getStream(final PaginatedApi api,
                                                                             final Sort ordering) {
        return Zonky.getStream(api, Settings.INSTANCE.getDefaultApiPageSize(), ordering);
    }

    private static > Stream getStream(final PaginatedApi api,
                                                                             final int pageSize,
                                                                             final Sort ordering) {
        final Paginated p = new PaginatedImpl<>(api, ordering, pageSize);
        final Spliterator s = new EntitySpliterator<>(p);
        return StreamSupport.stream(s, false);
    }

    /**
     * Retrieve blocked amounts from user's wallet via {@link WalletApi}.
     * @return All items from the remote API, lazy-loaded.
     */
    public Stream getBlockedAmounts() {
        return Zonky.getStream(walletApi);
    }

    public Statistics getStatistics() { // may be null when the user has a fresh Zonky account
        final Statistics s = portfolioApi.execute(PortfolioApi::statistics);
        return (s == null) ? new Statistics() : s;
    }

    /**
     * Retrieve investments from user's portfolio via {@link PortfolioApi}.
     * @return All items from the remote API, lazy-loaded. Does not include investments represented by blocked amounts.
     */
    public Stream getInvestments() {
        return Zonky.getStream(portfolioApi);
    }

    /**
     * Retrieve investments from user's portfolio via {@link PortfolioApi}, in a given order.
     * @param ordering Ordering in which the results should be returned.
     * @return All items from the remote API, lazy-loaded. Does not include investments represented by blocked amounts.
     */
    public Stream getInvestments(final Sort ordering) {
        return Zonky.getStream(portfolioApi, ordering);
    }

    public Loan getLoan(final int id) {
        return loanApi.execute(api -> {
            return api.item(id);
        });
    }

    /**
     * Retrieve loans from marketplace via {@link LoanApi}.
     * @return All items from the remote API, lazy-loaded.
     */
    public Stream getAvailableLoans() {
        return Zonky.getStream(loanApi);
    }

    /**
     * Retrieve participations from secondary marketplace via {@link ParticipationApi}.
     * @return All items from the remote API, lazy-loaded.
     */
    public Stream getAvailableParticipations() {
        return Zonky.getStream(participationApi);
    }

    /**
     * Retrieve loans from marketplace via {@link LoanApi}, in a given order.
     * @param ordering Ordering in which the results should be returned.
     * @return All items from the remote API, lazy-loaded.
     */
    public Stream getAvailableLoans(final Sort ordering) {
        return Zonky.getStream(loanApi, ordering);
    }

    public void logout() {
        controlApi.execute(ControlApi::logout);
    }

    @Override
    public void close() {
        this.controlApi.close();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy