Example usage for java.util Properties store

List of usage examples for java.util Properties store

Introduction

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

Prototype

public void store(OutputStream out, String comments) throws IOException 

Source Link

Document

Writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the #load(InputStream) load(InputStream) method.

Usage

From source file:com.l2jfree.loginserver.tools.L2GameServerRegistrar.java

/**
 * Launches the interactive game server registration.
 * /*from w  w w  . j  ava 2  s . com*/
 * @param args ignored
 */
public static void main(String[] args) {
    // LOW rework this crap
    Util.printSection("Game Server Registration");
    _log.info("Please choose:");
    _log.info("list - list registered game servers");
    _log.info("reg - register a game server");
    _log.info("rem - remove a registered game server");
    _log.info("hexid - generate a legacy hexid file");
    _log.info("quit - exit this application");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    L2GameServerRegistrar reg = new L2GameServerRegistrar();

    String line;
    try {
        RegistrationState next = RegistrationState.INITIAL_CHOICE;
        while ((line = br.readLine()) != null) {
            line = line.trim().toLowerCase();
            switch (reg.getState()) {
            case GAMESERVER_ID:
                try {
                    int id = Integer.parseInt(line);
                    if (id < 1 || id > 127)
                        throw new IllegalArgumentException("ID must be in [1;127].");
                    reg.setId(id);
                    reg.setState(next);
                } catch (RuntimeException e) {
                    _log.info("You must input a number between 1 and 127");
                }

                if (reg.getState() == RegistrationState.ALLOW_BANS) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con
                                .prepareStatement("SELECT allowBans FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        ResultSet rs = ps.executeQuery();
                        if (rs.next()) {
                            _log.info("A game server is already registered on ID " + reg.getId());
                            reg.setState(RegistrationState.INITIAL_CHOICE);
                        } else
                            _log.info("Allow account bans from this game server? [y/n]:");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not remove a game server!", e);
                    } finally {
                        L2Database.close(con);
                    }
                } else if (reg.getState() == RegistrationState.REMOVE) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement("DELETE FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        int cnt = ps.executeUpdate();
                        if (cnt == 0)
                            _log.info("No game server registered on ID " + reg.getId());
                        else
                            _log.info("Game server removed.");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not remove a game server!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } else if (reg.getState() == RegistrationState.GENERATE) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con
                                .prepareStatement("SELECT authData FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        ResultSet rs = ps.executeQuery();

                        if (rs.next()) {
                            reg.setAuth(rs.getString("authData"));
                            byte[] b = HexUtil.hexStringToBytes(reg.getAuth());

                            Properties pro = new Properties();
                            pro.setProperty("ServerID", String.valueOf(reg.getId()));
                            pro.setProperty("HexID", HexUtil.hexToString(b));

                            BufferedOutputStream os = new BufferedOutputStream(
                                    new FileOutputStream("hexid.txt"));
                            pro.store(os, "the hexID to auth into login");
                            IOUtils.closeQuietly(os);
                            _log.info("hexid.txt has been generated.");
                        } else
                            _log.info("No game server registered on ID " + reg.getId());

                        rs.close();
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not generate hexid.txt!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                }
                break;
            case ALLOW_BANS:
                try {
                    if (line.length() != 1)
                        throw new IllegalArgumentException("One char required.");
                    else if (line.charAt(0) == 'y')
                        reg.setTrusted(true);
                    else if (line.charAt(0) == 'n')
                        reg.setTrusted(false);
                    else
                        throw new IllegalArgumentException("Invalid choice.");

                    byte[] auth = Rnd.nextBytes(new byte[BYTES]);
                    reg.setAuth(HexUtil.bytesToHexString(auth));

                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement(
                                "INSERT INTO gameserver (id, authData, allowBans) VALUES (?, ?, ?)");
                        ps.setInt(1, reg.getId());
                        ps.setString(2, reg.getAuth());
                        ps.setBoolean(3, reg.isTrusted());
                        ps.executeUpdate();
                        ps.close();

                        _log.info("Registered game server on ID " + reg.getId());
                        _log.info("The authorization string is:");
                        _log.info(reg.getAuth());
                        _log.info("Use it when registering this login server.");
                        _log.info("If you need a legacy hexid file, use the 'hexid' command.");
                    } catch (SQLException e) {
                        _log.error("Could not register gameserver!", e);
                    } finally {
                        L2Database.close(con);
                    }

                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } catch (IllegalArgumentException e) {
                    _log.info("[y/n]?");
                }
                break;
            default:
                if (line.equals("list")) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement("SELECT id, allowBans FROM gameserver");
                        ResultSet rs = ps.executeQuery();
                        while (rs.next())
                            _log.info("ID: " + rs.getInt("id") + ", trusted: " + rs.getBoolean("allowBans"));
                        rs.close();
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not register gameserver!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } else if (line.equals("reg")) {
                    _log.info("Enter the desired ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.ALLOW_BANS;
                } else if (line.equals("rem")) {
                    _log.info("Enter game server ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.REMOVE;
                } else if (line.equals("hexid")) {
                    _log.info("Enter game server ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.GENERATE;
                } else if (line.equals("quit"))
                    Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN);
                else
                    _log.info("Incorrect command.");
                break;
            }
        }
    } catch (IOException e) {
        _log.fatal("Could not process input!", e);
    } finally {
        IOUtils.closeQuietly(br);
    }
}

