net.alegen.datpass.cli.input.ProfileCommand.java Source code

Java tutorial

Introduction

Here is the source code for net.alegen.datpass.cli.input.ProfileCommand.java

Source

/*
 * DatpassCLI - command line utility for generating passwords
 * Copyright (C) 2013 - 2014 Alexandru Geana (alegen)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package net.alegen.datpass.cli.input;

import net.alegen.datpass.cli.Application;
import net.alegen.datpass.cli.utils.Settings;
import net.alegen.datpass.library.Generator;
import net.alegen.datpass.library.Profile;
import net.alegen.datpass.library.configure.Configurator;
import net.alegen.datpass.library.configure.FieldManager;
import org.apache.commons.cli.*;

import java.util.List;
import java.util.Map;

public class ProfileCommand extends Command {

    private static final String OPTION_LIST = "l";
    private static final String OPTION_LIST_LONG = "list";
    private static final String OPTION_CREATE = "c";
    private static final String OPTION_CREATE_LONG = "create";
    private static final String OPTION_REMOVE = "r";
    private static final String OPTION_REMOVE_LONG = "remove";
    private static final String OPTION_UNLOCK = "unlock";
    private static final String OPTION_UNLOCK_LONG = "u";
    private static final String OPTION_ENCRYPTED = "e";
    private static final String OPTION_ENCRYPTED_LONG = "encrypted";

    protected ProfileCommand() {
        this.options = new Options();
        Option list = OptionBuilder.withDescription("list all existing profiles").withLongOpt(OPTION_LIST_LONG)
                .create(OPTION_LIST);
        Option create = OptionBuilder.withDescription("create a new profile").withLongOpt(OPTION_CREATE_LONG)
                .create(OPTION_CREATE);
        Option remove = OptionBuilder.hasArg().withArgName("name")
                .withDescription("remove an existing profile with the given name").withLongOpt(OPTION_REMOVE_LONG)
                .create(OPTION_REMOVE);
        Option unlock = OptionBuilder.hasArg().withArgName("name")
                .withDescription("unlock and load an existing profile with the given name")
                .withLongOpt(OPTION_UNLOCK_LONG).create(OPTION_UNLOCK);
        Option encrypted = OptionBuilder.withDescription("unlock and load an existing profile with the given name")
                .withLongOpt(OPTION_ENCRYPTED_LONG).create(OPTION_ENCRYPTED);
        this.options.addOption(list);
        this.options.addOption(create);
        this.options.addOption(remove);
        this.options.addOption(unlock);
        this.options.addOption(encrypted);
    }

    @Override
    public void execute() {
        try {
            Configurator configurator = Settings.getConfigurator();
            CommandLineParser parser = new PosixParser();
            String[] arrayArgs = new String[this.args.size()];
            this.args.toArray(arrayArgs);
            CommandLine line = parser.parse(this.options, arrayArgs);
            if (line.getOptions().length == 0) {
                Profile profile = Generator.getInstance().getCurrentProfile();
                if (profile == null)
                    System.out.println("No profile is currently in use.");
                else
                    System.out.println("Current profile: " + profile.getValue(FieldManager.NAME_FIELD));
            } else if (line.hasOption(OPTION_LIST)) {
                Map<String, Boolean> profiles = configurator.listProfiles();
                if (profiles.size() > 0) {
                    System.out.println("Available profiles:");
                    for (Map.Entry<String, Boolean> entry : profiles.entrySet()) {
                        if (entry.getValue())
                            System.out.println("* " + entry.getKey() + "\t[encrypted]");
                        else
                            System.out.println("* " + entry.getKey());
                    }
                } else
                    System.out.println("There are no available profiles.");
            } else if (line.hasOption(OPTION_CREATE)) {
                Profile profile = new Profile();
                for (FieldManager.Field field : FieldManager.getInstance()) {
                    boolean valid = false;
                    while (!valid) {
                        String question = field.getDescription();
                        if (field.getDefaultValue() != null || field.isMandatory()) {
                            question += " ( ";
                            if (field.getDefaultValue() != null && !field.getDefaultValue().isEmpty()) {
                                if (field.isMandatory()) {
                                    question += "default: " + field.getDefaultValue() + ", mandatory";
                                } else {
                                    question += "default: " + field.getDefaultValue();
                                }
                            } else {
                                question += "mandatory";
                            }
                            question += " )";
                        }
                        question += ": ";
                        System.out.print(question);
                        String answer = System.console().readLine();
                        if (answer.isEmpty()) {
                            if (field.isMandatory()) {
                                if (field.getDefaultValue() != null && !field.getDefaultValue().isEmpty()) {
                                    profile.setValue(field, field.getDefaultValue());
                                    System.out.println("Field set to default value.");
                                    valid = true;
                                } else
                                    System.out.println(
                                            "This field is mandatory and a default value is not available.\nPlease provide a value for it.");
                            } else
                                valid = true;
                        } else {
                            profile.setValue(field, answer);
                            valid = true;
                        }
                    }
                }
                if (line.hasOption(OPTION_ENCRYPTED)) {
                    String password1 = "password1";
                    String password2 = "password2";
                    while (!password1.equals(password2)) {
                        System.out.print("Password: ");
                        password1 = String.valueOf(System.console().readPassword());
                        System.out.print("Retype password: ");
                        password2 = String.valueOf(System.console().readPassword());
                        if (!password1.equals(password2))
                            System.out.println("The two passwords do not match. Please try again.");
                    }
                    configurator.saveProfile(profile, password1);
                    configurator.saveConfig();
                } else {
                    configurator.saveProfile(profile);
                    configurator.saveConfig();
                }
            } else if (line.hasOption(OPTION_UNLOCK)) {
                String name = line.getOptionValue(OPTION_UNLOCK);
                boolean isEncrypted = false;
                Map<String, Boolean> profiles = configurator.listProfiles();
                for (Map.Entry<String, Boolean> entry : profiles.entrySet())
                    if (entry.getKey().equals(name)) {
                        isEncrypted = entry.getValue();
                        break;
                    }
                Profile profile = null;
                if (isEncrypted) {
                    System.out.print("Password: ");
                    String password = String.valueOf(System.console().readPassword());
                    profile = configurator.loadProfile(name, password);
                } else
                    profile = configurator.loadProfile(name, "");
                Generator.getInstance().setCurrentProfile(profile);
            } else if (line.hasOption(OPTION_REMOVE)) {
                String name = line.getOptionValue(OPTION_REMOVE);
                configurator.removeProfile(name);
                configurator.saveConfig();
            }
        } catch (ParseException e) {

        } catch (Configurator.ConfigurationException e) {

        } catch (Profile.InvalidProfileException e) {

        }
    }

    private boolean isInteger(String value) {
        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException ex) {
            return false;
        }
    }
}