Example usage for java.util Properties load

List of usage examples for java.util Properties load

Introduction

In this page you can find the example usage for java.util Properties load.

Prototype

public synchronized void load(InputStream inStream) throws IOException 

Source Link

Document

Reads a property list (key and element pairs) from the input byte stream.

Usage

From source file:fi.hoski.remote.ui.Admin.java

/**
 * @param args the command line arguments
 *///w w  w  .  ja  va  2s  . c  om
public static void main(String[] args) {
    try {
        Properties properties = new Properties();
        if (args.length != 0) {
            try (InputStream pFile = new FileInputStream(args[0])) {
                properties.load(pFile);
            } catch (FileNotFoundException ex) {

            }
        }
        ServerProperties sp = new ServerProperties(properties);
        DataObjectDialog<ServerProperties> dod = new DataObjectDialog<>(null, sp.getModel().hide(
                ServerProperties.Tables, ServerProperties.SupportsZonerSMS, ServerProperties.SuperUser), sp);
        if (dod.edit()) {
            String[] server = sp.getServer().split(",");
            RemoteAppEngine.init(server[0], sp.getUsername(), sp.getPassword());
            DataStoreProxy dsp = new DataStoreProxy(properties);
            dsp.start();
            Admin r = new Admin(sp);
        } else {
            System.exit(0);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, ex.getMessage());
    }
}

From source file:me.mast3rplan.phantombot.PhantomBot.java