From source file:com.github.jcustenborder.kafka.connect.spooldir.SchemaGenerator.java

public static void main(String... args) throws Exception {
    ArgumentParser parser = ArgumentParsers.newArgumentParser("CsvSchemaGenerator").defaultHelp(true)
            .description("Generate a schema based on a file.");
    parser.addArgument("-t", "--type").required(true).choices("csv", "json")
            .help("The type of generator to use.");
    parser.addArgument("-c", "--config").type(File.class);
    parser.addArgument("-f", "--file").type(File.class).required(true)
            .help("The data file to generate the schema from.");
    parser.addArgument("-i", "--id").nargs("*").help("Field(s) to use as an identifier.");
    parser.addArgument("-o", "--output").type(File.class)
            .help("Output location to write the configuration to. Stdout is default.");

    Namespace ns = null;/*from  www  .  j a va2  s  .  c o m*/

    try {
        ns = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
        parser.handleError(ex);
        System.exit(1);
    }

    File inputFile = ns.get("file");
    List<String> ids = ns.getList("id");
    if (null == ids) {
        ids = ImmutableList.of();
    }

    Map<String, Object> settings = new LinkedHashMap<>();

    File inputPropertiesFile = ns.get("config");
    if (null != inputPropertiesFile) {
        Properties inputProperties = new Properties();

        try (FileInputStream inputStream = new FileInputStream(inputPropertiesFile)) {
            inputProperties.load(inputStream);
        }
        for (String s : inputProperties.stringPropertyNames()) {
            Object v = inputProperties.getProperty(s);
            settings.put(s, v);
        }
    }

    final SchemaGenerator generator;
    final String type = ns.getString("type");

    if ("csv".equalsIgnoreCase(type)) {
        generator = new CsvSchemaGenerator(settings);
    } else if ("json".equalsIgnoreCase(type)) {
        generator = new JsonSchemaGenerator(settings);
    } else {
        throw new UnsupportedOperationException(
                String.format("'%s' is not a supported schema generator type", type));
    }

    Map.Entry<Schema, Schema> kvp = generator.generate(inputFile, ids);

    Properties properties = new Properties();
    properties.putAll(settings);
    properties.setProperty(SpoolDirSourceConnectorConfig.KEY_SCHEMA_CONF,
            ObjectMapperFactory.INSTANCE.writeValueAsString(kvp.getKey()));
    properties.setProperty(SpoolDirSourceConnectorConfig.VALUE_SCHEMA_CONF,
            ObjectMapperFactory.INSTANCE.writeValueAsString(kvp.getValue()));

    String output = ns.getString("output");
    final String comment = "Configuration was dynamically generated. Please verify before submitting.";

    if (Strings.isNullOrEmpty(output)) {
        properties.store(System.out, comment);
    } else {
        try (FileOutputStream outputStream = new FileOutputStream(output)) {
            properties.store(outputStream, comment);
        }
    }
}

