Example usage for java.util Properties Properties

List of usage examples for java.util Properties Properties

Introduction

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

Prototype

public Properties() 

Source Link

Document

Creates an empty property list with no default values.

Usage

From source file:jp.mamesoft.mailsocketchat.Mailsocketchat.java

public static void main(String argv[]) {
    System.out.println("MailSocketChat Ver." + version);
    if (argv.length != 6) {
        System.out.println(//  w  w w .jav  a  2 s  .c  o m
                "ERROR! ? <?URL> <???> <GMail??> <GMail> <(Simple???Normal???All)> <????(Subject???Text)> ???????");
        System.exit(0);
    }

    TimerTask newversion = new NewVersion();
    Timer timer = new Timer();
    timer.schedule(newversion, 0, 6 * 60 * 60 * 1000); //6??????

    chat_url = argv[0];
    chat_name = argv[1];
    mail_user = argv[2];
    mail_pass = argv[3];

    if (argv[4].equals("Simple")) {
        logformat = "simple";
    } else if (argv[4].equals("Normal")) {
        logformat = "normal";
    } else if (argv[4].equals("All")) {
        logformat = "all";
    } else {
        System.out.println(
                "ERROR! (5)???????Simple???Normal???All???????");
        System.exit(0);
    }

    if (argv[5].equals("Subject")) {
        subjectname = true;
    } else if (argv[5].equals("Text")) {
        subjectname = false;
    } else {
        System.out.println(
                "ERROR! ????(6)???????Subject???Text???????");
        System.exit(0);
    }

    try {
        Properties headers = new Properties();
        headers.setProperty("user-agent", "MailSocketChat/" + version + " (" + osName + " " + osVer + ") Java/"
                + javaver + " (Mamesoft Web)");
        socket = new SocketIO(chat_url, headers);
        socket.connect(new IOCallback() {
            @Override
            public void onMessage(JSONObject json, IOAcknowledge ack) {
                try {
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onMessage(String data, IOAcknowledge ack) {
            }

            @Override
            public void onError(SocketIOException socketIOException) {
                System.out.println("??????");
                System.err.println(socketIOException);
                System.exit(0);
            }

            @Override
            public void onDisconnect() {
                System.out.println("???????");
                System.exit(0);
            }

            @Override
            public void onConnect() {
                socket.emit("register", new JSONObject().put("mode", "client").put("lastid", 1));
                System.out.println("SocketChat?????");
                Thread mail = new Mail();
                mail.start();
            }

            @Override
            public void on(String event, IOAcknowledge ack, Object... args) {
                if (event.equals("log")) {
                    JSONObject jsondata = (JSONObject) args[0];
                    Logperse(jsondata);
                }
                if (event.equals("init")) {
                    JSONObject jsondata = (JSONObject) args[0];
                    JSONArray logs = jsondata.getJSONArray("logs");
                    for (int i = logs.length() - 1; i >= 0; i--) {
                        JSONObject log = logs.getJSONObject(i);
                        Logperse(log);
                    }
                    socket.emit("inout", new JSONObject().put("name", chat_name));
                }
                if (event.equals("result")) {
                    JSONObject jsondata = (JSONObject) args[0];
                    System.out.println(jsondata);
                }
                if (event.equals("users")) {
                    JSONObject jsondata = (JSONObject) args[0];
                    JSONArray users = jsondata.getJSONArray("users");
                    for (int i = 0; i < users.length(); i++) {
                        JSONObject user = users.getJSONObject(i);
                        userchange(user);
                    }
                }
                if (event.equals("newuser")) {
                    JSONObject jsondata = (JSONObject) args[0];
                    userchange(jsondata);
                }
                if (event.equals("inout")) {
                    JSONObject jsondata = (JSONObject) args[0];
                    userchange(jsondata);
                }
                if (event.equals("deluser")) {
                    Integer id = (Integer) args[0];
                    if (users.containsKey(id)) {
                        users.remove(id);
                    }
                    if (roms.containsKey(id)) {
                        roms.remove(id);
                    }

                }
                if (event.equals("userinfo")) {
                    JSONObject jsondata = (JSONObject) args[0];
                    if (jsondata.getBoolean("rom")) {
                        in = false;
                    } else {
                        in = true;
                    }
                }
            }
        });

    } catch (MalformedURLException e1) {
        e1.printStackTrace();
        System.out.println("URL????????");
        return;
    }
}

From source file:eu.ensure.aging.AgingSimulator.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("n", "flip-bit-in-name", true, "Flip bit in first byte of name of first file");
    options.addOption("u", "flip-bit-in-uname", true, "Flip bit in first byte of username of first file");
    options.addOption("c", "update-checksum", true, "Update header checksum (after prior bit flips)");

    Properties properties = new Properties();
    CommandLineParser parser = new PosixParser();
    try {//from  w  ww .j a v  a  2s  .co m
        CommandLine line = parser.parse(options, args);

        //
        if (line.hasOption("flip-bit-in-name")) {
            properties.put("flip-bit-in-name", line.getOptionValue("flip-bit-in-name"));
        } else {
            // On by default (if not explicitly de-activated above)
            properties.put("flip-bit-in-name", "true");
        }

        //
        if (line.hasOption("flip-bit-in-uname")) {
            properties.put("flip-bit-in-uname", line.getOptionValue("flip-bit-in-uname"));
        } else {
            properties.put("flip-bit-in-uname", "false");
        }

        //
        if (line.hasOption("update-checksum")) {
            properties.put("update-checksum", line.getOptionValue("update-checksum"));
        } else {
            properties.put("update-checksum", "false");
        }

        String[] fileArgs = line.getArgs();

        if (fileArgs.length < 1) {
            printHelp(options, System.err);
            System.exit(1);
        }

        String srcPath = fileArgs[0];

        File srcAIP = new File(srcPath);
        if (!srcAIP.exists()) {
            String info = "The source path does not locate a file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        if (srcAIP.isDirectory()) {
            String info = "The source path locates a directory, not a file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        if (!srcAIP.canRead()) {
            String info = "Cannot read source file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        boolean doReplace = false;
        File destAIP = null;

        if (fileArgs.length > 1) {
            String destPath = fileArgs[1];
            destAIP = new File(destPath);

            if (destAIP.exists()) {
                String info = "The destination path locates an existing file: " + destPath;
                System.err.println(info);
                System.exit(1);
            }
        } else {
            doReplace = true;
            try {
                destAIP = File.createTempFile("tmp-aged-aip-", ".tar");
            } catch (IOException ioe) {
                String info = "Failed to create temporary file: ";
                info += ioe.getMessage();
                System.err.println(info);
                System.exit(1);
            }
        }

        String info = "Age simulation\n";
        info += "  Reading from " + srcAIP.getName() + "\n";
        if (doReplace) {
            info += "  and replacing it's content";
        } else {
            info += "  Writing to " + destAIP.getName();
        }
        System.out.println(info);

        //
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new BufferedInputStream(new FileInputStream(srcAIP));
            os = new BufferedOutputStream(new FileOutputStream(destAIP));

            simulateAging(srcAIP.getName(), is, os, properties);

        } catch (FileNotFoundException fnfe) {
            info = "Could not locate file: " + fnfe.getMessage();
            System.err.println(info);
        } finally {
            try {
                if (null != os)
                    os.close();
                if (null != is)
                    is.close();
            } catch (IOException ignore) {
            }
        }

        //
        if (doReplace) {
            File renamedOriginal = new File(srcAIP.getName() + "-backup");
            srcAIP.renameTo(renamedOriginal);

            ReadableByteChannel rbc = null;
            WritableByteChannel wbc = null;
            try {
                rbc = Channels.newChannel(new FileInputStream(destAIP));
                wbc = Channels.newChannel(new FileOutputStream(srcAIP));
                FileIO.fastChannelCopy(rbc, wbc);
            } catch (FileNotFoundException fnfe) {
                info = "Could not locate temporary output file: " + fnfe.getMessage();
                System.err.println(info);
            } catch (IOException ioe) {
                info = "Could not copy temporary output file over original AIP: " + ioe.getMessage();
                System.err.println(info);
            } finally {
                try {
                    if (null != wbc)
                        wbc.close();
                    if (null != rbc)
                        rbc.close();

                    destAIP.delete();
                } catch (IOException ignore) {
                }
            }
        }
    } catch (ParseException pe) {
        String info = "Failed to parse command line: " + pe.getMessage();
        System.err.println(info);
        printHelp(options, System.err);
        System.exit(1);
    }
}

From source file:com.heliosapm.streams.collector.ds.pool.impls.MQPCFPoolBuilder.java

public static void main(String[] args) {
    log("PCFMessageAgent Test");
    final Properties p = new Properties();
    p.setProperty(HOST_KEY, "localhost");
    p.setProperty(PORT_KEY, "1430");
    p.setProperty(CHANNEL_KEY, "JBOSS.SVRCONN");
    MQPCFPoolBuilder poolBuilder = new MQPCFPoolBuilder(p);
    log("Created");
    log("PCF_CTOR: [" + PCF_CTOR + "]");
    Object o = null;/*from  w  w w. j  a  va2  s .c o  m*/
    PooledObject<Object> pooledObject = null;
    try {
        o = poolBuilder.create();
        log("Created Object: [" + o + "]");
        pooledObject = new DefaultPooledObject<Object>(o);
        log("Validating Object....");
        poolBuilder.validateObject(pooledObject);
        //SystemClock.sleep(100000);

    } finally {
        if (pooledObject != null)
            try {
                poolBuilder.destroyObject(pooledObject);
            } catch (Exception x) {
            }
    }

}

From source file:com.amazonaws.services.iot.demo.danbo.rpi.Danbo.java

public static void main(String[] args) throws Exception {
    log.debug("starting");

    // uses pin 6 for the red Led
    final Led redLed = new Led(6);
    // uses pin 26 for the green Led
    final Led greenLed = new Led(26);

    // turns the red led on initially
    redLed.on();/*from   w ww.jav  a2  s.c o m*/

    // turns the green led off initially
    greenLed.off();

    // loads properties from danbo.properties file - make sure this file is
    // available on the pi's home directory
    InputStream input = new FileInputStream("/home/pi/danbo/danbo.properties");
    Properties properties = new Properties();
    properties.load(input);
    endpoint = properties.getProperty("awsiot.endpoint");
    rootCA = properties.getProperty("awsiot.rootCA");
    privateKey = properties.getProperty("awsiot.privateKey");
    certificate = properties.getProperty("awsiot.certificate");
    url = protocol + endpoint + ":" + port;

    log.debug("properties loaded");

    // turns off both eyes
    RGBLed rgbLed = new RGBLed("RGBLed1", Danbo.pinLayout1, Danbo.pinLayout2, new Color(0, 0, 0),
            new Color(0, 0, 0), 0, 100);
    new Thread(rgbLed).start();

    // resets servo to initial positon
    Servo servo = new Servo("Servo", 1);
    new Thread(servo).start();

    // gets the Pi serial number and uses it as part of the thing
    // registration name
    clientId = clientId + getSerialNumber();

    // AWS IoT things shadow topics
    updateTopic = "$aws/things/" + clientId + "/shadow/update";
    deltaTopic = "$aws/things/" + clientId + "/shadow/update/delta";
    rejectedTopic = "$aws/things/" + clientId + "/shadow/update/rejected";

    // AWS IoT controller things shadow topic (used to register new things)
    controllerUpdateTopic = "$aws/things/Controller/shadow/update";

    // defines an empty danbo shadow POJO
    final DanboShadow danboShadow = new DanboShadow();
    DanboShadow.State state = danboShadow.new State();
    final DanboShadow.State.Reported reported = state.new Reported();
    reported.setEyes("readyToBlink");
    reported.setHead("readyToMove");
    reported.setMouth("readyToSing");
    reported.setName(clientId);
    state.setReported(reported);
    danboShadow.setState(state);

    // defines an empty controller shadow POJO
    final ControllerShadow controllerShadow = new ControllerShadow();
    ControllerShadow.State controllerState = controllerShadow.new State();
    final ControllerShadow.State.Reported controllerReported = controllerState.new Reported();
    controllerReported.setThingName(clientId);
    controllerState.setReported(controllerReported);
    controllerShadow.setState(controllerState);

    try {
        log.debug("registering");

        // registers the thing (creates a new thing) by updating the
        // controller
        String message = gson.toJson(controllerShadow);
        MQTTPublisher controllerUpdatePublisher = new MQTTPublisher(controllerUpdateTopic, qos, message, url,
                clientId + "-controllerupdate" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                certificate);
        new Thread(controllerUpdatePublisher).start();

        log.debug("registered");

        // clears the thing status (in case the thing already existed)
        Danbo.deleteStatus("initialDelete");

        // creates an MQTT subscriber to the things shadow delta topic
        // (command execution notification)
        MQTTSubscriber deltaSubscriber = new MQTTSubscriber(new DanboShadowDeltaCallback(), deltaTopic, qos,
                url, clientId + "-delta" + rand.nextInt(100000), cleanSession, rootCA, privateKey, certificate);
        new Thread(deltaSubscriber).start();

        // creates an MQTT subscriber to the things shadow error topic
        MQTTSubscriber errorSubscriber = new MQTTSubscriber(new DanboShadowRejectedCallback(), rejectedTopic,
                qos, url, clientId + "-rejected" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                certificate);
        new Thread(errorSubscriber).start();

        // turns the red LED off
        redLed.off();

        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                // turns the green LED on
                greenLed.on();

                log.debug("running publish state thread");

                int temp = -300;
                int humid = -300;

                reported.setTemperature(new Integer(temp).toString());
                reported.setHumidity(new Integer(humid).toString());

                try {
                    // reads the temperature and humidity data
                    Set<Sensor> sensors = Sensors.getSensors();
                    log.debug(sensors.size());

                    for (Sensor sensor : sensors) {
                        log.debug(sensor.getPhysicalQuantity());
                        log.debug(sensor.getValue());
                        if (sensor.getPhysicalQuantity().toString().equals("Temperature")) {
                            temp = sensor.getValue().intValue();
                        }
                        if (sensor.getPhysicalQuantity().toString().equals("Humidity")) {
                            humid = sensor.getValue().intValue();
                        }
                    }

                    log.debug("temperature: " + temp);
                    log.debug("humidity: " + humid);
                    reported.setTemperature(new Integer(temp).toString());
                    reported.setHumidity(new Integer(humid).toString());
                } catch (Exception e) {
                    log.error("an error has ocurred: " + e.getMessage());
                    e.printStackTrace();
                }

                try {
                    // reports current state - last temperature and humidity
                    // read
                    String message = gson.toJson(danboShadow);
                    MQTTPublisher updatePublisher = new MQTTPublisher(updateTopic, qos, message, url,
                            clientId + "-update" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                            certificate);
                    new Thread(updatePublisher).start();
                } catch (Exception e) {
                    log.error("an error has ocurred: " + e.getMessage());
                    e.printStackTrace();
                }

                // turns the green LED off
                greenLed.off();
            }
        }, 0, 5, TimeUnit.SECONDS); // runs this thread every 5 seconds,
        // with an initial delay of 5 seconds
    } catch (MqttException me) {
        // Display full details of any exception that occurs
        log.error("reason " + me.getReasonCode());
        log.error("msg " + me.getMessage());
        log.error("loc " + me.getLocalizedMessage());
        log.error("cause " + me.getCause());
        log.error("excep " + me);
        me.printStackTrace();
    } catch (Throwable th) {
        log.error("msg " + th.getMessage());
        log.error("loc " + th.getLocalizedMessage());
        log.error("cause " + th.getCause());
        log.error("excep " + th);
        th.printStackTrace();
    }
}

