Example usage for java.lang System getProperty

List of usage examples for java.lang System getProperty

Introduction

In this page you can find the example usage for java.lang System getProperty.

Prototype

public static String getProperty(String key) 

Source Link

Document

Gets the system property indicated by the specified key.

Usage

From source file:com.revo.deployr.client.example.data.io.auth.stateful.exec.MultipleDataInMultipleDataOut.java

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

    RClient rClient = null;//from w  ww  .  j  a v  a2s.com
    RProject rProject = null;

    try {

        /*
         * Determine DeployR server endpoint.
         */
        String endpoint = System.getProperty("endpoint");
        log.info("[ CONFIGURATION  ] Using endpoint=" + endpoint);

        /*
         * Establish RClient connection to DeployR server.
         *
         * An RClient connection is the mandatory starting
         * point for any application using the client library.
         */
        rClient = RClientFactory.createClient(endpoint);

        log.info("[   CONNECTION   ] Established anonymous " + "connection [ RClient ].");

        /*
         * Build a basic authentication token.
         */
        RAuthentication rAuth = new RBasicAuthentication(System.getProperty("username"),
                System.getProperty("password"));

        /*
         * Establish an authenticated handle with the DeployR
         * server, rUser. Following this call the rClient 
         * connection is operating as an authenticated connection
         * and all calls on rClient inherit the access permissions
         * of the authenticated user, rUser.
         */
        RUser rUser = rClient.login(rAuth);
        log.info("[ AUTHENTICATION ] Upgraded to authenticated " + "connection [ RUser ].");

        /*
         * Create a temporary project (R session).
         *
         * Optionally:
         * ProjectCreationOptions options =
         * new ProjectCreationOptions();
         *
         * Populate options as needed, then:
         *
         * rProject = rUser.createProject(options);
         */
        rProject = rUser.createProject();

        log.info("[  GO STATEFUL   ] Created stateful temporary " + "R session [ RProject ].");

        /*
         * Create a ProjectExecutionOptions instance
         * to specify data inputs and output to the
         * execution of the repository-managed R script.
         *
         * This options object can be used to pass standard
         * execution model parameters on execution calls. All
         * fields are optional.
         *
         * See the Standard Execution Model chapter in the
         * Client Library Tutorial on the DeployR website for
         * further details.
         */
        ProjectExecutionOptions options = new ProjectExecutionOptions();

        /*
         * MultipleDataInMultipleDataOut Example Note:
         * 
         * The inputs sent on this example are contrived
         * and superfluous as the hipStar.rData binary R
         * object input and the hipStarUrl input perform
         * the exact same purpose...to load the Hip STAR
         * dataset into the workspace ahead of execution.
         * 
         * The example is provided to simply demonstrate
         * the mechanism of specifying multiple inputs.
         */

        /* 
         * Preload from the DeployR repository the following
         * binary R object input file:
         * /testuser/example-data-io/hipStar.rData
         */
        ProjectPreloadOptions preloadWorkspace = new ProjectPreloadOptions();
        preloadWorkspace.filename = "hipStar.rData";
        preloadWorkspace.directory = "example-data-io";
        preloadWorkspace.author = "testuser";
        options.preloadWorkspace = preloadWorkspace;

        log.info("[   DATA INPUT   ] Repository binary file input "
                + "set on execution, [ ProjectExecutionOptions.preloadWorkspace ].");

        /* 
         * Load an R object literal "hipStarUrl" into the
         * workspace prior to script execution.
         *
         * The R script checks for the existence of "hipStarUrl"
         * in the workspace and if present uses the URL path
         * to load the Hipparcos star dataset from the DAT file
         * at that location.
         */
        RData hipStarUrl = RDataFactory.createString("hipStarUrl", HIP_DAT_URL);
        List<RData> rinputs = Arrays.asList(hipStarUrl);
        options.rinputs = rinputs;

        log.info("[   DATA INPUT   ] External data source input "
                + "set on execution, [ ProjectExecutionOptions.rinputs ].");

        /*
         * Request the retrieval of the "hip" data.frame and
         * two vector objects from the workspace following the
         * execution. The corresponding R objects are named as
         * follows:
         * 'hip', hipDim', 'hipNames'.
         */
        options.routputs = Arrays.asList("hip", "hipDim", "hipNames");

        log.info("[  EXEC OPTION   ] DeployR-encoded R object request "
                + "set on execution [ ProjectExecutionOptions.routputs ].");

        /*
         * Execute a public analytics Web service as an authenticated
         * user based on a repository-managed R script:
         * /testuser/example-data-io/dataIO.R
         */
        RProjectExecution exec = rProject.executeScript("dataIO.R", "example-data-io", "testuser", null,
                options);

        log.info("[   EXECUTION    ] Stateful R script " + "execution completed [ RProjectExecution ].");

        /*
         * Retrieve multiple outputs following the execution:
         *
         * 1. R console output.
         * 2. R console output.
         * 3. R console output.
         * 4. R console output.
         * 5. R console output.
         */

        String console = exec.about().console;
        log.info("[  DATA OUTPUT   ] Retrieved R console " + "output [ String ].");

        /*
         * Retrieve the requested R object data encodings from
         * the workspace follwing the script execution. 
         *
         * See the R Object Data Decoding chapter in the
         * Client Library Tutorial on the DeployR website for
         * further details.
         */
        List<RData> objects = exec.about().workspaceObjects;

        for (RData rData : objects) {
            if (rData instanceof RDataFrame) {
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object output " + rData.getName()
                        + " [ RDataFrame ].");
                List<RData> hipSubsetVal = ((RDataFrame) rData).getValue();
            } else if (rData instanceof RNumericVector) {
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object output " + rData.getName()
                        + " [ RNumericVector ].");
                List<Double> hipDimVal = ((RNumericVector) rData).getValue();
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object " + rData.getName()
                        + " value=" + hipDimVal);
            } else if (rData instanceof RStringVector) {
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object output " + rData.getName()
                        + " [ RStringVector ].");
                List<String> hipNamesVal = ((RStringVector) rData).getValue();
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object " + rData.getName()
                        + " value=" + hipNamesVal);
            } else {
                log.info("Unexpected DeployR-encoded R object returned, " + "object name=" + rData.getName()
                        + ", encoding=" + rData.getClass());
            }
        }

        /*
         * Retrieve the working directory files (artifact)
         * was generated by the execution.
         */
        List<RProjectFile> wdFiles = exec.about().artifacts;

        for (RProjectFile wdFile : wdFiles) {
            log.info("[  DATA OUTPUT   ] Retrieved working directory " + "file output "
                    + wdFile.about().filename + " [ RProjectFile ].");
            InputStream fis = null;
            try {
                fis = wdFile.download();
            } catch (Exception ex) {
                log.warn("Working directory binary file download " + ex);
            } finally {
                IOUtils.closeQuietly(fis);
            }
        }

        /*
         * Retrieve R graphics device plots (results) called
         * unnamedplot*.png that was generated by the execution.
         */
        List<RProjectResult> results = exec.about().results;

        for (RProjectResult result : results) {
            log.info("[  DATA OUTPUT   ] Retrieved graphics device " + "plot output " + result.about().filename
                    + " [ RProjectResult ].");
            InputStream fis = null;
            try {
                fis = result.download();
            } catch (Exception ex) {
                log.warn("Graphics device plot download " + ex);
            } finally {
                IOUtils.closeQuietly(fis);
            }
        }

    } catch (Exception ex) {
        log.warn("Unexpected runtime exception=" + ex);
    } finally {
        try {
            if (rProject != null) {
                /*
                 * Close rProject before application exits.
                 */
                rProject.close();
            }
        } catch (Exception fex) {
        }
        try {
            if (rClient != null) {
                /*
                 * Release rClient connection before application exits.
                 */
                rClient.release();
            }
        } catch (Exception fex) {
        }
    }

}

