org.shaf.core.process.cmd.CommandLineHandler.java Source code

Java tutorial

Introduction

Here is the source code for org.shaf.core.process.cmd.CommandLineHandler.java

Source

/**
 * Copyright 2014-2015 SHAF-WORK
 * 
 * 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 org.shaf.core.process.cmd;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Properties;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.shaf.core.content.DescriptionContent;
import org.shaf.core.content.FieldInfo;
import org.shaf.core.content.ResourceInfo;
import org.shaf.core.content.SingleOptionInfo;
import org.shaf.core.process.Process;
import org.shaf.core.util.Log;
import org.shaf.core.util.StringUtils;

import com.google.common.base.Strings;
import com.google.common.collect.ObjectArrays;

/**
 * @author Mykola Galushka
 * 
 */
public class CommandLineHandler {

    /**
     * Defines a logger.
     */
    private static final Log LOG = Log.forClass(CommandLineHandler.class);

    /**
     * Returns a {@link Process process} settings containing 'key/value' pairs,
     * where 'key' - name of the process class filed and 'value' - value to
     * which this field need to be set.
     * 
     * @param descr
     *            the process descriptor.
     * @param args
     *            the process arguments.
     * @return the process execution settings.
     * @throws ParseException
     *             if parsing of the command line has failed.
     */
    public final static Properties getSettings(final DescriptionContent descr, final String[] args)
            throws ParseException {

        LOG.trace(Strings.repeat("=", 80));
        LOG.trace("| Block for converting the description content and arguments into");
        LOG.trace("| the settings object.");
        LOG.trace("| Content:   " + descr);
        LOG.trace("| Arguments: " + StringUtils.array2string(args));

        /*
         * Converts the process description into the command line options.
         */
        Options options = CommandOptionHandler.getOptions(descr);

        /*
         * Uses the obtained process options to parse command line arguments.
         */
        CommandLine line = new BasicParser().parse(options, args);

        /*
         * Creates process settings object.
         */
        Properties settings = new Properties();
        for (Object elm : options.getOptions()) {

            LOG.trace(Strings.repeat("-", 80));

            /*
             * Converts a single Option or OptionGroup into array of options.
             * Obviously is we converting a single option array will contain
             * only one element.
             */
            Option[] group = new Option[0];
            if (elm instanceof Option) {
                Option o = (Option) elm;
                group = ObjectArrays.concat(group, o);
            } else {
                OptionGroup og = (OptionGroup) elm;
                for (Object e : og.getOptions()) {
                    Option o = (Option) e;
                    group = ObjectArrays.concat(group, o);
                }
            }

            /*
             * Populates the process execution settings.
             */
            for (Option option : group) {
                LOG.trace("| Select option:   " + option);

                ResourceInfo resInfo = descr.getResourceInfo(option.getOpt());
                SingleOptionInfo optInfo = (SingleOptionInfo) resInfo.getOptionInfo();
                FieldInfo fldInfo = resInfo.getFieldInfo();

                LOG.trace("| Select resource: " + resInfo);

                String fldName = null;
                String fldValue = null;
                if (fldInfo == null) {
                    fldName = optInfo.getName();
                    if (!Strings.isNullOrEmpty(optInfo.getValue())) {
                        fldValue = line.getOptionValue(optInfo.getName(), optInfo.getValue());
                    } else {
                        fldValue = line.getOptionValue(optInfo.getName());
                    }
                } else {
                    fldName = fldInfo.getName();
                    if (boolean.class.getCanonicalName().equals(fldInfo.getType())
                            || Boolean.class.getCanonicalName().equals(fldInfo.getType())) {
                        fldValue = String.valueOf(line.hasOption(optInfo.getName()));
                    } else {
                        if (!Strings.isNullOrEmpty(optInfo.getValue())) {
                            fldValue = line.getOptionValue(optInfo.getName(), optInfo.getValue());
                        } else {
                            fldValue = line.getOptionValue(optInfo.getName());
                        }
                    }
                }

                if (fldValue != null) {
                    settings.put(fldName + ".option", optInfo.getName());
                    LOG.trace("| Set: " + fldName + ".option=" + optInfo.getName());

                    settings.put(fldName + ".value", fldValue);
                    LOG.trace("| Set: " + fldName + ".value=" + fldValue);
                }
            }
        }

        LOG.trace(Strings.repeat("=", 80));

        LOG.debug("Initialized the process settings: " + settings);

        return settings;
    }

    /**
     * Returns the command usage to invoke the specified {@link Process process}
     * .
     * 
     * @param cls
     *            the process class.
     * @return the command usage.
     */
    public final static String getHelp(final Class<? extends Process> cls) {
        // Gets the process description from its class.
        DescriptionContent descr = DescriptionContent.forProcess(cls);

        // Converts the process description into the command line options.
        Options options = CommandOptionHandler.getOptions(descr);

        // Creates the help statement.
        StringWriter writer = new StringWriter();
        new HelpFormatter().printHelp(new PrintWriter(writer), 80, "your.jar", null, options, 7, 2, null, true);

        return writer.toString();
    }
}