public static void main(String[] args) throws IOException {
    /* List of properties that must exist. */
    String requiredProperties[] = new String[] { "oauth", "channel", "owner", "user" };
    String requiredPropertiesErrorMessage = "";

    /* Properties configuration */
    Properties startProperties = new Properties();

    /* Indicates that the botlogin.txt file should be overwritten/created. */
    Boolean changed = false;/* ww  w  .jav a 2  s  .co m*/

    /* Print the user dir */
    com.gmt2001.Console.out.println("The working directory is: " + System.getProperty("user.dir"));

    /* Load up the bot info from the bot login file */
    try {
        if (new File("./botlogin.txt").exists()) {
            try {
                FileInputStream inputStream = new FileInputStream("botlogin.txt");
                startProperties.load(inputStream);
                inputStream.close();

                if (startProperties.getProperty("debugon", "false").equals("true")) {
                    com.gmt2001.Console.out.println("Debug Mode Enabled via botlogin.txt");
                    PhantomBot.enableDebugging = true;
                }

                if (startProperties.getProperty("debuglog", "false").equals("true")) {
                    com.gmt2001.Console.out.println("Debug Log Only Mode Enabled via botlogin.txt");
                    PhantomBot.enableDebugging = true;
                    PhantomBot.enableDebuggingLogOnly = true;
                }

                if (startProperties.getProperty("reloadscripts", "false").equals("true")) {
                    com.gmt2001.Console.out.println("Enabling Script Reloading");
                    PhantomBot.reloadScripts = true;
                }
                if (startProperties.getProperty("rhinodebugger", "false").equals("true")) {
                    com.gmt2001.Console.out.println("Rhino Debugger will be launched if system supports it.");
                    PhantomBot.enableRhinoDebugger = true;
                }
            } catch (IOException ex) {
                com.gmt2001.Console.err.printStackTrace(ex);
            }
        } else {

            /* Fill in the Properties object with some default values. Note that some values are left 
             * unset to be caught in the upcoming logic to enforce settings.
             */
            startProperties.setProperty("baseport", "25000");
            startProperties.setProperty("usehttps", "false");
            startProperties.setProperty("webenable", "true");
            startProperties.setProperty("msglimit30", "18.75");
            startProperties.setProperty("musicenable", "true");
            startProperties.setProperty("whisperlimit60", "60.0");
        }
    } catch (Exception ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }

    /* Check to see if there's a webOauth set */
    if (startProperties.getProperty("webauth") == null) {
        startProperties.setProperty("webauth", generateWebAuth());
        com.gmt2001.Console.debug.println("New webauth key has been generated for botlogin.txt");
        changed = true;
    }
    /* Check to see if there's a webOAuthRO set */
    if (startProperties.getProperty("webauthro") == null) {
        startProperties.setProperty("webauthro", generateWebAuth());
        com.gmt2001.Console.debug.println("New webauth read-only key has been generated for botlogin.txt");
        changed = true;
    }
    /* Check to see if there's a panelUsername set */
    if (startProperties.getProperty("paneluser") == null) {
        com.gmt2001.Console.debug.println(
                "No Panel Username, using default value of 'panel' for Control Panel and YouTube Player");
        startProperties.setProperty("paneluser", "panel");
        changed = true;
    }
    /* Check to see if there's a panelPassword set */
    if (startProperties.getProperty("panelpassword") == null) {
        com.gmt2001.Console.debug.println(
                "No Panel Password, using default value of 'panel' for Control Panel and YouTube Player");
        startProperties.setProperty("panelpassword", "panel");
        changed = true;
    }
    /* Check to see if there's a youtubeOAuth set */
    if (startProperties.getProperty("ytauth") == null) {
        startProperties.setProperty("ytauth", generateWebAuth());
        com.gmt2001.Console.debug.println("New YouTube websocket key has been generated for botlogin.txt");
        changed = true;
    }
    /* Check to see if there's a youtubeOAuthThro set */
    if (startProperties.getProperty("ytauthro") == null) {
        startProperties.setProperty("ytauthro", generateWebAuth());
        com.gmt2001.Console.debug
                .println("New YouTube read-only websocket key has been generated for botlogin.txt");
        changed = true;
    }

    /* Make a new botlogin with the botName, oauth or channel is not found */
    if (startProperties.getProperty("user") == null || startProperties.getProperty("oauth") == null
            || startProperties.getProperty("channel") == null) {
        try {
            com.gmt2001.Console.out.print("\r\n");
            com.gmt2001.Console.out.print("Welcome to the PhantomBot setup process!\r\n");
            com.gmt2001.Console.out
                    .print("If you have any issues please report them on our forum or Tweet at us!\r\n");
            com.gmt2001.Console.out.print("Forum: https://community.phantombot.tv/\r\n");
            com.gmt2001.Console.out.print("Twitter: https://twitter.com/phantombotapp/\r\n");
            com.gmt2001.Console.out.print("PhantomBot Knowledgebase: https://docs.phantombot.tv/\r\n");
            com.gmt2001.Console.out.print("PhantomBot WebPanel: https://docs.phantombot.tv/kb/panel/\r\n");
            com.gmt2001.Console.out.print("\r\n");
            com.gmt2001.Console.out.print("\r\n");

            com.gmt2001.Console.out.print("1. Please enter the bot's Twitch username: ");
            startProperties.setProperty("user", System.console().readLine().trim());

            com.gmt2001.Console.out.print("\r\n");
            com.gmt2001.Console.out
                    .print("2. You will now need a OAuth token for the bot to be able to chat.\r\n");
            com.gmt2001.Console.out.print(
                    "Please note, this OAuth token needs to be generated while you're logged in into the bot's Twitch account.\r\n");
            com.gmt2001.Console.out.print(
                    "If you're not logged in as the bot, please go to https://twitch.tv/ and login as the bot.\r\n");
            com.gmt2001.Console.out.print("Get the bot's OAuth token here: https://twitchapps.com/tmi/\r\n");
            com.gmt2001.Console.out.print("Please enter the bot's OAuth token: ");
            startProperties.setProperty("oauth", System.console().readLine().trim());

            com.gmt2001.Console.out.print("\r\n");
            com.gmt2001.Console.out.print(
                    "3. You will now need your channel OAuth token for the bot to be able to change your title and game.\r\n");
            com.gmt2001.Console.out.print(
                    "Please note, this OAuth token needs to be generated while you're logged in into your caster account.\r\n");
            com.gmt2001.Console.out.print(
                    "If you're not logged in as the caster, please go to https://twitch.tv/ and login as the caster.\r\n");
            com.gmt2001.Console.out.print("Get the your OAuth token here: https://phantombot.tv/oauth/\r\n");
            com.gmt2001.Console.out.print("Please enter your OAuth token: ");
            startProperties.setProperty("apioauth", System.console().readLine().trim());

            com.gmt2001.Console.out.print("\r\n");
            com.gmt2001.Console.out
                    .print("4. Please enter the name of the Twitch channel the bot should join: ");
            startProperties.setProperty("channel", System.console().readLine().trim());

            com.gmt2001.Console.out.print("\r\n");
            com.gmt2001.Console.out.print("5. Please enter a custom username for the web panel: ");
            startProperties.setProperty("paneluser", System.console().readLine().trim());

            com.gmt2001.Console.out.print("\r\n");
            com.gmt2001.Console.out.print("6. Please enter a custom password for the web panel: ");
            startProperties.setProperty("panelpassword", System.console().readLine().trim());

            changed = true;
            newSetup = true;
        } catch (NullPointerException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
            com.gmt2001.Console.out.println("[ERROR] Failed to setup PhantomBot. Now exiting...");
            System.exit(0);
        }
    }

    /* Make sure the oauth has been set correctly */
    if (startProperties.getProperty("oauth") != null) {
        if (!startProperties.getProperty("oauth").startsWith("oauth")
                && !startProperties.getProperty("oauth").isEmpty()) {
            startProperties.setProperty("oauth", "oauth:" + startProperties.getProperty("oauth"));
            changed = true;
        }
    }

    /* Make sure the apiOAuth has been set correctly */
    if (startProperties.getProperty("apioauth") != null) {
        if (!startProperties.getProperty("apioauth").startsWith("oauth")
                && !startProperties.getProperty("apioauth").isEmpty()) {
            startProperties.setProperty("apioauth", "oauth:" + startProperties.getProperty("apioauth"));
            changed = true;
        }
    }

    /* Make sure the channelName does not have a # */
    if (startProperties.getProperty("channel").startsWith("#")) {
        startProperties.setProperty("channel", startProperties.getProperty("channel").substring(1));
        changed = true;
    } else if (startProperties.getProperty("channel").contains(".tv")) {
        startProperties.setProperty("channel", startProperties.getProperty("channel")
                .substring(startProperties.getProperty("channel").indexOf(".tv/") + 4).replaceAll("/", ""));
        changed = true;
    }

    /* Check for the owner after the channel check is done. */
    if (startProperties.getProperty("owner") == null) {
        if (startProperties.getProperty("channel") != null) {
            if (!startProperties.getProperty("channel").isEmpty()) {
                startProperties.setProperty("owner", startProperties.getProperty("channel"));
                changed = true;
            }
        }
    }

    /* Iterate the properties and delete entries for anything that does not have a 
     * value.
     */
    for (String propertyKey : startProperties.stringPropertyNames()) {
        if (startProperties.getProperty(propertyKey).isEmpty()) {
            changed = true;
            startProperties.remove(propertyKey);
        }
    }

    /* 
     * Check for required settings.
     */
    for (String requiredProperty : requiredProperties) {
        if (startProperties.getProperty(requiredProperty) == null) {
            requiredPropertiesErrorMessage += requiredProperty + " ";
        }
    }

    if (!requiredPropertiesErrorMessage.isEmpty()) {
        com.gmt2001.Console.err.println();
        com.gmt2001.Console.err.println("Missing Required Properties: " + requiredPropertiesErrorMessage);
        com.gmt2001.Console.err.println("Exiting PhantomBot");
        System.exit(0);
    }

    /* Check to see if anything changed */
    if (changed) {
        Properties outputProperties = new Properties() {
            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(new TreeSet<>(super.keySet()));
            }
        };

        try {
            try (FileOutputStream outputStream = new FileOutputStream("botlogin.txt")) {
                outputProperties.putAll(startProperties);
                outputProperties.store(outputStream, "PhantomBot Configuration File");
            }
        } catch (IOException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
    }

    /* Start PhantomBot */
    PhantomBot.instance = new PhantomBot(startProperties);
}