From source file:edu.indiana.d2i.sloan.internal.StopVMSimulator.java

public static void main(String[] args) {
    StopVMSimulator simulator = new StopVMSimulator();

    CommandLineParser parser = new PosixParser();

    try {// w  w  w  . ja v a2 s. c  om
        CommandLine line = simulator.parseCommandLine(parser, args);
        String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR));

        if (!HypervisorCmdSimulator.resourceExist(wdir)) {
            logger.error(String.format("Cannot find VM working dir: %s", wdir));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_EXIST));
        }

        Properties prop = new Properties();
        String filename = HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME;

        prop.load(new FileInputStream(new File(filename)));

        // cannot stop VM when it is not running
        VMState currentState = VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE)));

        if (!currentState.equals(VMState.RUNNING)) {
            logger.error("Cannot perform stop when VM is not running");
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_RUNNING));
        }

        // stop VM
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }

        // update VM status file, i.e. set state to shutdown
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE), VMState.SHUTDOWN.toString());

        // save VM state file back
        prop.store(new FileOutputStream(new File(filename)), "");

        // success
        System.exit(0);

    } catch (ParseException e) {
        logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s",
                StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, "")));

        System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR));
    }

}

From source file:edu.indiana.d2i.sloan.internal.CreateVMSimulator.java

public static void main(String[] args) {
    CreateVMSimulator simulator = new CreateVMSimulator();

    CommandLineParser parser = new PosixParser();

    try {/*from ww  w.  j  ava  2 s . c o  m*/
        CommandLine line = simulator.parseCommandLine(parser, args);

        String imagePath = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.IMAGE_PATH));
        int vcpu = Integer.parseInt(line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VCPU)));
        int mem = Integer.parseInt(line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.MEM)));

        if (!HypervisorCmdSimulator.resourceExist(imagePath)) {
            logger.error(String.format("Cannot find requested image: %s", imagePath));
            System.exit(ERROR_CODE.get(ERROR_STATE.IMAGE_NOT_EXIST));
        }

        if (!hasEnoughCPUs(vcpu)) {
            logger.error(String.format("Don't have enough cpus, requested %d", vcpu));
            System.exit(ERROR_CODE.get(ERROR_STATE.NOT_ENOUGH_CPU));
        }

        if (!hasEnoughMem(mem)) {
            logger.error(String.format("Don't have enough memory, requested %d", mem));
            System.exit(ERROR_CODE.get(ERROR_STATE.NOT_ENOUGH_MEM));
        }

        String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR));

        if (HypervisorCmdSimulator.resourceExist(wdir)) {
            logger.error(String.format("Working directory %s already exists ", wdir));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_ALREADY_EXIST));
        }

        // copy VM image to working directory
        File imageFile = new File(imagePath);
        FileUtils.copyFile(imageFile, new File(HypervisorCmdSimulator.cleanPath(wdir) + imageFile.getName()));

        // write state as property file so that we can query later
        Properties prop = new Properties();

        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.IMAGE_PATH), imagePath);
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VCPU), String.valueOf(vcpu));
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.MEM), String.valueOf(mem));
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR), wdir);
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VNC_PORT),
                line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VNC_PORT)));
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.SSH_PORT),
                line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.SSH_PORT)));
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_USERNAME),
                line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_USERNAME)));
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_PASSWD),
                line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_PASSWD)));

        // write VM state as shutdown
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE), VMState.SHUTDOWN.toString());
        // write VM mode as undefined
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE), VMMode.NOT_DEFINED.toString());

        prop.store(
                new FileOutputStream(new File(
                        HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME)),
                "");

        // do other related settings
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }

        // success
        System.exit(0);

    } catch (ParseException e) {
        logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s",
                StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, "")));

        System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR));
    }
}

