org.pau.assetmanager.business.HistoricalStockValuesBusiness.java Source code

Java tutorial

Introduction

Here is the source code for org.pau.assetmanager.business.HistoricalStockValuesBusiness.java

Source

/**
 * This file is part of Pau's Asset Manager Project.
 *
 * Pau's Asset Manager Project is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Pau's Asset Manager Project is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Pau's Asset Manager Project.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.pau.assetmanager.business;

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;

import org.pau.assetmanager.entities.HistoricalStockValue;
import org.pau.assetmanager.viewmodel.stocks.HistoricalStocksValuesDownloader;

import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;

public class HistoricalStockValuesBusiness {

    public static Optional<HistoricalStockValue> getHistoricalValueForSymbolMonthAndYear(String symbol,
            Integer month, Integer year) {
        String query = "select historicalStockValue from HistoricalStockValue historicalStockValue where symbol = :symbol and year = :year and month = :month";
        Optional<HistoricalStockValue> optionalHistoricalStockValue = DaoFunction
                .<HistoricalStockValue>querySimpleUniqueFunction("year", year, "month", month, "symbol", symbol)
                .apply(query);
        return optionalHistoricalStockValue;
    }

    public static Optional<HistoricalStockValue> getHistoricalLastValueForSymbol(String symbol) {
        String query = "select historicalStockValue from HistoricalStockValue historicalStockValue where symbol = :symbol order by year desc, month desc";
        List<HistoricalStockValue> optionalHistoricalStockValue = DaoFunction
                .<HistoricalStockValue>querySimpleListFunction("symbol", symbol).apply(query);
        if (optionalHistoricalStockValue.size() > 0) {
            return Optional.of(optionalHistoricalStockValue.iterator().next());
        } else {
            return Optional.absent();
        }
    }

    public static Optional<Double> converSymbolToEuro(String symbol, Double value) {
        Optional<Double> valueInDollars = Optional.absent();
        if (symbol.contains(".")) {
            // check if the market is supported
            String marketSymbol = symbol.split("\\.")[1];
            for (String pattern : HistoricalStocksValuesDownloader.LABEL_TO_CURRENCY_MAP.keySet()) {
                if (marketSymbol.matches(pattern)) {
                    // supported, we get the change
                    String marketSymbolYahoo = HistoricalStocksValuesDownloader.LABEL_TO_CURRENCY_MAP.get(pattern);
                    Optional<HistoricalStockValue> currencyLastHistoricalValue = getHistoricalLastValueForSymbol(
                            marketSymbolYahoo);
                    if (currencyLastHistoricalValue.isPresent()) {
                        valueInDollars = Optional.of(value / currencyLastHistoricalValue.get().getValue());
                    }
                }
            }
        } else {
            // no market, we assume dollars (American market)
            valueInDollars = Optional.of(value);
        }
        if (valueInDollars.isPresent()) {
            // convert to euros
            Optional<HistoricalStockValue> currencyLastHistoricalValue = getHistoricalLastValueForSymbol(
                    HistoricalStocksValuesDownloader.EURO);
            if (currencyLastHistoricalValue.isPresent()) {
                return Optional.of(valueInDollars.get() * currencyLastHistoricalValue.get().getValue());
            }
        }
        return Optional.absent();
    }

    public static void saveOrUpdate(final String symbol, final Integer year) {
        // collect data from Internet
        final Collection<HistoricalStockValue> historicalValuesInInternet = HistoricalStocksValuesDownloader
                .getHistoricalStockValuesForYear(symbol, year);
        // find the values in the database for the given symbol and year
        String query = "select historicalStockValue from HistoricalStockValue historicalStockValue where year = :year and symbol = :symbol";
        final List<HistoricalStockValue> historicalValuesForSymbolInCurrentYearInDatabase = DaoFunction
                .<HistoricalStockValue>querySimpleListFunction("symbol", symbol, "year", year).apply(query);
        Collection<HistoricalStockValue> historicalValuesInInternetButNotInDatabase = Collections2
                .filter(historicalValuesInInternet, new Predicate<HistoricalStockValue>() {
                    @Override
                    public boolean apply(HistoricalStockValue input) {
                        return !historicalValuesForSymbolInCurrentYearInDatabase.contains(input);
                    }
                });

        // store the values that are not in database
        DaoFunction<Collection<HistoricalStockValue>, Void> saveFunction = new DaoFunction<Collection<HistoricalStockValue>, Void>() {
            @Override
            protected Void doInTransaction(EntityManager entityManager,
                    Collection<HistoricalStockValue> historicalValuesInInternetButNotInDatabase) {
                for (HistoricalStockValue currentHistoricalValuesNotInDatabase : historicalValuesInInternetButNotInDatabase) {
                    entityManager.persist(currentHistoricalValuesNotInDatabase);
                }
                return null;
            }
        };
        saveFunction.apply(historicalValuesInInternetButNotInDatabase);

        for (HistoricalStockValue historicalStockValueInDatabase : historicalValuesForSymbolInCurrentYearInDatabase) {
            for (HistoricalStockValue historicalStockValueInInternet : historicalValuesInInternet) {
                if (historicalStockValueInDatabase.equals(historicalStockValueInInternet)) {
                    historicalStockValueInDatabase
                            .setNumericalValue(historicalStockValueInInternet.getNumericalValue());
                }
            }
        }

        // merge the changes for the values in database
        DaoFunction<Collection<HistoricalStockValue>, Void> updateFunction = new DaoFunction<Collection<HistoricalStockValue>, Void>() {
            @Override
            protected Void doInTransaction(EntityManager entityManager,
                    Collection<HistoricalStockValue> historicalValuesForSymbolInCurrentYearInDatabase) {
                for (HistoricalStockValue currentHistoricalValuesNotInDatabase : historicalValuesForSymbolInCurrentYearInDatabase) {
                    entityManager.merge(currentHistoricalValuesNotInDatabase);
                }
                return null;
            }
        };
        updateFunction.apply(historicalValuesForSymbolInCurrentYearInDatabase);
    }

    public static void removeHistoricalValuesCollectedInTheirMonth() {
        String query = "delete from HistoricalStockValue where collection_date < concat(year,'-',month + 2 ,'-01')";
        DaoFunction.nativeUpdateFunction().apply(query);
    }

}