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:com.dtolabs.rundeck.ec2.NodeGenerator.java

public static void main(final String[] args) throws IOException, GeneratorException {
    File outfile = null;/*  ww  w  . j a  v a 2s .com*/

    //load generator mapping
    if (args.length < 2) {
        System.err.println(
                "usage: <credentials.properties> <endpoint> [mapping.properties] [outfile] [query parameters, \"a=b\" ...]");
        System.err.println(
                "\t optional arguments can be replaced by \"-\" to use the default, and then query parameters appended");
        System.exit(2);
    }

    final InputStream stream = new FileInputStream(args[0]);
    final String endPoint = args[1];
    final AWSCredentials credentials = new PropertiesCredentials(stream);

    Properties mapping = new Properties();
    if (args.length > 2 && !"-".equals(args[2])) {
        mapping.load(new FileInputStream(args[2]));
    } else {
        mapping.load(NodeGenerator.class.getClassLoader().getResourceAsStream("simplemapping.properties"));
    }

    final ResourceXMLGenerator gen;
    if (args.length > 3 && !"-".equals(args[3])) {
        outfile = new File(args[3]);
        gen = new ResourceXMLGenerator(outfile);
    } else {
        //use stdout
        gen = new ResourceXMLGenerator(System.out);
    }
    ArrayList<String> params = new ArrayList<String>();
    if (args.length > 4) {
        for (int i = 4; i < args.length; i++) {
            params.add(args[i]);
        }
    }

    Set<Instance> instances = performQuery(credentials, endPoint, params);

    for (final Instance inst : instances) {
        final INodeEntry iNodeEntry = instanceToNode(inst, mapping);
        if (null != iNodeEntry) {
            gen.addNode(iNodeEntry);
        }
    }
    gen.generate();
    //
    if (null != outfile) {
        System.out.println("XML Stored: " + outfile.getAbsolutePath());
    }
}

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 .  j  a v  a2 s  . c  om

    // 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:dashboard.ImportCDN.java

public static void main(String[] args)