From source file:de.uniwue.info2.main.CommandLineInterpreter.java

@SuppressWarnings("static-access")
public static void main(String[] args) {

    /*-------------------------------------------------------- */
    /*---------------SETTING TARGET LANGUAGE------------------ */
    /*-------------------------------------------------------- */
    LanguageFactory languageFactory = new LanguageFactory();

    CommandLine line = null;//from  w  w w  .  ja  va 2 s  .c  om
    CommandLineParser parser = new BasicParser();
    Options options = new Options();
    // options to display in the help page
    Options options_short = new Options();

    // add help option
    Option help_option = new Option(HELP_OPTION_SHORT, HELP_OPTION, false, HELP_DESCRIPTION);
    options.addOption(help_option);
    options_short.addOption(help_option);
    // add extended help option
    Option help2_option = new Option(HELP2_OPTION_SHORT, HELP2_OPTION, false, HELP2_DESCRIPTION);
    options.addOption(help2_option);
    options_short.addOption(help2_option);
    // add optional operations option
    options.addOption(new Option(OPTIONAL_OPTION_SHORT, OPTIONAL_OPTION, false, OPTIONAL_DESCRIPTION));
    options.addOption(new Option(BIG_ENDIAN_OPTION_SHORT, BIG_ENDIAN_OPTION, false, BIG_ENDIAN_DESCRIPTION));
    options.addOption(
            new Option(LITTLE_ENDIAN_OPTION_SHORT, LITTLE_ENDIAN_OPTION, false, LITTLE_ENDIAN_DESCRIPTION));
    // add optional operations config option
    options.addOption(OptionBuilder.withLongOpt(OPTIONAL_FUNCTIONS_CONFIG_OPTION)
            .withArgName(OPTIONAL_FUNCTIONS_CONFIG_ARGUMENT)
            .withDescription(OPTIONAL_FUNCTIONS_CONFIG_DESCRIPTION).hasArg()
            .create(OPTIONAL_FUNCTIONS_CONFIG_SHORT));
    // add dsl option
    Option dsl_option = OptionBuilder.withLongOpt(DSL_OPTION).withArgName(DSL_ARGUMENT)
            .withDescription(DSL_DESCRIPTION).hasArg().isRequired().create(DSL_OPTION_SHORT);
    options.addOption(dsl_option);
    options_short.addOption(dsl_option);
    // add output-folder option
    Option output_option = OptionBuilder.withLongOpt(OUTPUT_OPTION).isRequired().withArgName(OUTPUT_ARGUMENT)
            .withDescription(OUTPUT_DESCRIPTION).hasArg().create(OUTPUT_OPTION_SHORT);
    options.addOption(output_option);
    options_short.addOption(output_option);

    // count possible language-specifications
    short optionCounter = 1;

    // get all possible language-specifications from language-factory and iterate through them
    List<LanguageSpecification> lSpecs = languageFactory.getAvailableLanguageSpecifications_();

    for (LanguageSpecification lSpec : lSpecs) {
        // get all possible unit-specifications for current language and iterate through them
        List<UnitTestLibrarySpecification> uSpecs = languageFactory
                .getAvailableUnitTestLibraries_(lSpec.getOptionName());
        String languageDescriptionAll = LANGUAGE_SPECIFICATION + lSpec.getLanguageName();
        String languageCounter = "s" + INDEX.format(optionCounter++);

        for (UnitTestLibrarySpecification uSpec : uSpecs) {
            // get all possible arithmetic-library-specifications for current language and iterate through
            // them
            List<ArithmeticLibrarySpecification> aSpecs = languageFactory
                    .getAvailableArithmeticLibraries_(lSpec.getOptionName());
            for (ArithmeticLibrarySpecification aSpec : aSpecs) {
                String languageDescription = "Generate unit-test for " + lSpec.getLanguageName() + "\n*["
                        + uSpec.getLibraryName() + " - " + uSpec.getVersion() + "]\n*[" + aSpec.getLibraryName()
                        + " - " + aSpec.getVersion() + "]";

                // if there is more than one option, generate suitable option-names and add them all to
                // commandline options
                if (uSpecs.size() > 1 || aSpecs.size() > 1) {
                    options.addOption(OptionBuilder
                            .withLongOpt(lSpec.getOptionName() + "_" + uSpec.getOptionName() + "_"
                                    + aSpec.getOptionName())
                            .withDescription(languageDescription).hasArg(false)
                            .create("s" + INDEX.format(optionCounter++)));
                } else {
                    // if there is only one option, use language-name as option-name
                    languageDescriptionAll = languageDescription;
                }
            }
            // add specifications to options
            options.addOption(OptionBuilder.withLongOpt(lSpec.getOptionName())
                    .withDescription(languageDescriptionAll).hasArg(false).create(languageCounter));
        }
    }

    /*-------------------------------------------------------- */
    /*-------------------PARSE USER INPUT--------------------- */
    /*-------------------------------------------------------- */
    try {
        // manual search for help-arguments
        for (String arg : args) {
            arg = arg.trim().replace("-", "");
            if (arg.equals(HELP_OPTION_SHORT) || arg.equals(HELP_OPTION)) {
                printHelp(options_short);
                return;
            }
            if (arg.equals(HELP2_OPTION_SHORT) || arg.equals(HELP2_OPTION)) {
                printExtendedHelp(options);
                return;
            }
        }

        // parse arguments   
        line = parser.parse(options, args);

        File dsl_file = null;
        File output_folder = null;
        File optional_config = null;
        Properties optional_operations = null;
        Boolean optional = false;
        Boolean little_endian = null;
        ArrayList<String> optional_exceptions = new ArrayList<String>();

        // if help-option found print help
        if (line.hasOption(HELP2_OPTION_SHORT) || args.length == 0) {
            printExtendedHelp(options);
            return;
        }

        // if help-option found print help
        if (line.hasOption(HELP_OPTION_SHORT) || args.length == 0) {
            System.out.println("\n");
            printHelp(options_short);
            return;
        }

        if (line.hasOption(OPTIONAL_OPTION_SHORT)) {
            optional = true;
        }

        if (line.hasOption(LITTLE_ENDIAN_OPTION)) {
            little_endian = true;
        }

        if (line.hasOption(BIG_ENDIAN_OPTION)) {
            little_endian = false;
        }

        // if dsl-option found, check if file exists and is readable
        // print help if error occurs
        if (line.hasOption(DSL_OPTION_SHORT)) {
            dsl_file = new File(line.getOptionValue(DSL_OPTION_SHORT));
            if (!dsl_file.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - DSL-file doesn't exist:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (dsl_file.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - DSL-file is a directory:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!dsl_file.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Need read-permission for DSL-file:\n"
                        + dsl_file + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            }
        }

        // if output-option found, check if folder exists and if write-permission was granted
        // print help if error occurs
        if (line.hasOption(OUTPUT_OPTION_SHORT)) {
            output_folder = new File(line.getOptionValue(OUTPUT_OPTION_SHORT));
            if (!output_folder.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Output-folder doesn't exist:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!output_folder.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Output-folder is not a directory:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!output_folder.canWrite() || !output_folder.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Missing permissions for output-folder:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            }
        }

        if (line.hasOption(OPTIONAL_FUNCTIONS_CONFIG_SHORT)) {
            optional_config = new File(line.getOptionValue(OPTIONAL_FUNCTIONS_CONFIG_OPTION));
            if (!dsl_file.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - config-file doesn't exist:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            } else if (dsl_file.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - config-file is a directory:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            } else if (!dsl_file.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Need read-permission for config-file:\n"
                        + dsl_file + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            }
        }

        if (optional_config != null) {
            optional_operations = new Properties();
            BufferedInputStream stream = new BufferedInputStream(new FileInputStream(optional_config));
            optional_operations.load(stream);
            stream.close();
            String optional_prop = optional_operations.getProperty("GENERATE_OPTIONAL");
            if (optional_prop != null) {
                if (optional_prop.trim().toLowerCase().equals("true")) {
                    optional = true;
                } else if (optional_prop.trim().toLowerCase().equals("false")) {
                    optional = false;
                } else if (!optional_prop.trim().isEmpty()) {
                    System.err.println("\n" + SEPERATOR + "\n"
                            + "ERROR - Syntax incorrect in config-file:\nUse \"true\" or \"false\" for \"GENERATE_OPTIONAL\"\n"
                            + SEPERATOR + "\n");
                    printExtendedHelp(options);
                    return;
                }
            }
            String exceptions = optional_operations.getProperty("EXCLUSIONS");
            if (exceptions != null) {
                for (String exc : optional_operations.getProperty("EXCLUSIONS").split(";")) {
                    optional_exceptions.add(exc.trim());
                }
            }
        }

        /*-------------------------------------------------------- */
        /*-------------------START GENERATING--------------------- */
        /*-------------------------------------------------------- */

        // instantiate generator for unit-tests
        TestcaseGenerator mainGenerator = new TestcaseGenerator(dsl_file, output_folder);

        boolean overrideDefaultSpecs = false;

        // check if user input contains a language-specifications
        // if user specified language, set overrideDefaultSpecs to true, so that only given specifications
        // are used
        for (int i = 1; i <= optionCounter; i++) {
            String opt = "s" + INDEX.format(i);
            if (line.hasOption(opt)) {
                LanguageSpecification targetSpecification = languageFactory
                        .getLanguageSpecification(options.getOption(opt).getLongOpt());
                String output = (GENERATING_DIALOG + targetSpecification.getLanguageName());

                // finally generate unit-test for current language-specification
                boolean successful = mainGenerator.generateUnitTest(targetSpecification, optional,
                        optional_exceptions, little_endian);

                if (successful) {
                    System.out.println(output + "\n--> Successfully generated.");
                } else {
                    System.err.println(output + "\n--> ERROR - see logfile");
                }
                overrideDefaultSpecs = true;
            }
        }

        // skip, if user already defined one language-specification
        // if user did not define language-specification, generate unit-tests for all
        // possible language-specifications (default)
        if (!overrideDefaultSpecs) {
            for (int i = 0; i < lSpecs.size(); i++) {
                LanguageSpecification specification = languageFactory
                        .getLanguageSpecification(lSpecs.get(i).getOptionName());

                String output = INDEX.format(i + 1) + " - " + GENERATING_DIALOG
                        + specification.getLanguageName();

                // finally generate unit-test for current language-specification
                boolean successful = mainGenerator.generateUnitTest(specification, optional,
                        optional_exceptions, little_endian);

                if (successful) {
                    System.out.println(output + "\n--> Successfully generated.");
                } else {
                    System.err.println(output + "\n--> ERROR - see logfile");
                }
            }
        }

    } catch (ParseException | IOException p) {
        System.err.println("\n" + SEPERATOR + "\n" + "ERROR - WRONG ARGUMENTS:\n" + p.getMessage() + "\n"
                + SEPERATOR + "\n");
        printHelp(options_short);
        System.out.println("\n");
    }
}

From source file:com.mgreau.jboss.as7.cli.CliLauncher.java

public static void main(String[] args) throws Exception {
    int exitCode = 0;
    CommandContext cmdCtx = null;//from w ww . j a  v a 2 s . c  o m
    boolean gui = false;
    String appName = "";
    try {
        String argError = null;
        List<String> commands = null;
        File file = null;
        boolean connect = false;
        String defaultControllerProtocol = "http-remoting";
        String defaultControllerHost = null;
        int defaultControllerPort = -1;
        boolean version = false;
        String username = null;
        char[] password = null;
        int connectionTimeout = -1;

        //App deployment
        boolean isAppDeployment = false;
        final Properties props = new Properties();

        for (String arg : args) {
            if (arg.startsWith("--controller=") || arg.startsWith("controller=")) {
                final String fullValue;
                final String value;
                if (arg.startsWith("--")) {
                    fullValue = arg.substring(13);
                } else {
                    fullValue = arg.substring(11);
                }
                final int protocolEnd = fullValue.lastIndexOf("://");
                if (protocolEnd == -1) {
                    value = fullValue;
                } else {
                    value = fullValue.substring(protocolEnd + 3);
                    defaultControllerProtocol = fullValue.substring(0, protocolEnd);
                }

                String portStr = null;
                int colonIndex = value.lastIndexOf(':');
                if (colonIndex < 0) {
                    // default port
                    defaultControllerHost = value;
                } else if (colonIndex == 0) {
                    // default host
                    portStr = value.substring(1);
                } else {
                    final boolean hasPort;
                    int closeBracket = value.lastIndexOf(']');
                    if (closeBracket != -1) {
                        //possible ip v6
                        if (closeBracket > colonIndex) {
                            hasPort = false;
                        } else {
                            hasPort = true;
                        }
                    } else {
                        //probably ip v4
                        hasPort = true;
                    }
                    if (hasPort) {
                        defaultControllerHost = value.substring(0, colonIndex).trim();
                        portStr = value.substring(colonIndex + 1).trim();
                    } else {
                        defaultControllerHost = value;
                    }
                }

                if (portStr != null) {
                    int port = -1;
                    try {
                        port = Integer.parseInt(portStr);
                        if (port < 0) {
                            argError = "The port must be a valid non-negative integer: '" + args + "'";
                        } else {
                            defaultControllerPort = port;
                        }
                    } catch (NumberFormatException e) {
                        argError = "The port must be a valid non-negative integer: '" + arg + "'";
                    }
                }
            } else if ("--connect".equals(arg) || "-c".equals(arg)) {
                connect = true;
            } else if ("--version".equals(arg)) {
                version = true;
            } else if ("--gui".equals(arg)) {
                gui = true;
            } else if (arg.startsWith("--appDeployment=") || arg.startsWith("appDeployment=")) {
                isAppDeployment = true;
                appName = arg.startsWith("--") ? arg.substring(16) : arg.substring(14);
            } else if (arg.startsWith("--file=") || arg.startsWith("file=")) {
                if (file != null) {
                    argError = "Duplicate argument '--file'.";
                    break;
                }
                if (commands != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }

                final String fileName = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
                if (!fileName.isEmpty()) {
                    file = new File(fileName);
                    if (!file.exists()) {
                        argError = "File " + file.getAbsolutePath() + " doesn't exist.";
                        break;
                    }
                } else {
                    argError = "Argument '--file' is missing value.";
                    break;
                }
            } else if (arg.startsWith("--commands=") || arg.startsWith("commands=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(11) : arg.substring(9);
                commands = Util.splitCommands(value);
            } else if (arg.startsWith("--command=") || arg.startsWith("command=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(10) : arg.substring(8);
                commands = Collections.singletonList(value);
            } else if (arg.startsWith("--user=")) {
                username = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
            } else if (arg.startsWith("--password=")) {
                password = (arg.startsWith("--") ? arg.substring(11) : arg.substring(9)).toCharArray();
            } else if (arg.startsWith("--timeout=")) {
                if (connectionTimeout > 0) {
                    argError = "Duplicate argument '--timeout'";
                    break;
                }
                final String value = arg.substring(10);
                try {
                    connectionTimeout = Integer.parseInt(value);
                } catch (final NumberFormatException e) {
                    //
                }
                if (connectionTimeout <= 0) {
                    argError = "The timeout must be a valid positive integer: '" + value + "'";
                }
            } else if (arg.equals("--help") || arg.equals("-h")) {
                commands = Collections.singletonList("help");
            } else if (arg.startsWith("--properties=")) {
                final String value = arg.substring(13);
                final File propertiesFile = new File(value);
                if (!propertiesFile.exists()) {
                    argError = "File doesn't exist: " + propertiesFile.getAbsolutePath();
                    break;
                }

                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(propertiesFile);
                    props.load(fis);
                } catch (FileNotFoundException e) {
                    argError = e.getLocalizedMessage();
                    break;
                } catch (java.io.IOException e) {
                    argError = "Failed to load properties from " + propertiesFile.getAbsolutePath() + ": "
                            + e.getLocalizedMessage();
                    break;
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (java.io.IOException e) {
                        }
                    }
                }
                for (final Object prop : props.keySet()) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        public Object run() {
                            System.setProperty((String) prop, (String) props.get(prop));
                            return null;
                        }
                    });
                }
            } else if (!(arg.startsWith("-D") || arg.equals("-XX:"))) {// skip system properties and jvm options
                // assume it's commands
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time: "
                            + arg;
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                commands = Util.splitCommands(arg);
            }
        }

        if (argError != null) {
            System.err.println(argError);
            exitCode = 1;
            return;
        }

        if (version) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            VersionHandler.INSTANCE.handle(cmdCtx);
            return;
        }

        if (file != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processFile(file, cmdCtx, isAppDeployment, appName, props);
            return;
        }

        if (commands != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processCommands(commands, cmdCtx);
            return;
        }

        // Interactive mode
        cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                username, password, true, connect, connectionTimeout);
        cmdCtx.interact();
    } catch (Throwable t) {
        t.printStackTrace();
        exitCode = 1;
    } finally {
        if (cmdCtx != null && cmdCtx.getExitCode() != 0) {
            exitCode = cmdCtx.getExitCode();
        }
        if (!gui) {
            System.exit(exitCode);
        }
    }
    System.exit(exitCode);
}

