ren.hankai.cordwood.core.ApplicationInitializer.java Source code

Java tutorial

Introduction

Here is the source code for ren.hankai.cordwood.core.ApplicationInitializer.java

Source

/*******************************************************************************
 * Copyright (C) 2018 hankai
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ******************************************************************************/

package ren.hankai.cordwood.core;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

/**
 * ?????
 *
 * @author hankai
 * @version 1.0.0
 * @since Jun 21, 2016 12:51:54 PM
 */
public class ApplicationInitializer {

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

    /**
     * ??
     *
     * @param supportFileNames ?? support ???
     * @return ??
     * @author hankai
     * @since Jun 21, 2016 12:52:30 PM
     */
    public static boolean initialize(String... supportFileNames) {
        return initialize(true, ApplicationInitInfo.initWithConfigs(supportFileNames));
    }

    /**
     * ??
     *
     * @param printClassPaths ??
     * @param supportFileNames ?? support ???
     * @return ??
     * @author hankai
     * @since Nov 29, 2018 5:42:18 PM
     */
    public static boolean initialize(boolean printClassPaths, String... supportFileNames) {
        return initialize(printClassPaths, ApplicationInitInfo.initWithConfigs(supportFileNames));
    }

    /**
     * ??????
     *
     * @param printClassPaths ??
     * @param appInitInfo ??
     * @return ???
     * @author hankai
     * @since Mar 23, 2018 12:58:24 AM
     */
    public static boolean initialize(boolean printClassPaths, ApplicationInitInfo appInitInfo) {
        if (printClassPaths) {
            printClassPaths();
        }
        boolean success = false;
        logger.info("Initializing application ...");
        success = checkHome();
        if (success) {
            success = checkConfigurations(appInitInfo.getConfigFiles());
            success = checkTemplates(appInitInfo.getTemplates());
        }
        if (success) {
            logger.info("Application initialized successfully.");
        } else {
            logger.error("Application initialization failed.");
        }
        return success;
    }

    /**
     * ??
     *
     * @author hankai
     * @since Oct 13, 2016 9:52:48 AM
     */
    private static void printClassPaths() {
        logger.info("Class paths:");
        final URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
        final URL[] urls = cl.getURLs();
        for (final URL url : urls) {
            logger.info(url.getPath());
        }
    }

    /**
     * ??????????? ???
     *
     * @param fileNames ???
     * @return ?
     * @author hankai
     * @since Jun 21, 2016 12:52:59 PM
     */
    private static boolean checkConfigurations(List<String> fileNames) {
        return checkSupportFiles("/support/", Preferences.getConfigDir(), fileNames);
    }

    /**
     * ????
     *
     * @param fileNames ???
     * @return ?
     * @author hankai
     * @since Aug 13, 2017 12:07:21 PM
     */
    private static boolean checkTemplates(List<String> fileNames) {
        return checkSupportFiles("/support/templates/", Preferences.getConfigDir() + File.separator + "templates",
                fileNames);
    }

    /**
     * ????
     *
     * @param basePath ?
     * @param targetDir ?
     * @param fileNames ???
     * @return ?????
     * @author hankai
     * @since Mar 23, 2018 12:56:15 AM
     */
    private static boolean checkSupportFiles(String basePath, String targetDir, List<String> fileNames) {
        if (fileNames == null) {
            return true;
        }
        InputStream in = null;
        OutputStream out = null;
        try {
            for (final String fileName : fileNames) {
                in = ApplicationInitializer.class.getResourceAsStream(basePath + fileName);
                if (in != null) {
                    final File destFile = new File(targetDir + File.separator + fileName);
                    if (!destFile.exists()) {
                        out = new FileOutputStream(destFile);
                        FileCopyUtils.copy(in, out);
                        logger.info(String.format("Copied support file: %s", fileName));
                    }
                } else {
                    logger.warn(String.format("Missing support file: %s", fileName));
                }
            }
            return true;
        } catch (final IOException ex) {
            logger.error("Error occurred while copying support files.", ex);
            return false;
        } finally {
            if (out != null) {
                IOUtils.closeQuietly(out);
            }
            if (in != null) {
                IOUtils.closeQuietly(in);
            }
        }
    }

    /**
     * ???
     *
     * @return ?
     * @author hankai
     * @since Jun 21, 2016 12:53:23 PM
     */
    private static boolean checkHome() {
        logger.info(String.format("Application home is: \"%s\"", Preferences.getHomeDir()));
        final String[] subDirs = { Preferences.getConfigDir(), Preferences.getDataDir(), Preferences.getCacheDir(),
                Preferences.getLogDir(), Preferences.getTempDir(), Preferences.getAttachmentDir(),
                Preferences.getBackupDir(), Preferences.getDbDir(), Preferences.getPluginsDir(),
                Preferences.getLibsDir(), Preferences.getTemplatesDir() };
        for (final String dir : subDirs) {
            final File file = new File(dir);
            if (!file.exists()) {
                logger.info(String.format("Creating \"%s\"...", dir));
                if (!file.mkdirs()) {
                    logger.error(String.format("Failed to create \"%s\" ...", dir));
                    return false;
                }
            }
        }
        logger.info("Application home directory is fine.");
        return true;
    }
}