{
    int n = 0;/*from   w  w w.  j a  v a2s.  c  o  m*/
    String propertiesFileName = "";

    // First argument - number of events to import
    if (args.length > 0) {
        try {
            n = Integer.parseInt(args[0]);
        } catch (NumberFormatException e) {
            System.err.println("First argument must be an integer");
            System.exit(1);
        }
    } else {
        System.err.println("Please specify number of events to import.");
        System.exit(1);
    }

    // Second argument - properties file name
    if (args.length > 1)
        propertiesFileName = args[1];
    else
        propertiesFileName = "gigaDashboard.properties";

    // Read Properties file
    Properties prop = new Properties();

    try {
        //load a properties file
        prop.load(new FileInputStream(propertiesFileName));

        // Another option - load default properties from the Jar
        //prop.load(ImportCDN.class.getResourceAsStream("/gigaDashboard.properties"));

        //get the property values
        TOKEN = prop.getProperty("MIXPANEL_GIGA_PROJECT_TOKEN");
        API_KEY = prop.getProperty("MIXPANEL_GIGA_API_KEY");
        bucketName = prop.getProperty("S3_BUCKET_NAME");
        AWS_USER = prop.getProperty("AWS_USER");
        AWS_PASS = prop.getProperty("AWS_PASS");
        DELETE_PROCESSED_LOGS = prop.getProperty("DELETE_PROCESSED_LOGS");

        //System.out.println("MIXPANEL PROJECT TOKEN = " + TOKEN);
        //System.out.println("MIXPANEL API KEY = " + API_KEY);
        System.out.println("DELETE_PROCESSED_LOGS = " + DELETE_PROCESSED_LOGS);
        System.out.println("S3_BUCKET_NAME = " + prop.getProperty("S3_BUCKET_NAME"));
        //System.out.println("AWS_USER = " + prop.getProperty("AWS_USER"));
        //System.out.println("AWS_PASS = " + prop.getProperty("AWS_PASS"));

        System.out.println("===================");
    } catch (IOException ex) {
        //ex.printStackTrace();
        System.err.println("Can't find Propertie file - " + propertiesFileName);
        System.err.println("Second argument must be properties file name");
        System.exit(1);
    }

    try {
        System.out.println("\n>>> Starting to import " + n + " events... \n");
        readAmazonLogs(n);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.edgenius.wiki.installation.SilenceInstall.java

public static void main(String[] args) throws FileNotFoundException, IOException, NumberFormatException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    if (args.length != 1) {
        System.out.println("Usage: SilenceInstall silence-install.properites");
        System.exit(1);/*from   ww  w.  ja va  2s.c om*/
        return;
    }
    if (!(new File(args[0]).exists())) {
        System.out.println("Given silence-install.properites not found: [" + args[0] + "]");
        System.exit(1);
        return;
    }
    SilenceInstall silence = new SilenceInstall();
    Properties prop = new Properties();
    prop.load(new FileInputStream(args[0]));

    log.info("Silence installation starting... on properties: {}", args[0]);

    if (Boolean.parseBoolean(getProperty(prop, "data.root.in.system.property"))) {
        System.setProperty(DataRoot.rootKey, getProperty(prop, "data.root"));
        log.info("Date root is set to System Properties {}", getProperty(prop, "data.root"));
    }
    try {
        Field[] flds = Class.forName(Server.class.getName()).getDeclaredFields();
        for (Field field : flds) {
            serverFields.add(field.getName());
        }
        flds = Class.forName(GlobalSetting.class.getName()).getDeclaredFields();
        for (Field field : flds) {
            globalFields.add(field.getName());
        }
        flds = Class.forName(Installation.class.getName()).getDeclaredFields();
        for (Field field : flds) {
            installFields.add(field.getName());
        }
    } catch (Exception e) {
        log.error("Load fields name failed", e);
        System.exit(1);
    }

    boolean succ = silence.createDataRoot(getProperty(prop, "data.root"));
    if (!succ) {
        log.error("Unable to complete create data root");
        return;
    }
    //detect if Install.xml exist and if it is already installed.
    File installFile = FileUtil.getFile(DataRoot.getDataRoot() + Installation.FILE);
    if (installFile.exists()) {
        Installation install = Installation.refreshInstallation();
        if (Installation.STATUS_COMPLETED.equals(install.getStatus())) {
            log.info("GeniusWiki is already installed, exit this installation.");
            System.exit(0);
        }
    }

    //load Server.properties, Global.xml and Installation.properties
    Server server = new Server();
    Properties serverProp = FileUtil.loadProperties(Server.FILE_DEFAULT);
    server.syncFrom(serverProp);
    GlobalSetting global = GlobalSetting
            .loadGlobalSetting(FileUtil.getFileInputStream(Global.DEFAULT_GLOBAL_XML));
    Installation install = Installation.loadDefault();

    //sync values from silence-install.properites
    silence.sync(prop, server, global, install);

    //install....
    succ = silence.setupDataRoot(server, global, install);
    if (!succ) {
        log.error("Unable to complete save configuration files to data root");
        return;
    }

    if (Boolean.parseBoolean(getProperty(prop, "create.database"))) {
        succ = silence.createDatabase(server, getProperty(prop, "database.root.username"),
                getProperty(prop, "database.root.password"));
        if (!succ) {
            log.error("Unable to complete create database");
            return;
        }
    }

    succ = silence.createTable(server);
    if (!succ) {
        log.error("Unable to complete create tables");
        return;
    }
    succ = silence.createAdministrator(server, getProperty(prop, "admin.fullname"),
            getProperty(prop, "admin.username"), getProperty(prop, "admin.password"),
            getProperty(prop, "admin.email"));
    if (!succ) {
        log.error("Unable to complete create administrator");
        return;
    }

    log.info("Silence installation completed successfully.");
}

From source file:edu.umd.cs.submit.CommandLineSubmit.java

public static void main(String[] args) {
    try {/*from  www  .  j  ava2  s .  co  m*/
        Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        File home = args.length > 0 ? new File(args[0]) : new File(".");

        Protocol.registerProtocol("easyhttps", easyhttps);
        File submitFile = new File(home, ".submit");
        File submitUserFile = new File(home, ".submitUser");
        File submitIgnoreFile = new File(home, ".submitIgnore");
        File cvsIgnoreFile = new File(home, ".cvsignore");

        if (!submitFile.canRead()) {
            System.out.println("Must perform submit from a directory containing a \".submit\" file");
            System.out.println("No such file found at " + submitFile.getCanonicalPath());
            System.exit(1);
        }

        Properties p = new Properties();
        p.load(new FileInputStream(submitFile));
        String submitURL = p.getProperty("submitURL");
        if (submitURL == null) {
            System.out.println(".submit file does not contain a submitURL");
            System.exit(1);
        }
        String courseName = p.getProperty("courseName");
        String courseKey = p.getProperty("courseKey");
        String semester = p.getProperty("semester");
        String projectNumber = p.getProperty("projectNumber");
        String authenticationType = p.getProperty("authentication.type");
        String baseURL = p.getProperty("baseURL");

        System.out.println("Submitting contents of " + home.getCanonicalPath());
        System.out.println(" as project " + projectNumber + " for course " + courseName);
        FilesToIgnore ignorePatterns = new FilesToIgnore();
        addIgnoredPatternsFromFile(cvsIgnoreFile, ignorePatterns);
        addIgnoredPatternsFromFile(submitIgnoreFile, ignorePatterns);

        FindAllFiles find = new FindAllFiles(home, ignorePatterns.getPattern());
        Collection<File> files = find.getAllFiles();

        boolean createdSubmitUser = false;
        Properties userProps = new Properties();
        if (submitUserFile.canRead()) {
            userProps.load(new FileInputStream(submitUserFile));
        }
        if (userProps.getProperty("cvsAccount") == null && userProps.getProperty("classAccount") == null
                || userProps.getProperty("oneTimePassword") == null) {
            System.out.println();
            System.out.println(
                    "We need to authenticate you and create a .submitUser file so you can submit your project");

            createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL);
            createdSubmitUser = true;
            userProps.load(new FileInputStream(submitUserFile));
        }

        MultipartPostMethod filePost = createFilePost(p, find, files, userProps);
        HttpClient client = new HttpClient();
        client.setConnectionTimeout(HTTP_TIMEOUT);
        int status = client.executeMethod(filePost);
        System.out.println(filePost.getResponseBodyAsString());
        if (status == 500 && !createdSubmitUser) {
            System.out.println("Let's try reauthenticating you");
            System.out.println();

            createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL);
            userProps.load(new FileInputStream(submitUserFile));
            filePost = createFilePost(p, find, files, userProps);
            client = new HttpClient();
            client.setConnectionTimeout(HTTP_TIMEOUT);
            status = client.executeMethod(filePost);
            System.out.println(filePost.getResponseBodyAsString());
        }
        if (status != HttpStatus.SC_OK) {
            System.out.println("Status code: " + status);
            System.exit(1);
        }
        System.out.println("Submission accepted");
    } catch (Exception e) {
        System.out.println();
        System.out.println("An Error has occured during submission!");
        System.out.println();
        System.out.println("[DETAILS]");
        System.out.println(e.getMessage());
        e.printStackTrace(System.out);
        System.out.println();
    }
}