From source file:Main.java

/**
 * Read file from SDCARD/*  w  w  w  .j av  a  2  s  .  c  om*/
 * 
 * @param filepath
 * @throws IOException
 */
public static void readfromsdcard(String filepath) throws IOException {
    // FileInputStream fis = new FileInputStream("sdcard/test.properties");
    FileInputStream fis = new FileInputStream(filepath);
    Properties cfg = new Properties();
    cfg.load(fis);
}

From source file:example.client.CamelMongoJmsStockClient.java

private static Properties loadProperties() throws Exception {
    Properties props = new Properties();
    props.load(CamelMongoJmsStockClient.class.getClassLoader().getResourceAsStream("application.properties"));
    return props;
}

From source file:Main.java

public static Map<String, String> toMap(String properties) {
    try {//from  w ww  . j a v  a  2 s .c  o m
        InputStream is = new ByteArrayInputStream(properties.getBytes("UTF-8"));
        Properties prop = new Properties();
        prop.load(is);
        Map<String, String> ret = new HashMap<String, String>();
        for (String key : prop.stringPropertyNames()) {
            ret.put(key, prop.getProperty(key));
        }
        return ret;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:Main.java

/**
 * Converts properties from file storage format
 *//*w w w  . j  a  v a2 s  . c  om*/
public static Properties fromFileContent(String content) {
    try {
        StringReader reader = new StringReader(content);
        Properties props = new Properties();
        props.load(reader);
        return props;
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe); // shouldn't happen
    }
}

From source file:Main.java

public static Properties getProperties(String string) {
    Properties properties = new Properties();
    try {//from www.  j av a2s.  c o  m
        properties.load(new StringReader(string));
    } catch (IOException e) {
        e.printStackTrace();
    }

    return properties;
}

From source file:Main.java

static boolean isTestnet(final Context c) {
    try {/*from  w ww. j av a2  s .co  m*/
        final Properties p = new Properties();
        p.load(new BufferedInputStream(new FileInputStream(getBitcoinConf(c))));
        return p.getProperty("testnet", p.getProperty("regtest", "0")).equals("1");
    } catch (final IOException e) {
        return false;
    }
}