From source file:edu.indiana.d2i.sloan.internal.LaunchVMSimulator.java

/**
 * @param args/*from   w w w .j  a  v  a  2s.c om*/
 */
public static void main(String[] args) {
    LaunchVMSimulator simulator = new LaunchVMSimulator();

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine line = simulator.parseCommandLine(parser, args);

        String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR));
        String mode = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE));
        String policyFilePath = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH));

        if (!HypervisorCmdSimulator.resourceExist(wdir)) {
            logger.error(String.format("Cannot find VM working dir: %s", wdir));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_EXIST));
        }

        VMMode vmmode = HypervisorCmdSimulator.getVMMode(mode);

        if (vmmode == null) {
            logger.error(String.format("Invalid requested mode: %s, can only be %s or %s", mode,
                    VMMode.MAINTENANCE.toString(), VMMode.SECURE.toString()));
            System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_VM_MODE));
        }

        if (!HypervisorCmdSimulator.resourceExist(policyFilePath)) {
            logger.error(String.format("Cannot find plicy file: %s", policyFilePath));
            System.exit(ERROR_CODE.get(ERROR_STATE.FIREWALL_POLICY_NOT_EXIST));
        }

        // load VM status info
        Properties prop = new Properties();
        String filename = HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME;

        prop.load(new FileInputStream(new File(filename)));

        // can only launch VM when it is in shutdown state
        VMState currentState = VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE)));

        if (!currentState.equals(VMState.SHUTDOWN)) {
            logger.error(String.format("Can only launch VM when it is in %s state, current VM state is %s",
                    VMState.SHUTDOWN.toString(), currentState.toString()));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_SHUTDOWN));
        }
        // launch VM
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }

        // update VM state file

        // set following properties
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH), policyFilePath);
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE), vmmode.toString());

        // set VM state to running
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE), VMState.RUNNING.toString());

        // save VM state file back
        prop.store(new FileOutputStream(new File(filename)), "");

        // success
        System.exit(0);
    } catch (ParseException e) {
        logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s",
                StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, "")));

        System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS));
    } catch (FileNotFoundException e) {
        logger.error(String.format("Cannot find vm state file: %s", e.getMessage()));

        System.exit(ERROR_CODE.get(ERROR_STATE.VM_STATE_FILE_NOT_FOUND));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR));
    }
}

From source file:de.cwclan.cwsa.serverendpoint.main.ServerEndpoint.java

