io.yields.math.framework.kpi.ScoreDAO.java Source code

Java tutorial

Introduction

Here is the source code for io.yields.math.framework.kpi.ScoreDAO.java

Source

/*
 * Copyright 2014 by Yields.
 *
 * 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 io.yields.math.framework.kpi;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JSR310Module;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.stream.Collectors;

import static java.lang.String.format;
import static java.nio.file.Files.list;
import static org.apache.commons.io.FileUtils.forceMkdir;
import static org.apache.commons.io.FileUtils.getTempDirectoryPath;

/**
 * DAO for Score Results.
 */
public class ScoreDAO {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("ddMMyyyyHHmmss");

    private static final String YIELDS_SCORE_PATH = "yields.score.path";

    private static final String FILE_SUFFIX = "yields.json";

    private static final String FOLDER_NAME = "yields";

    private static final Logger logger = LoggerFactory.getLogger(ScoreDAO.class);

    private static File scoreFolder;

    /**
     * Persists a #{ScoreResult}.
     * If a system property yields.score.path is found, this result is written to that location.
     * Otherwise, this result is written to the path defined by the system property java.io.tmpDir.
     *
     * @param scoreResult Score Result to persist
     */
    public static void save(ScoreResult scoreResult) {

        File destinationFolder = getRootFolder();

        if (!destinationFolder.exists()) {
            try {
                forceMkdir(destinationFolder);
            } catch (IOException ioe) {
                throw new IllegalStateException(format("Destination folder for scores could not be created at %s",
                        destinationFolder.getAbsolutePath()), ioe);
            }
        }

        if (!destinationFolder.isDirectory()) {
            throw new IllegalStateException(
                    format("Destination path for scores %s is not a folder", destinationFolder.getAbsolutePath()));
        }

        if (!destinationFolder.canWrite()) {
            throw new IllegalStateException(format("Destination folder for scores %s is not writable",
                    destinationFolder.getAbsolutePath()));
        }

        ObjectMapper jsonMapper = getObjectMapper();
        File destinationFile = new File(destinationFolder, scoreResult.getName().replaceAll("[^a-zA-Z0-9]", "_")
                + "_" + DATE_TIME_FORMATTER.format(LocalDateTime.now()) + "." + FILE_SUFFIX);
        try {
            scoreResult.setTimestamp(ZonedDateTime.now());
            jsonMapper.writeValue(destinationFile, scoreResult);
            logger.info("Written score result to {}", destinationFile.getAbsolutePath());
        } catch (IOException ioe) {
            logger.error("Could not write score result to file " + destinationFile.getAbsolutePath(), ioe);
            throw new IllegalStateException(
                    format("Could not write score file at %s", destinationFile.getAbsolutePath()), ioe);
        }

    }

    private static File getRootFolder() {
        if (scoreFolder == null) {
            File yieldsFolder = new File(System.getProperty(YIELDS_SCORE_PATH, getTempDirectoryPath()),
                    FOLDER_NAME);
            scoreFolder = new File(yieldsFolder, DATE_TIME_FORMATTER.format(LocalDateTime.now()));
        }
        return scoreFolder;
    }

    public static Collection<ScoreResult> retrieve() {
        return retrieve(getRootFolder());
    }

    public static Collection<ScoreResult> retrieve(File path) {

        try {
            return list(path.toPath()).filter(ScoreDAO::isKPIFile).map(ScoreDAO::fromFile)
                    .collect(Collectors.toList());
        } catch (IOException ioe) {
            throw new RuntimeException("Error reading all Yields KPI result from " + path.getAbsolutePath(), ioe);
        }

    }

    private static ScoreResult fromFile(Path file) {

        ObjectMapper jsonMapper = getObjectMapper();
        try {
            return jsonMapper.readValue(file.toFile(), ScoreResult.class);
        } catch (IOException ioe) {
            throw new RuntimeException("Error reading yields KPI file from " + file, ioe);
        }
    }

    private static boolean isKPIFile(Path path) {
        return path.toFile().isFile() && path.toString().endsWith(FILE_SUFFIX);
    }

    private static ObjectMapper getObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JSR310Module());
        return mapper;
    }

}