From source file:com.revo.deployr.client.example.data.io.auth.stateful.preload.MultipleDataInMultipleDataOut.java

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

    RClient rClient = null;//from  w ww . ja v a  2  s.  c  om
    RProject rProject = null;

    try {

        /*
         * Determine DeployR server endpoint.
         */
        String endpoint = System.getProperty("endpoint");
        log.info("[ CONFIGURATION  ] Using endpoint=" + endpoint);

        /*
         * Establish RClient connection to DeployR server.
         *
         * An RClient connection is the mandatory starting
         * point for any application using the client library.
         */
        rClient = RClientFactory.createClient(endpoint);

        log.info("[   CONNECTION   ] Established anonymous " + "connection [ RClient ].");

        /*
         * Build a basic authentication token.
         */
        RAuthentication rAuth = new RBasicAuthentication(System.getProperty("username"),
                System.getProperty("password"));

        /*
         * Establish an authenticated handle with the DeployR
         * server, rUser. Following this call the rClient 
         * connection is operating as an authenticated connection
         * and all calls on rClient inherit the access permissions
         * of the authenticated user, rUser.
         */
        RUser rUser = rClient.login(rAuth);
        log.info("[ AUTHENTICATION ] Upgraded to authenticated " + "connection [ RUser ].");

        /*
         * Create a ProjectCreationOptions instance
         * to specify data inputs that "pre-heat" the R session
         * workspace or working directory for your project.
         */
        ProjectCreationOptions creationOpts = new ProjectCreationOptions();

        /*
         * MultipleDataInMultipleDataOut Example Note:
         * 
         * The preload inputs sent on this example are
         * contrived and superfluous as the hipStar.rData
         * binary R object input and the hipStarUrl input
         * perform the exact same purpose...to load the Hip STAR
         * dataset into the workspace at project initialization.
         * 
         * The example is provided to simply demonstrate
         * the mechanism of specifying multiple preload inputs.
         */

        /* 
         * Preload from the DeployR repository the following
         * binary R object input file:
         * /testuser/example-data-io/hipStar.rData
         */
        ProjectPreloadOptions preloadWorkspace = new ProjectPreloadOptions();
        preloadWorkspace.filename = "hipStar.rData";
        preloadWorkspace.directory = "example-data-io";
        preloadWorkspace.author = "testuser";
        creationOpts.preloadWorkspace = preloadWorkspace;

        log.info("[ PRELOAD INPUT  ] Repository binary file input "
                + "set on project creation, [ ProjectCreationOptions.preloadWorkspace ].");

        /* 
         * Load an R object literal "hipStarUrl" into the
         * workspace on project initialization.
         *
         * The R script execution that follows will check for
         * the existence of "hipStarUrl" in the workspace and if
         * present uses the URL path to load the Hipparcos star
         * dataset from the DAT file at that location.
         */
        RData hipStarUrl = RDataFactory.createString("hipStarUrl", HIP_DAT_URL);
        List<RData> rinputs = Arrays.asList(hipStarUrl);
        creationOpts.rinputs = rinputs;

        log.info("[ PRELOAD INPUT  ] External data source input "
                + "set on project creation, [ ProjectCreationOptions.rinputs ].");

        /*
         * Create a temporary project (R session) passing a 
         * ProjectCreationOptions to "pre-heat" data into the
         * workspace and/or working directory.
         */
        rProject = rUser.createProject(creationOpts);

        log.info("[  GO STATEFUL   ] Created stateful temporary " + "R session [ RProject ].");

        /*
         * Create a ProjectExecutionOptions instance
         * to specify data inputs and output to the
         * execution of the repository-managed R script.
         *
         * This options object can be used to pass standard
         * execution model parameters on execution calls. All
         * fields are optional.
         *
         * See the Standard Execution Model chapter in the
         * Client Library Tutorial on the DeployR website for
         * further details.
         */
        ProjectExecutionOptions execOpts = new ProjectExecutionOptions();

        /*
         * Request the retrieval of the "hip" data.frame and
         * two vector objects from the workspace following the
         * execution. The corresponding R objects are named as
         * follows:
         * 'hip', hipDim', 'hipNames'.
         */
        execOpts.routputs = Arrays.asList("hip", "hipDim", "hipNames");

        log.info("[  EXEC OPTION   ] DeployR-encoded R object request "
                + "set on execution [ ProjectExecutionOptions.routputs ].");

        /*
         * Execute a public analytics Web service as an authenticated
         * user based on a repository-managed R script:
         * /testuser/example-data-io/dataIO.R
         */
        RProjectExecution exec = rProject.executeScript("dataIO.R", "example-data-io", "testuser", null,
                execOpts);

        log.info("[   EXECUTION    ] Stateful R script " + "execution completed [ RProjectExecution ].");

        /*
         * Retrieve multiple outputs following the execution:
         *
         * 1. R console output.
         * 2. R console output.
         * 3. R console output.
         * 4. R console output.
         * 5. R console output.
         */

        String console = exec.about().console;
        log.info("[  DATA OUTPUT   ] Retrieved R console " + "output [ String ].");

        /*
         * Retrieve the requested R object data encodings from
         * the workspace follwing the script execution. 
         *
         * See the R Object Data Decoding chapter in the
         * Client Library Tutorial on the DeployR website for
         * further details.
         */
        List<RData> objects = exec.about().workspaceObjects;

        for (RData rData : objects) {
            if (rData instanceof RDataFrame) {
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object output " + rData.getName()
                        + " [ RDataFrame ].");
                List<RData> hipSubsetVal = ((RDataFrame) rData).getValue();
            } else if (rData instanceof RNumericVector) {
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object output " + rData.getName()
                        + " [ RNumericVector ].");
                List<Double> hipDimVal = ((RNumericVector) rData).getValue();
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object " + rData.getName()
                        + " value=" + hipDimVal);
            } else if (rData instanceof RStringVector) {
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object output " + rData.getName()
                        + " [ RStringVector ].");
                List<String> hipNamesVal = ((RStringVector) rData).getValue();
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object " + rData.getName()
                        + " value=" + hipNamesVal);
            } else {
                log.info("Unexpected DeployR-encoded R object returned, " + "object name=" + rData.getName()
                        + ", encoding=" + rData.getClass());
            }
        }

        /*
         * Retrieve the working directory files (artifact)
         * was generated by the execution.
         */
        List<RProjectFile> wdFiles = exec.about().artifacts;

        for (RProjectFile wdFile : wdFiles) {
            log.info("[  DATA OUTPUT   ] Retrieved working directory " + "file output "
                    + wdFile.about().filename + " [ RProjectFile ].");
            InputStream fis = null;
            try {
                fis = wdFile.download();
            } catch (Exception ex) {
                log.warn("Working directory binary file download " + ex);
            } finally {
                IOUtils.closeQuietly(fis);
            }
        }

        /*
         * Retrieve R graphics device plots (results) called
         * unnamedplot*.png that was generated by the execution.
         */
        List<RProjectResult> results = exec.about().results;

        for (RProjectResult result : results) {
            log.info("[  DATA OUTPUT   ] Retrieved graphics device " + "plot output " + result.about().filename
                    + " [ RProjectResult ].");
            InputStream fis = null;
            try {
                fis = result.download();
            } catch (Exception ex) {
                log.warn("Graphics device plot download " + ex);
            } finally {
                IOUtils.closeQuietly(fis);
            }
        }

    } catch (Exception ex) {
        log.warn("Unexpected runtime exception=" + ex);
    } finally {
        try {
            if (rProject != null) {
                /*
                 * Close rProject before application exits.
                 */
                rProject.close();
            }
        } catch (Exception fex) {
        }
        try {
            if (rClient != null) {
                /*
                 * Release rClient connection before application exits.
                 */
                rClient.release();
            }
        } catch (Exception fex) {
        }
    }

}