/**
 * @param args the command line arguments
 *//*from w  w w  .  ja  va2  s  .  c  o  m*/
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription(
            "Used to enter path of configfile. Default file is endpoint.properties. NOTE: If the file is empty or does not exsist, a default config is created.")
            .create("config"));
    options.addOption("h", "help", false, "displays this page");
    CommandLineParser parser = new PosixParser();
    Properties properties = new Properties();
    try {
        /*
         * parse default config shipped with jar
         */
        CommandLine cmd = parser.parse(options, args);

        /*
         * load default configuration
         */
        InputStream in = ServerEndpoint.class.getResourceAsStream("/endpoint.properties");
        if (in == null) {
            throw new IOException("Unable to load default config from JAR. This should not happen.");
        }
        properties.load(in);
        in.close();
        log.debug("Loaded default config base: {}", properties.toString());
        if (cmd.hasOption("help")) {
            printHelp(options);
            System.exit(0);
        }

        /*
         * parse cutom config if exists, otherwise create default cfg
         */
        if (cmd.hasOption("config")) {
            File file = new File(cmd.getOptionValue("config", "endpoint.properties"));
            if (file.exists() && file.canRead() && file.isFile()) {
                in = new FileInputStream(file);
                properties.load(in);
                log.debug("Loaded custom config from {}: {}", file.getAbsoluteFile(), properties);
            } else {
                log.warn("Config file does not exsist. A default file will be created.");
            }
            FileWriter out = new FileWriter(file);
            properties.store(out,
                    "Warning, this file is recreated on every startup to merge missing parameters.");
        }

        /*
         * create and start endpoint
         */
        log.info("Config read successfull. Values are: {}", properties);
        ServerEndpoint endpoint = new ServerEndpoint(properties);
        Runtime.getRuntime().addShutdownHook(endpoint.getShutdownHook());
        endpoint.start();
    } catch (IOException ex) {
        log.error("Error while reading config.", ex);
    } catch (ParseException ex) {
        log.error("Error while parsing commandline options: {}", ex.getMessage());
        printHelp(options);
        System.exit(1);
    }
}

From source file:edu.indiana.d2i.sloan.internal.SwitchVMSimulator.java

/**
 * @param args/*from   w  ww  .  java2 s  .c  om*/
 */
public static void main(String[] args) {
    SwitchVMSimulator simulator = new SwitchVMSimulator();

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine line = simulator.parseCommandLine(parser, args);

        String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR));
        String mode = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE));
        String policyFilePath = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH));

        if (!HypervisorCmdSimulator.resourceExist(wdir)) {
            logger.error(String.format("Cannot find VM working dir: %s", wdir));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_EXIST));
        }

        VMMode requestedMode = HypervisorCmdSimulator.getVMMode(mode);

        if (requestedMode == null) {
            logger.error(String.format("Invalid requested mode: %s, can only be %s or %s", mode,
                    VMMode.MAINTENANCE.toString(), VMMode.SECURE.toString()));
            System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_VM_MODE));
        }

        if (!HypervisorCmdSimulator.resourceExist(policyFilePath)) {
            logger.error(String.format("Cannot find plicy file: %s", policyFilePath));
            System.exit(ERROR_CODE.get(ERROR_STATE.FIREWALL_POLICY_NOT_EXIST));
        }

        // load VM state file
        Properties prop = new Properties();
        String filename = HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME;

        prop.load(new FileInputStream(new File(filename)));

        // cannot switch when VM is not running
        VMState currentState = VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE)));

        if (!currentState.equals(VMState.RUNNING)) {
            logger.error("Cannot perform switch when VM is not running");
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_RUNNING));
        }

        // get current mode
        VMMode currentMode = VMMode.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE)));

        if (currentMode.equals(requestedMode)) {
            logger.error(String.format("VM is already in the requested mode: %s", requestedMode.toString()));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_ALREADY_IN_REQUESTED_MODE));
        }

        // switch VM
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }

        // update firewall policy
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH), policyFilePath);

        // update VM status file, i.e. set mode to the requested mode
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE), requestedMode.toString());

        // save VM state file back
        prop.store(new FileOutputStream(new File(filename)), "");

        // success
        System.exit(0);
    } catch (ParseException e) {
        logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s",
                StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, "")));

        System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS));
    } catch (FileNotFoundException e) {
        logger.error(String.format("Cannot find vm state file: %s", e.getMessage()));

        System.exit(ERROR_CODE.get(ERROR_STATE.VM_STATE_FILE_NOT_FOUND));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR));
    }
}