From source file:POP3Mail.java

public static void main(String[] args) {
    try {//from   w w w.  j a v a2 s .  c  o  m
        LogManager.getLogManager().readConfiguration(new FileInputStream("logging.properties"));
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    String server = null;
    String username = null;
    String password = null;
    if (new File("mail.properties").exists()) {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(new File("mail.properties")));
            server = properties.getProperty("server");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            ArrayList<String> list = new ArrayList<String>(
                    Arrays.asList(new String[] { server, username, password }));
            list.addAll(Arrays.asList(args));
            args = list.toArray(new String[list.size()]);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    if (args.length < 3) {
        System.err
                .println("Usage: POP3Mail <pop3 server hostname> <username> <password> [TLS [true=implicit]]");
        System.exit(1);
    }

    server = args[0];
    username = args[1];
    password = args[2];
    String proto = null;
    int messageid = -1;
    boolean implicit = false;
    for (int i = 3; i < args.length; ++i) {
        if (args[i].equals("-m")) {
            i += 1;
            messageid = Integer.parseInt(args[i]);
        }
    }

    // String proto = args.length > 3 ? args[3] : null;
    // boolean implicit = args.length > 4 ? Boolean.parseBoolean(args[4])
    // : false;

    POP3Client pop3;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        pop3 = new POP3SClient(proto, implicit);
    } else {
        pop3 = new POP3Client();
    }
    pop3.setDefaultPort(110);
    System.out.println("Connecting to server " + server + " on " + pop3.getDefaultPort());

    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);
    // suppress login details
    pop3.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        pop3.connect(server);
    } catch (IOException e) {
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        if (!pop3.login(username, password)) {
            System.err.println("Could not login to server.  Check password.");
            pop3.disconnect();
            System.exit(1);
        }
        PrintWriter printWriter = new PrintWriter(new FileWriter("messages.csv"), true);
        POP3MessageInfo[] messages = null;
        POP3MessageInfo[] identifiers = null;
        if (messageid == -1) {
            messages = pop3.listMessages();
            identifiers = pop3.listUniqueIdentifiers();
        } else {
            messages = new POP3MessageInfo[] { pop3.listMessage(messageid) };
        }
        if (messages == null) {
            System.err.println("Could not retrieve message list.");
            pop3.disconnect();
            return;
        } else if (messages.length == 0) {
            System.out.println("No messages");
            pop3.logout();
            pop3.disconnect();
            return;
        }
        new File("../json").mkdirs();
        int count = 0;
        for (POP3MessageInfo msginfo : messages) {
            if (msginfo.number != identifiers[count].number) {
                throw new RuntimeException();
            }
            msginfo.identifier = identifiers[count].identifier;
            BufferedReader reader = (BufferedReader) pop3.retrieveMessageTop(msginfo.number, 0);
            ++count;
            if (count % 100 == 0) {
                logger.finest(String.format("%d %s", msginfo.number, msginfo.identifier));
            }
            System.out.println(String.format("%d %s", msginfo.number, msginfo.identifier));
            if (reader == null) {
                System.err.println("Could not retrieve message header.");
                pop3.disconnect();
                System.exit(1);
            }
            if (printMessageInfo(reader, msginfo.number, printWriter)) {
            }
        }
        printWriter.close();
        pop3.logout();
        pop3.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
}