From source file:be.redlab.maven.yamlprops.create.YamlConvertCli.java

public static void main(String... args) throws IOException {
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();
    HelpFormatter formatter = new HelpFormatter();
    options.addOption(Option.builder("s").argName("source").desc("the source folder or file to convert")
            .longOpt("source").hasArg(true).build());
    options.addOption(Option.builder("t").argName("target").desc("the target file to store in")
            .longOpt("target").hasArg(true).build());
    options.addOption(Option.builder("h").desc("print help").build());

    try {/* ww  w  .  ja  va 2  s  .  c om*/
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption('h')) {
            formatter.printHelp("converter", options);
        }
        File source = new File(cmd.getOptionValue("s", System.getProperty("user.dir")));
        String name = source.getName();
        if (source.isDirectory()) {
            PropertiesToYamlConverter yamlConverter = new PropertiesToYamlConverter();
            String[] ext = { "properties" };
            Iterator<File> fileIterator = FileUtils.iterateFiles(source, ext, true);
            while (fileIterator.hasNext()) {
                File next = fileIterator.next();
                System.out.println(next);
                String s = StringUtils.removeStart(next.getParentFile().getPath(), source.getPath());
                System.out.println(s);
                String f = StringUtils.split(s, IOUtils.DIR_SEPARATOR)[0];
                System.out.println("key = " + f);
                Properties p = new Properties();
                try {
                    p.load(new FileReader(next));
                    yamlConverter.addProperties(f, p);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileWriter fileWriter = new FileWriter(
                    new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml"));
            yamlConverter.writeYaml(fileWriter);
            fileWriter.close();
        } else {
            Properties p = new Properties();
            p.load(new FileReader(source));
            FileWriter fileWriter = new FileWriter(
                    new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml"));
            new PropertiesToYamlConverter().addProperties(name, p).writeYaml(fileWriter);
            fileWriter.close();
        }
    } catch (ParseException e) {
        e.printStackTrace();
        formatter.printHelp("converter", options);
    }
}

From source file:com.haulmont.cuba.core.sys.utils.DbUpdaterUtil.java

public static void main(String[] args) {
    String property = System.getProperty("logback.configurationFile");
    if (StringUtils.isBlank(property)) {
        System.setProperty("logback.configurationFile", "com/haulmont/cuba/core/sys/utils/dbutil-logback.xml");
    }/*from w  w  w .  j  a v a 2  s. c  o  m*/

    DbUpdaterUtil runner = new DbUpdaterUtil();
    runner.execute(args);
}

From source file:copi.ScalaEntryPoint.java

public static void main(String[] args) {
    /*//w  w w . ja v  a 2 s. c om
       * Set lwjgl library path so that LWJGL finds the natives depending on
       * the OS.
       */
    File libDir = new File(path);

    if (!libDir.exists()) {
        // create native lib folder 
        libDir.mkdir();

        // retrieve os type
        String osName = System.getProperty("os.name");

        // try to determine if the system is 64 bit  
        boolean is64bit = false;
        if (System.getProperty("os.name").contains("Windows")) {
            is64bit = (System.getenv("ProgramFiles(x86)") != null);
        } else {
            is64bit = (System.getProperty("os.arch").indexOf("64") != -1);
        }

        // construct name of native lib file 
        String natLibLWJGL = "";
        if (osName.startsWith("Windows")) {
            natLibLWJGL += "lwjgl";
            if (is64bit)
                natLibLWJGL += "64";
            natLibLWJGL += ".dll";
        } else if (osName.startsWith("Linux")) {
            natLibLWJGL += "liblwjgl";
            if (is64bit)
                natLibLWJGL += "64";
            natLibLWJGL += ".so";
        } else if (osName.startsWith("Mac OS X")) {
            natLibLWJGL += "liblwjgl";
            natLibLWJGL += ".jnilib";
        } else {
            System.out.println("Unsupported OS: " + osName + ". Exiting.");
            System.exit(-1);
        }

        // try to establish an input stream on the native lib inside the jar
        InputStream fis = ScalaEntryPoint.class.getResourceAsStream("/" + natLibLWJGL);
        if (fis == null) {
            System.out.println("Native library file " + natLibLWJGL + " was not found inside JAR.");
            System.exit(-1);
        }

        // establish an output stream on the target file 
        File fOut = new File(path + "/" + natLibLWJGL);
        try (FileOutputStream fos = new FileOutputStream(fOut)) {
            // create file at destination if not already existing
            if (!fOut.exists())
                fOut.createNewFile();

            // making buffer for copy operation 
            byte[] buffer = new byte[1024];
            int readBytes;

            // Open output stream and copy data between source file in JAR and the temporary file
            try {
                while ((readBytes = fis.read(buffer)) != -1) {
                    fos.write(buffer, 0, readBytes);
                }
            } finally {
                fos.close();
                fis.close();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
            System.exit(-1);
        }

        // register shutdown hook
        JVMShutdownHook jvmShutdownHook = new JVMShutdownHook();
        Runtime.getRuntime().addShutdownHook(jvmShutdownHook);

    }

    // set lwjgl native library path
    System.setProperty("org.lwjgl.librarypath", libDir.getAbsolutePath());

    // start COPI
    System.out.println("Starting COPI ...");
    (new SICApplicationLogic()).render();
}

From source file:example.topic.durable.Subscriber.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();/* ww  w. j  ava2s . co m*/
    }
    System.out
            .println("\nWaiting to receive messages... Either waiting for END message or press Ctrl+C to exit");
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;
    final CountDownLatch latch = new CountDownLatch(1);

    try {

        connection = connectionFactory.createConnection();
        String clientId = System.getProperty("clientId");
        connection.setClientID(clientId);

        connection.start();

        Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Topic destination = session.createTopic("test-topic");

        MessageConsumer consumer = session.createDurableSubscriber(destination, clientId);
        consumer.setMessageListener(new Subscriber(latch));

        latch.await();
        consumer.close();
        session.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("Could not close an open connection...");
            }
        }
    }
}