From source file:net.ontopia.persistence.rdbms.CSVExport.java

public static void main(String[] argv) throws Exception {

    // Initialize logging
    CmdlineUtils.initializeLogging();/*from  w w w .  j ava  2s  .  c  o  m*/

    // Initialize command line option parser and listeners
    CmdlineOptions options = new CmdlineOptions("CSVExport", argv);
    OptionsListener ohandler = new OptionsListener();

    // Register local options
    options.addLong(ohandler, "separator", 's', true);

    // Register logging options
    CmdlineUtils.registerLoggingOptions(options);

    // Parse command line options
    try {
        options.parse();
    } catch (CmdlineOptions.OptionsException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    // Get command line arguments
    String[] args = options.getArguments();
    if (args.length < 3) {
        System.err.println("Error: wrong number of arguments.");
        usage();
        System.exit(1);
    }

    String dbprops = args[0];
    String table = args[1];
    String[] columns = StringUtils.split(args[2], ",");

    // Load property file
    Properties props = new Properties();
    props.load(new FileInputStream(dbprops));

    // Create database connection
    DefaultConnectionFactory cfactory = new DefaultConnectionFactory(props, true);
    Connection conn = cfactory.requestConnection();

    CSVExport ce = new CSVExport(conn);
    ce.setSeparator(ohandler.separator);
    //! ce.setUseQuotes(ohandler.usequotes);

    ce.exportCSV(new OutputStreamWriter(System.out), table, columns);
}

From source file:de.zazaz.iot.bosch.indego.util.IndegoMqttAdapter.java

public static void main(String[] args) {
    System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-normal.xml");

    Options options = new Options();

    StringBuilder commandList = new StringBuilder();
    for (DeviceCommand cmd : DeviceCommand.values()) {
        if (commandList.length() > 0) {
            commandList.append(", ");
        }//from  ww  w.j  a v a2 s.c o m
        commandList.append(cmd.toString());
    }

    options.addOption(Option //
            .builder("c") //
            .longOpt("config") //
            .desc("The configuration file to use") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("d") //
            .longOpt("debug") //
            .desc("Logs more details") //
            .build());
    options.addOption(Option //
            .builder("?") //
            .longOpt("help") //
            .desc("Prints this help") //
            .build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmds = null;
    try {
        cmds = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        System.err.println();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(IndegoMqttAdapter.class.getName(), options);
        System.exit(1);
        return;
    }

    if (cmds.hasOption("?")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CmdLineTool.class.getName(), options);
        return;
    }

    if (cmds.hasOption("d")) {
        System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-debug.xml");
    }

    String configFileName = cmds.getOptionValue('c');
    File configFile = new File(configFileName);

    if (!configFile.exists()) {
        System.err.println(String.format("The specified config file (%s) does not exist", configFileName));
        System.err.println();
        System.exit(2);
        return;
    }

    Properties properties = new Properties();
    try (InputStream in = new FileInputStream(configFile)) {
        properties.load(in);
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
        System.err.println(String.format("Was not able to load the properties file (%s)", configFileName));
        System.err.println();
    }

    MqttIndegoAdapterConfiguration config = new MqttIndegoAdapterConfiguration();
    config.setIndegoBaseUrl(properties.getProperty("indego.mqtt.device.base-url"));
    config.setIndegoUsername(properties.getProperty("indego.mqtt.device.username"));
    config.setIndegoPassword(properties.getProperty("indego.mqtt.device.password"));
    config.setMqttBroker(properties.getProperty("indego.mqtt.broker.connection"));
    config.setMqttClientId(properties.getProperty("indego.mqtt.broker.client-id"));
    config.setMqttUsername(properties.getProperty("indego.mqtt.broker.username"));
    config.setMqttPassword(properties.getProperty("indego.mqtt.broker.password"));
    config.setMqttTopicRoot(properties.getProperty("indego.mqtt.broker.topic-root"));
    config.setPollingIntervalMs(Integer.parseInt(properties.getProperty("indego.mqtt.polling-interval-ms")));

    MqttIndegoAdapter adapter = new MqttIndegoAdapter(config);
    adapter.startup();
}

From source file:de.zazaz.iot.bosch.indego.util.IndegoIftttAdapter.java

public static void main(String[] args) {
    System.setProperty("log4j.configurationFile", "log4j2-indegoIftttAdapter-normal.xml");

    Options options = new Options();

    StringBuilder commandList = new StringBuilder();
    for (DeviceCommand cmd : DeviceCommand.values()) {
        if (commandList.length() > 0) {
            commandList.append(", ");
        }//from   ww w . j a  va2s.co  m
        commandList.append(cmd.toString());
    }

    options.addOption(Option //
            .builder("c") //
            .longOpt("config") //
            .desc("The configuration file to use") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("d") //
            .longOpt("debug") //
            .desc("Logs more details") //
            .build());
    options.addOption(Option //
            .builder("?") //
            .longOpt("help") //
            .desc("Prints this help") //
            .build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmds = null;
    try {
        cmds = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        System.err.println();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(IndegoIftttAdapter.class.getName(), options);
        System.exit(1);
        return;
    }

    if (cmds.hasOption("?")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CmdLineTool.class.getName(), options);
        return;
    }

    if (cmds.hasOption("d")) {
        System.setProperty("log4j.configurationFile", "log4j2-indegoIftttAdapter-debug.xml");
    }

    String configFileName = cmds.getOptionValue('c');
    File configFile = new File(configFileName);

    if (!configFile.exists()) {
        System.err.println(String.format("The specified config file (%s) does not exist", configFileName));
        System.err.println();
        System.exit(2);
        return;
    }

    Properties properties = new Properties();
    try (InputStream in = new FileInputStream(configFile)) {
        properties.load(in);
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
        System.err.println(String.format("Was not able to load the properties file (%s)", configFileName));
        System.err.println();
    }

    IftttIndegoAdapterConfiguration config = new IftttIndegoAdapterConfiguration();
    config.setIftttMakerKey(properties.getProperty("indego.ifttt.maker.key"));
    config.setIftttIgnoreServerCertificate(
            Integer.parseInt(properties.getProperty("indego.ifttt.maker.ignore-server-certificate")) != 0);
    config.setIftttReceiverPort(Integer.parseInt(properties.getProperty("indego.ifttt.maker.receiver-port")));
    config.setIftttReceiverSecret(properties.getProperty("indego.ifttt.maker.receiver-secret"));
    config.setIftttOfflineEventName(properties.getProperty("indego.ifttt.maker.eventname-offline"));
    config.setIftttOnlineEventName(properties.getProperty("indego.ifttt.maker.eventname-online"));
    config.setIftttErrorEventName(properties.getProperty("indego.ifttt.maker.eventname-error"));
    config.setIftttErrorClearedEventName(properties.getProperty("indego.ifttt.maker.eventname-error-cleared"));
    config.setIftttStateChangeEventName(properties.getProperty("indego.ifttt.maker.eventname-state-change"));
    config.setIndegoBaseUrl(properties.getProperty("indego.ifttt.device.base-url"));
    config.setIndegoUsername(properties.getProperty("indego.ifttt.device.username"));
    config.setIndegoPassword(properties.getProperty("indego.ifttt.device.password"));
    config.setPollingIntervalMs(Integer.parseInt(properties.getProperty("indego.ifttt.polling-interval-ms")));

    IftttIndegoAdapter adapter = new IftttIndegoAdapter(config);
    adapter.startup();
}

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

/**
 * @param args//from www .  jav  a 2s  . c  o  m
 */
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.tu_dortmund.ub.data.dswarm.TaskProcessingUnit.java

public static void main(final String[] args) throws Exception {

    // default config
    String configFile = DEFAULT_CONF_FOLDER_NAME + File.separatorChar + DEFAULT_CONFIG_PROPERTIES_FILE_NAME;

    // read program parameters
    if (args.length > 0) {

        for (final String arg : args) {

            LOG.info("arg = " + arg);

            if (arg.startsWith("-conf=")) {

                configFile = arg.split("=")[1];
            }//  w w w .j  a  va 2s  .c  o m
        }
    }

    final Properties config;

    // Init properties
    try {

        try (final InputStream inputStream = new FileInputStream(configFile)) {

            try (final BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream, TPUUtil.UTF_8))) {

                config = new Properties();
                config.load(reader);
            }
        }
    } catch (final IOException e) {

        LOG.error("something went wrong", e);
        LOG.error(String.format("FATAL ERROR: Could not read '%s'!", configFile));

        throw e;
    }

    startTPU(configFile, config);
}

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

/**
 * @param args/*from   ww w . j  a  v a 2 s.  co  m*/
 */
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));
    }
}