hrytsenko.gscripts.App.java Source code

Java tutorial

Introduction

Here is the source code for hrytsenko.gscripts.App.java

Source

/*
 * #%L
 * gscripts
 * %%
 * Copyright (C) 2015 Anton Hrytsenko
 * %%
 * 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.
 * #L%
 */
package hrytsenko.gscripts;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;

import org.apache.commons.cli.ParseException;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.ImportCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.io.Resources;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import hrytsenko.gscripts.io.CsvFiles;
import hrytsenko.gscripts.io.XlsFiles;

/**
 * Entry point for application.
 * 
 * @author hrytsenko.anton
 */
public final class App {

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

    /**
     * List of embedded scripts.
     *
     * <p>
     * These scripts will be executed in given order prior to user scripts.
     */
    private static final String[] EMBEDDED_SCRIPTS = new String[] { "embedded/IO.groovy" };

    private App() {
    }

    /**
     * Execute scripts with given arguments.
     * 
     * @param args
     *            the command-line arguments
     */
    public static void main(String[] args) {
        try {
            executeScripts(AppArgs.parseArgs(args));
        } catch (ParseException exception) {
            AppArgs.printHelp();
            System.exit(-1);
        } catch (Exception exception) {
            LOGGER.error("Script error.", exception);
            System.exit(-1);
        }

        System.exit(0);
    }

    private static void executeScripts(AppArgs args) {
        GroovyShell shell = createShell(args);

        Arrays.stream(EMBEDDED_SCRIPTS).forEach(script -> executeEmbeddedScript(shell, script));

        args.getScripts().stream().map(Paths::get).forEach(script -> executeCustomScript(shell, script));
    }

    private static void executeEmbeddedScript(GroovyShell shell, String scriptName) {
        try {
            shell.evaluate(Resources.toString(Resources.getResource(scriptName), StandardCharsets.UTF_8));
        } catch (IOException exception) {
            throw new AppException(String.format("Cannot execute embedded script %s.", scriptName), exception);
        }
    }

    private static void executeCustomScript(GroovyShell shell, Path script) {
        Path scriptFilename = script.getFileName();
        LOGGER.info("Execute: {}.", scriptFilename);

        try (BufferedReader reader = Files.newBufferedReader(script, StandardCharsets.UTF_8)) {
            shell.evaluate(reader);
        } catch (IOException exception) {
            throw new AppException(String.format("Cannot execute script %s.", scriptFilename), exception);
        }
    }

    private static GroovyShell createShell(AppArgs args) {
        Binding binding = new Binding(Collections.singletonMap("args", args.getScriptsArgs()));

        ImportCustomizer imports = new ImportCustomizer();
        imports.addStaticStars(CsvFiles.class.getCanonicalName()).addStaticStars(XlsFiles.class.getCanonicalName());

        CompilerConfiguration configuration = new CompilerConfiguration().addCompilationCustomizers(imports);

        return new GroovyShell(binding, configuration);
    }

}