From source file:StringConverter.java

public static void main(String[] args) {

    System.out.println(System.getProperty("file.encoding"));
    String original = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");

    System.out.println("original = " + original);
    System.out.println();/*  w w w  . j  av a2  s.  co  m*/

    try {
        byte[] utf8Bytes = original.getBytes("UTF8");
        byte[] defaultBytes = original.getBytes();

        String roundTrip = new String(utf8Bytes, "UTF8");
        System.out.println("roundTrip = " + roundTrip);

        System.out.println();
        printBytes(utf8Bytes, "utf8Bytes");
        System.out.println();
        printBytes(defaultBytes, "defaultBytes");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

}

From source file:org.atomserver.utils.jetty.StandAloneAtomServer.java

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

    // the System Property "atomserver.home" defines the home directory for the standalone app
    String atomserverHome = System.getProperty("atomserver.home");
    if (StringUtils.isEmpty(atomserverHome)) {
        log.error("The variable \"atomserver.home\" must be defined");
        System.exit(-1);/*  w  w w  .j a  va2 s  . co m*/
    }
    File atomserverHomeDir = new File(atomserverHome);
    if (!atomserverHomeDir.exists() && !atomserverHomeDir.isDirectory()) {
        log.error("The variable \"atomserver.home\" (" + atomserverHome
                + ") must point to a directory that exists");
    }

    // instantiate the Jetty Server
    Server server = new Server();

    // create a new connector on the declared port, and set it onto the server
    log.debug("atomserver.port = " + System.getProperty("atomserver.port"));
    Connector connector = new SelectChannelConnector();
    connector.setPort(Integer.getInteger("atomserver.port", DEFAULT_PORT));
    server.setConnectors(new Connector[] { connector });

    // create a ClassLoader that points at the conf directories
    log.debug("atomserver.conf.dir = " + System.getProperty("atomserver.conf.dir"));
    log.debug("atomserver.ops.conf.dir = " + System.getProperty("atomserver.ops.conf.dir"));
    ClassLoader classLoader = new ConfigurationAwareClassLoader(StandAloneAtomServer.class.getClassLoader());

    // load the version from the version.properties file
    Properties versionProps = new Properties();
    versionProps.load(classLoader.getResourceAsStream(DEFAULT_VERSIONS_FILE));
    String version = versionProps.getProperty("atomserver.version");

    // create a new webapp, rooted at webapps/atomserver-${version}, with the configured
    // context name
    String servletContextName = System.getProperty("atomserver.servlet.context");
    log.debug("atomserver.servlet.context = " + servletContextName);
    WebAppContext webapp = new WebAppContext(atomserverHome + "/webapps/atomserver-" + version,
            "/" + servletContextName);

    // set the webapp's ClassLoader to be the one that loaded THIS class.  the REASON that
    // this needs to be set is so that when we extract the web application context below we can
    // cast it to WebApplicationContext here
    webapp.setClassLoader(StandAloneAtomServer.class.getClassLoader());

    // set the Jetty server's webapp and start it
    server.setHandler(webapp);
    server.start();

    // if the seed system property was set, use the DBSeeder to populate the server
    String seedDB = System.getProperty("seed.database.with.pets");
    log.debug("seed.database.with.pets = " + seedDB);
    if (!StringUtils.isEmpty(seedDB)) {
        if (Boolean.valueOf(seedDB)) {
            Thread.sleep(2000);

            WebApplicationContext webappContext = WebApplicationContextUtils
                    .getWebApplicationContext(webapp.getServletContext());

            DBSeeder.getInstance(webappContext).seedPets();
        }
    }

    server.join();
}