From source file:com.jivesoftware.os.routing.bird.deployable.config.extractor.ConfigExtractor.java

public static void main(String[] args) {
    String configHost = args[0];//from  ww  w . j a  va  2  s . co  m
    String configPort = args[1];
    String instanceKey = args[2];
    String instanceVersion = args[3];
    String setPath = args[4];
    String getPath = args[5];

    HttpRequestHelper buildRequestHelper = buildRequestHelper(null, configHost, Integer.parseInt(configPort));

    try {
        Set<URL> packages = new HashSet<>();
        for (int i = 5; i < args.length; i++) {
            packages.addAll(ClasspathHelper.forPackage(args[i]));
        }

        Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(packages)
                .setScanners(new SubTypesScanner(), new TypesScanner()));

        Set<Class<? extends Config>> subTypesOf = reflections.getSubTypesOf(Config.class);

        File configDir = new File("./config");
        configDir.mkdirs();

        Set<Class<? extends Config>> serviceConfig = new HashSet<>();
        Set<Class<? extends Config>> healthConfig = new HashSet<>();
        for (Class<? extends Config> type : subTypesOf) {
            if (HealthCheckConfig.class.isAssignableFrom(type)) {
                healthConfig.add(type);
            } else {
                serviceConfig.add(type);
            }
        }

        Map<String, String> defaultServiceConfig = extractAndPublish(serviceConfig,
                new File(configDir, "default-service-config.properties"), "default", instanceKey,
                instanceVersion, buildRequestHelper, setPath);

        DeployableConfig getServiceOverrides = new DeployableConfig("override", instanceKey, instanceVersion,
                defaultServiceConfig);
        DeployableConfig gotSerivceConfig = buildRequestHelper.executeRequest(getServiceOverrides, getPath,
                DeployableConfig.class, null);
        if (gotSerivceConfig == null) {
            System.out.println("Failed to publish default service config for " + Arrays.deepToString(args));
        } else {
            Properties override = createKeySortedProperties();
            override.putAll(gotSerivceConfig.properties);
            override.store(new FileOutputStream("config/override-service-config.properties"), "");
        }

        Map<String, String> defaultHealthConfig = extractAndPublish(healthConfig,
                new File(configDir, "default-health-config.properties"), "default-health", instanceKey,
                instanceVersion, buildRequestHelper, setPath);

        DeployableConfig getHealthOverrides = new DeployableConfig("override-health", instanceKey,
                instanceVersion, defaultHealthConfig);
        DeployableConfig gotHealthConfig = buildRequestHelper.executeRequest(getHealthOverrides, getPath,
                DeployableConfig.class, null);
        if (gotHealthConfig == null) {
            System.out.println("Failed to publish default health config for " + Arrays.deepToString(args));
        } else {
            Properties override = createKeySortedProperties();
            override.putAll(gotHealthConfig.properties);
            override.store(new FileOutputStream("config/override-health-config.properties"), "");
        }

        Properties instanceProperties = createKeySortedProperties();
        File configFile = new File("config/instance.properties");
        if (configFile.exists()) {
            instanceProperties.load(new FileInputStream(configFile));
        }

        Properties serviceOverrideProperties = createKeySortedProperties();
        configFile = new File("config/override-service-config.properties");
        if (configFile.exists()) {
            serviceOverrideProperties.load(new FileInputStream(configFile));
        }

        Properties healthOverrideProperties = createKeySortedProperties();
        configFile = new File("config/override-health-config.properties");
        if (configFile.exists()) {
            healthOverrideProperties.load(new FileInputStream(configFile));
        }

        Properties properties = createKeySortedProperties();
        properties.putAll(defaultServiceConfig);
        properties.putAll(defaultHealthConfig);
        properties.putAll(serviceOverrideProperties);
        properties.putAll(healthOverrideProperties);
        properties.putAll(instanceProperties);
        properties.store(new FileOutputStream("config/config.properties"), "");

        System.exit(0);
    } catch (Exception x) {
        x.printStackTrace();
        System.exit(1);
    }

}

