com.crosstreelabs.cognitio.common.CustomCommander.java Source code

Java tutorial

Introduction

Here is the source code for com.crosstreelabs.cognitio.common.CustomCommander.java

Source

/*
 * Copyright 2015 Crosstree Labs.
 *
 * 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 com.crosstreelabs.cognitio.common;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterDescription;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.Strings;
import com.beust.jcommander.WrappedParameter;
import com.beust.jcommander.internal.Lists;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.lang3.text.WordUtils;
import org.reflections.Reflections;

public class CustomCommander extends JCommander {

    public CustomCommander() {
    }

    public CustomCommander(Object object) {
        super(object);
    }

    @Override
    public void usage(StringBuilder out, String indent) {
        Map<String, ParameterDescription> parameters = new HashMap<>();
        for (ParameterDescription pd : getParameters()) {
            parameters.put(pd.getParameterized().getName(), pd);
        }

        //
        // First line of the usage
        //
        String programName = "<main class>";
        out.append(indent).append("Usage: ").append(programName).append(" [options]");
        if (!getCommands().isEmpty()) {
            out.append(indent).append(" [command] [command options]");
        }
        out.append("\n");

        //
        // Display all the names and descriptions
        //
        for (Object obj : getObjects()) {
            int i = 0;
            for (Field field : obj.getClass().getDeclaredFields()) {
                if (!field.isAnnotationPresent(Parameter.class)) {
                    continue;
                }

                if (i == 0) {
                    String name = obj.getClass().getSimpleName();
                    if (name.toLowerCase().endsWith("configuration")) {
                        name = name.substring(0, name.length() - 13);
                    }
                    out.append(indent).append("\n  " + name + " Options:\n");
                }

                ParameterDescription pd = parameters.get(field.getName());
                WrappedParameter parameter = pd.getParameter();

                StringBuilder description = new StringBuilder(pd.getNames()).append(" ")
                        .append(parameter.required() ? "(REQUIRED)" : "").append("\n");
                wrapDescription(description, pd.getDescription());

                Object def = pd.getDefault();
                if (pd.isDynamicParameter()) {
                    description.append("\n            ").append(
                            "Syntax: " + parameter.names()[0] + "key" + parameter.getAssignment() + "value");
                }
                if (def != null) {
                    String displayedDef = Strings.isStringEmpty(def.toString()) ? "<empty string>" : def.toString();
                    description.append("\n            ")
                            .append("Default: " + (parameter.password() ? "********" : displayedDef));
                }
                description.append("\n");
                out.append(description);
                i++;
            }
        }
    }

    private void wrapDescription(StringBuilder out, String description) {
        final int INDENT = 12;

        int offset = 0;
        int strLen = description.length();

        int maxLineLength = getColumnSize() - INDENT;
        while (offset <= strLen) {
            if (strLen < offset + getColumnSize() - INDENT) {
                out.append(new String(new char[INDENT]).replace("\0", " ")).append(description.substring(offset));
                break;
            }

            String line = description.substring(offset,
                    description.lastIndexOf(" ", Math.min(offset + maxLineLength, strLen)));
            out.append(new String(new char[INDENT]).replace("\0", " ")).append(line.trim()).append("\n");
            offset += INDENT + line.length();
        }
    }
}