From source file:it.geosolutions.sfs.web.Start.java

public static void main(String[] args) {
    final Server jettyServer = new Server();

    try {/*from  w  w w  .ja va 2 s .  c o m*/
        SocketConnector conn = new SocketConnector();
        String portVariable = System.getProperty("jetty.port");
        int port = parsePort(portVariable);
        if (port <= 0)
            port = 8082;
        conn.setPort(port);
        conn.setAcceptQueueSize(100);
        conn.setMaxIdleTime(1000 * 60 * 60);
        conn.setSoLingerTime(-1);

        // Use this to set a limit on the number of threads used to respond requests
        // BoundedThreadPool tp = new BoundedThreadPool();
        // tp.setMinThreads(8);
        // tp.setMaxThreads(8);
        // conn.setThreadPool(tp);

        // SSL host name given ?
        String sslHost = System.getProperty("ssl.hostname");
        SslSocketConnector sslConn = null;
        //            if (sslHost!=null && sslHost.length()>0) {   
        //                Security.addProvider(new BouncyCastleProvider());
        //                sslConn = getSslSocketConnector(sslHost);
        //            }

        if (sslConn == null) {
            jettyServer.setConnectors(new Connector[] { conn });
        } else {
            conn.setConfidentialPort(sslConn.getPort());
            jettyServer.setConnectors(new Connector[] { conn, sslConn });
        }

        /*Constraint constraint = new Constraint();
        constraint.setName(Constraint.__BASIC_AUTH);;
        constraint.setRoles(new String[]{"user","admin","moderator"});
        constraint.setAuthenticate(true);
                 
        ConstraintMapping cm = new ConstraintMapping();
        cm.setConstraint(constraint);
        cm.setPathSpec("/*");
                
        SecurityHandler sh = new SecurityHandler();
        sh.setUserRealm(new HashUserRealm("MyRealm","/Users/jdeolive/realm.properties"));
        sh.setConstraintMappings(new ConstraintMapping[]{cm});
                
        WebAppContext wah = new WebAppContext(sh, null, null, null);*/
        WebAppContext wah = new WebAppContext();
        wah.setContextPath("/sfs");
        wah.setWar("src/main/webapp");

        jettyServer.setHandler(wah);
        wah.setTempDirectory(new File("target/work"));
        //this allows to send large SLD's from the styles form
        wah.getServletContext().getContextHandler().setMaxFormContentSize(1024 * 1024 * 2);

        String jettyConfigFile = System.getProperty("jetty.config.file");
        if (jettyConfigFile != null) {
            //                log.info("Loading Jetty config from file: " + jettyConfigFile);
            (new XmlConfiguration(new FileInputStream(jettyConfigFile))).configure(jettyServer);
        }

        jettyServer.start();

        /*
         * Reads from System.in looking for the string "stop\n" in order to gracefully terminate
         * the jetty server and shut down the JVM. This way we can invoke the shutdown hooks
         * while debugging in eclipse. Can't catch CTRL-C to emulate SIGINT as the eclipse
         * console is not propagating that event
         */
        Thread stopThread = new Thread() {
            @Override
            public void run() {
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                String line;
                try {
                    while (true) {
                        line = reader.readLine();
                        if ("stop".equals(line)) {
                            jettyServer.stop();
                            System.exit(0);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.exit(1);
                }
            }
        };
        stopThread.setDaemon(true);
        stopThread.run();

        // use this to test normal stop behaviour, that is, to check stuff that
        // need to be done on container shutdown (and yes, this will make 
        // jetty stop just after you started it...)
        // jettyServer.stop(); 
    } catch (Exception e) {
        //            log.log(Level.SEVERE, "Could not start the Jetty server: " + e.getMessage(), e);

        if (jettyServer != null) {
            try {
                jettyServer.stop();
            } catch (Exception e1) {
                //                    log.log(Level.SEVERE,
                //                        "Unable to stop the " + "Jetty server:" + e1.getMessage(), e1);
            }
        }
    }
}

From source file:eu.fbk.utils.twm.FormPageSearcher.java

public static void main(final String args[]) throws Exception {
    String logConfig = System.getProperty("log-config");
    if (logConfig == null) {
        logConfig = "configuration/log-config.txt";
    }//from   w  w w  .j av  a2s. c  o  m

    PropertyConfigurator.configure(logConfig);
    final Options options = new Options();
    try {
        OptionBuilder.withArgName("index");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("open an index with the specified name");
        OptionBuilder.isRequired();
        OptionBuilder.withLongOpt("index");
        final Option indexNameOpt = OptionBuilder.create("i");
        OptionBuilder.withArgName("interactive-mode");
        OptionBuilder.withDescription("enter in the interactive mode");
        OptionBuilder.withLongOpt("interactive-mode");
        final Option interactiveModeOpt = OptionBuilder.create("t");
        OptionBuilder.withArgName("search");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("search for the specified key");
        OptionBuilder.withLongOpt("search");
        final Option searchOpt = OptionBuilder.create("s");
        OptionBuilder.withArgName("key-freq");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("read the keys' frequencies from the specified file");
        OptionBuilder.withLongOpt("key-freq");
        final Option freqFileOpt = OptionBuilder.create("f");
        OptionBuilder.withArgName("minimum-freq");
        // Option keyFieldNameOpt =
        // OptionBuilder.withArgName("key-field-name").hasArg().withDescription("use the specified name for the field key").withLongOpt("key-field-name").create("k");
        // Option valueFieldNameOpt =
        // OptionBuilder.withArgName("value-field-name").hasArg().withDescription("use the specified name for the field value").withLongOpt("value-field-name").create("v");
        final Option minimumKeyFreqOpt = OptionBuilder.hasArg()
                .withDescription("minimum key frequency of cached values (default is " + DEFAULT_MIN_FREQ + ")")
                .withLongOpt("minimum-freq").create("m");
        OptionBuilder.withArgName("int");
        final Option notificationPointOpt = OptionBuilder.hasArg()
                .withDescription(
                        "receive notification every n pages (default is " + DEFAULT_NOTIFICATION_POINT + ")")
                .withLongOpt("notification-point").create("b");
        options.addOption("h", "help", false, "print this message");
        options.addOption("v", "version", false, "output version information and exit");

        options.addOption(indexNameOpt);
        options.addOption(interactiveModeOpt);
        options.addOption(searchOpt);
        options.addOption(freqFileOpt);
        // options.addOption(keyFieldNameOpt);
        // options.addOption(valueFieldNameOpt);
        options.addOption(minimumKeyFreqOpt);
        options.addOption(notificationPointOpt);

        final CommandLineParser parser = new PosixParser();
        final CommandLine line = parser.parse(options, args);

        if (line.hasOption("help") || line.hasOption("version")) {
            throw new ParseException("");
        }

        int minFreq = DEFAULT_MIN_FREQ;
        if (line.hasOption("minimum-freq")) {
            minFreq = Integer.parseInt(line.getOptionValue("minimum-freq"));
        }

        int notificationPoint = DEFAULT_NOTIFICATION_POINT;
        if (line.hasOption("notification-point")) {
            notificationPoint = Integer.parseInt(line.getOptionValue("notification-point"));
        }

        final FormPageSearcher pageFormSearcher = new FormPageSearcher(line.getOptionValue("index"));
        pageFormSearcher.setNotificationPoint(notificationPoint);
        /*
         * logger.debug(line.getOptionValue("key-field-name") + "\t" +
         * line.getOptionValue("value-field-name")); if (line.hasOption("key-field-name")) {
         * pageFormSearcher.setKeyFieldName(line.getOptionValue("key-field-name")); } if
         * (line.hasOption("value-field-name")) {
         * pageFormSearcher.setValueFieldName(line.getOptionValue("value-field-name")); }
         */
        if (line.hasOption("key-freq")) {
            pageFormSearcher.loadCache(line.getOptionValue("key-freq"), minFreq);
        }
        if (line.hasOption("search")) {
            logger.debug("searching " + line.getOptionValue("search") + "...");
            final FreqSetSearcher.Entry[] result = pageFormSearcher.search(line.getOptionValue("search"));
            logger.info(Arrays.toString(result));
        }
        if (line.hasOption("interactive-mode")) {
            pageFormSearcher.interactive();
        }
    } catch (final ParseException e) {
        // oops, something went wrong
        if (e.getMessage().length() > 0) {
            System.out.println("Parsing failed: " + e.getMessage() + "\n");
        }
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(400,
                "java -cp dist/thewikimachine.jar org.fbk.cit.hlt.thewikimachine.index.FormPageSearcher", "\n",
                options, "\n", true);
    }
}