From source file:io.anserini.index.UserPostFrequencyDistribution.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(new Option(HELP_OPTION, "show help"));

    options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors"));

    options.addOption(OptionBuilder.withArgName("collection").hasArg()
            .withDescription("source collection directory").create(COLLECTION_OPTION));
    options.addOption(OptionBuilder.withArgName("property").hasArg()
            .withDescription("source collection directory").create("property"));
    options.addOption(OptionBuilder.withArgName("collection_pattern").hasArg()
            .withDescription("source collection directory").create("collection_pattern"));

    CommandLine cmdline = null;//from   w w w. ja v a 2s.  c o m
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(COLLECTION_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(UserPostFrequencyDistribution.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);

    final FieldType textOptions = new FieldType();
    textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
    textOptions.setStored(true);
    textOptions.setTokenized(true);
    textOptions.setStoreTermVectors(true);

    LOG.info("collection: " + collectionPath);
    LOG.info("collection_pattern " + cmdline.getOptionValue("collection_pattern"));
    LOG.info("property " + cmdline.getOptionValue("property"));
    LongOpenHashSet deletes = null;

    long startTime = System.currentTimeMillis();
    File file = new File(collectionPath);
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    final JsonStatusCorpusReader stream = new JsonStatusCorpusReader(file,
            cmdline.getOptionValue("collection_pattern"));

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {

            try {

                stream.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            ;

            System.out.println("# of users indexed this round: " + userIndexedCount);

            System.out.println("Shutting down");

        }
    });
    Status status;
    boolean readerNotInitialized = true;

    try {
        Properties prop = new Properties();
        while ((status = stream.next()) != null) {

            // try{
            // status = DataObjectFactory.createStatus(s);
            // if (status==null||status.getText() == null) {
            // continue;
            // }}catch(Exception e){
            //
            // }
            //

            boolean pittsburghRelated = false;
            try {

                if (Math.abs(status.getLongitude() - pittsburghLongitude) < 0.05d
                        && Math.abs(status.getlatitude() - pittsburghLatitude) < 0.05d)
                    pittsburghRelated = true;
            } catch (Exception e) {

            }
            try {
                if (status.getPlace().contains("Pittsburgh, PA"))
                    pittsburghRelated = true;
            } catch (Exception e) {

            }
            try {
                if (status.getUserLocation().contains("Pittsburgh, PA"))
                    pittsburghRelated = true;
            } catch (Exception e) {

            }

            try {
                if (status.getText().contains("Pittsburgh"))
                    pittsburghRelated = true;
            } catch (Exception e) {

            }

            if (pittsburghRelated) {

                int previousPostCount = 0;

                if (prop.containsKey(String.valueOf(status.getUserid()))) {
                    previousPostCount = Integer
                            .valueOf(prop.getProperty(String.valueOf(status.getUserid())).split(" ")[1]);
                }

                prop.setProperty(String.valueOf(status.getUserid()),
                        String.valueOf(status.getStatusesCount()) + " " + (1 + previousPostCount));
                if (prop.size() > 0 && prop.size() % 1000 == 0) {
                    Runtime runtime = Runtime.getRuntime();
                    runtime.gc();
                    System.out.println("Property size " + prop.size() + "Memory used:  "
                            + ((runtime.totalMemory() - runtime.freeMemory()) / (1024L * 1024L)) + " MB\n");
                }
                OutputStream output = new FileOutputStream(cmdline.getOptionValue("property"), false);
                prop.store(output, null);
                output.close();

            }
        }
        //         prop.store(output, null);
        LOG.info(String.format("Total of %s statuses added", userIndexedCount));
        LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {

        stream.close();
    }
}

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;/*from  w ww  . j a va2s  . c om*/

    /* 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:Main.java

/**
 * Stores the properties using {@link Properties#store(OutputStream, String)} on the given <code>stream</code>.
 * @param properties The properties to store
 * @param stream The stream to store to//from  w ww.j  a v a 2s.  c o  m
 * @param comment The comment to use
 * @throws IOException
 */
public static void storeProperties(Map<String, String> properties, OutputStream stream, String comment)
        throws IOException {
    Properties props = new Properties();
    props.putAll(properties);
    props.store(stream, comment);
}