From source file:com.adobe.aem.demomachine.Updates.java

public static void main(String[] args) {

    String rootFolder = null;/*from ww w .  j  av a2 s  .  co m*/

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Demo Machine root folder");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {
            rootFolder = cmd.getOptionValue("f");
        }

    } catch (Exception e) {
        System.exit(-1);
    }

    Properties md5properties = new Properties();

    try {
        URL url = new URL(
                "https://raw.githubusercontent.com/Adobe-Marketing-Cloud/aem-demo-machine/master/conf/checksums.properties");
        InputStream in = url.openStream();
        Reader reader = new InputStreamReader(in, "UTF-8");
        md5properties.load(reader);
        reader.close();
    } catch (Exception e) {
        System.out.println("Error: Cannot connect to GitHub.com to check for updates");
        System.exit(-1);
    }

    System.out.println(AemDemoConstants.HR);

    int nbUpdateAvailable = 0;

    List<String[]> listPaths = Arrays.asList(AemDemoConstants.demoPaths);
    for (String[] path : listPaths) {
        if (path.length == 5) {
            logger.debug(path[1]);
            File pathFolder = new File(rootFolder + (path[1].length() > 0 ? (File.separator + path[1]) : ""));
            if (pathFolder.exists()) {
                String newMd5 = AemDemoUtils.calcMD5HashForDir(pathFolder, Boolean.parseBoolean(path[3]),
                        false);
                logger.debug("MD5 is: " + newMd5);
                String oldMd5 = md5properties.getProperty("demo.md5." + path[0]);
                if (oldMd5 == null || oldMd5.length() == 0) {
                    logger.error("Cannot find MD5 for " + path[0]);
                    System.out.println(path[2] + " : Cannot find M5 checksum");
                    continue;
                }
                if (newMd5.equals(oldMd5)) {
                    continue;
                } else {
                    System.out.println(path[2] + " : New update available"
                            + (path[0].equals("0") ? " (use 'git pull' to get the latest changes)" : ""));
                    nbUpdateAvailable++;
                }
            } else {
                System.out.println(path[2] + " : Not installed");
            }
        }
    }

    if (nbUpdateAvailable == 0) {
        System.out.println("Your AEM Demo Machine is up to date!");
    }

    System.out.println(AemDemoConstants.HR);

}

From source file:com.marklogic.client.tutorial.util.Bootstrapper.java

/**
 * Command-line invocation./*from  w  w w.j  a v a  2  s .c  o  m*/
 * @param args   command-line arguments specifying the configuration and REST server
 */
public static void main(String[] args)
        throws ClientProtocolException, IOException, XMLStreamException, FactoryConfigurationError {
    Properties properties = new Properties();
    for (int i = 0; i < args.length; i++) {
        String name = args[i];
        if (name.startsWith("-") && name.length() > 1 && ++i < args.length) {
            name = name.substring(1);
            if ("properties".equals(name)) {
                InputStream propsStream = Bootstrapper.class.getClassLoader().getResourceAsStream(name);
                if (propsStream == null)
                    throw new IOException("Could not read bootstrapper properties");
                Properties props = new Properties();
                props.load(propsStream);
                props.putAll(properties);
                properties = props;
            } else {
                properties.put(name, args[i]);
            }
        } else {
            System.err.println("invalid argument: " + name);
            System.err.println(getUsage());
            System.exit(1);
        }
    }

    String invalid = joinList(listInvalidKeys(properties));
    if (invalid != null && invalid.length() > 0) {
        System.err.println("invalid arguments: " + invalid);
        System.err.println(getUsage());
        System.exit(1);
    }

    new Bootstrapper().makeServer(properties);

    System.out.println("Created " + properties.getProperty("restserver") + " server on "
            + properties.getProperty("restport") + " port for " + properties.getProperty("restdb")
            + " database");
}

From source file:com.marklogic.client.example.util.Bootstrapper.java

/**
 * Command-line invocation.//from  w ww.ja  v a  2  s.c  om
 * @param args   command-line arguments specifying the configuration and REST server
 */
public static void main(String[] args) throws ClientProtocolException, IOException, FactoryConfigurationError {
    Properties properties = new Properties();
    for (int i = 0; i < args.length; i++) {
        String name = args[i];
        if (name.startsWith("-") && name.length() > 1 && ++i < args.length) {
            name = name.substring(1);
            if ("properties".equals(name)) {
                InputStream propsStream = Bootstrapper.class.getClassLoader().getResourceAsStream(name);
                if (propsStream == null)
                    throw new IOException("Could not read bootstrapper properties");
                Properties props = new Properties();
                props.load(propsStream);
                props.putAll(properties);
                properties = props;
            } else {
                properties.put(name, args[i]);
            }
        } else {
            System.err.println("invalid argument: " + name);
            System.err.println(getUsage());
            System.exit(1);
        }
    }

    String invalid = joinList(listInvalidKeys(properties));
    if (invalid != null && invalid.length() > 0) {
        System.err.println("invalid arguments: " + invalid);
        System.err.println(getUsage());
        System.exit(1);
    }

    // TODO: catch invalid argument exceptions and provide feedback
    new Bootstrapper().makeServer(properties);

    System.out.println("Created " + properties.getProperty("restserver") + " server on "
            + properties.getProperty("restport") + " port for " + properties.getProperty("restdb")
            + " database");
}