Example usage for java.lang System setProperty

List of usage examples for java.lang System setProperty

Introduction

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

Prototype

public static String setProperty(String key, String value) 

Source Link

Document

Sets the system property indicated by the specified key.

Usage

From source file:it.geosolutions.unredd.apputil.AreaBuilder.java

public static void main(String[] args) {
    Option help = OptionBuilder.withLongOpt("help").withDescription("print help").create('?');

    Options helpOptions = new Options().addOption(help);

    Options options = new Options().addOption(help)
            .addOption(OptionBuilder.withLongOpt("extents").withArgName("n/e/s/w")
                    .withDescription("extents in the format n/e/s/w").hasArgs(4).withValueSeparator('/')
                    .isRequired().withType(Double.class).create(OPT_EXTENTS))
            .addOption(OptionBuilder.withLongOpt("size").withArgName("width,height")
                    .withDescription("size of output image in pixel in the format width,height").hasArgs(2)
                    .withValueSeparator(',').isRequired().withType(Integer.class).create(OPT_SIZE))
            .addOption(OptionBuilder.withLongOpt("outfile").withArgName("file")
                    .withDescription("the output tiff file").hasArg().isRequired().withType(String.class)
                    .create(OPT_OUTFILE))
            .addOption(OptionBuilder.withLongOpt("mem").withArgName("megabytes")
                    .withDescription("the max memory available for the operation").hasArg().create(OPT_MEM))
            .addOption(OptionBuilder.withLongOpt("threads").withArgName("numThreads")
                    .withDescription("number of threads JAI will use").hasArg().create(OPT_THREADS));

    try {/* ww  w .j a  v a  2s  .  c  om*/

        //=== Create parser
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);

        //=== Parse input params
        String sFile = cmd.getOptionValue(OPT_OUTFILE);

        String[] sSizeArr = cmd.getOptionValues(OPT_SIZE);
        if (sSizeArr.length != 2) {
            LOGGER.error("size requires 2 args");
            return;
        }
        String[] sExtArr = cmd.getOptionValues(OPT_EXTENTS);
        if (sExtArr.length != 4) {
            LOGGER.error("extents require 4 args");
            return;
        }

        File file = new File(sFile);
        LOGGER.info("Output file " + file);

        int w = Integer.parseInt(sSizeArr[0]);
        int h = Integer.parseInt(sSizeArr[1]);
        LOGGER.info("Image size " + w + " x " + h);

        double boxn = Double.parseDouble(sExtArr[0]);
        double boxe = Double.parseDouble(sExtArr[1]);
        double boxs = Double.parseDouble(sExtArr[2]);
        double boxw = Double.parseDouble(sExtArr[3]);
        LOGGER.info("Image bbox is n:" + boxn + "e:" + boxe + " s:" + boxs + " w:" + boxw);

        //=== Parse and set tilecache memory
        Long mega = 512l;
        if (cmd.hasOption(OPT_MEM)) {
            mega = Long.parseLong(cmd.getOptionValue(OPT_MEM));
            LOGGER.info("JAI tilecache memory set to " + mega + "MB");
        } else {
            LOGGER.info("JAI tilecache memory defaulting to " + mega + "MB");
        }

        JAI.getDefaultInstance().getTileCache().setMemoryCapacity(mega * MEGA);

        //=== Parse and set JAI parallelism level
        int threads = 4;
        if (cmd.hasOption(OPT_THREADS)) {
            threads = Integer.parseInt(cmd.getOptionValue(OPT_THREADS));
            LOGGER.info("JAI tile scheduler parallelism set to " + threads);
        } else {
            LOGGER.info("JAI tile scheduler parallelism defaulting to " + threads);
        }

        TileScheduler ts = JAI.getDefaultInstance().getTileScheduler();
        ts.setParallelism(threads);
        ts.setPrefetchParallelism(threads);

        //=== Create grid and save

        System.setProperty("org.geotools.referencing.forceXY", "true");
        GridCoverage2D grid = createAreaGrid(w, h, boxw, boxe, boxs, boxn);
        saveAreaGrid(grid, file);

    } catch (ParseException ex) {

        CommandLine cmd0 = null;
        try { // find out if an help was requested (it's missing mandatory params)
            CommandLineParser helpParser = new PosixParser();
            cmd0 = helpParser.parse(helpOptions, args);
        } catch (ParseException ex1) {
            LOGGER.error("Unexpected error: " + ex1);
        }

        if (cmd0 == null || !cmd0.hasOption("help")) {
            LOGGER.error("Parse error: " + ex);
        }

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("createAreaLayer", options);
    } catch (Exception e) {
        LOGGER.error("Unexpected exception", e);
    }
}

From source file:com.da.daum.DaumCafeImgAllList.java

public static void main(String[] args) {
    DaumCafeImgAllList cfl = new DaumCafeImgAllList();

    log.warn("Logging Works");
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");

    System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
    System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");

    try {//w  w w.jav a  2 s.  c o m
        // https://msp.f-secure.com/web-test/common/test.html
        // String body =
        // CHttpUtil.DownloadHtml("https://logins.daum.net/accounts/loginform.do?mobilefull=1&t__nil_footer=login&url=http%3a%2f%2fm%2edaum%2enet%2f");
        /*
         * String body = CHttpUtil.DownloadHtml(
         * "https://logins.daum.net/accounts/mobile.do?url=http%3A%2F%2Fm.daum.net%2F&relative=&mobilefull=1&weblogin=1&id=changwng&pw=cw89040310&stln=on&saved_id=on"
         * ); System.out.println(body);
         */
        String nPage = "1";
        String p_author_id = "bluesman";
        String p_gnum = ""; // ga
        String p_host_url = ""; // ga
        if (args.length > 0) {
            nPage = args[0];
        }
        if (args.length > 1) {
            p_author_id = args[1];
        }
        if (args.length > 2) {
            STORY_DIR = args[2];
        }

        if (args.length > 3) {
            p_host_url = args[3];
            SO_URL = p_host_url;
            /*
             * host_url = "http://www."+SO_URL; photo_url =
             * "http://photo."+SO_URL+"/album/theme/"; story_url =
             * "http://story."+SO_URL+"/honor/";
             */
        }
        cfl.executeURL(nPage, p_author_id, p_gnum);
        // cfl.executeAuthorList(nPage, p_author_id, p_gnum);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.example.geomesa.authorizations.AuthorizationsTutorial.java

/**
 * Main entry point. Executes queries against an existing GDELT dataset.
 *
 * @param args/*from w w  w.  ja v a2 s  .  c om*/
 *
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    // read command line options - this contains the connection to accumulo and the table to query
    CommandLineParser parser = new BasicParser();
    Options options = SetupUtil.getGeomesaDataStoreOptions();
    CommandLine cmd = parser.parse(options, args);

    // verify that we can see this Accumulo destination in a GeoTools manner
    Map<String, String> dsConf = SetupUtil.getAccumuloDataStoreConf(cmd);

    // get an instance of the data store that uses the default authorizations provider, which will use whatever auths the connector has available
    System.setProperty(AuthorizationsProvider.AUTH_PROVIDER_SYS_PROPERTY,
            DefaultAuthorizationsProvider.class.getName());
    DataStore authDataStore = DataStoreFinder.getDataStore(dsConf);
    assert authDataStore != null;

    // get another instance of the data store that uses our authorizations provider that always returns empty auths
    System.setProperty(AuthorizationsProvider.AUTH_PROVIDER_SYS_PROPERTY,
            EmptyAuthorizationsProvider.class.getName());
    DataStore noAuthDataStore = DataStoreFinder.getDataStore(dsConf);

    // create the simple feature type for our test
    String simpleFeatureTypeName = cmd.getOptionValue(SetupUtil.FEATURE_NAME);
    SimpleFeatureType simpleFeatureType = GdeltFeature.buildGdeltFeatureType(simpleFeatureTypeName);

    // execute the query, with and without visibilities
    System.out.println("\nExecuting query with AUTHORIZED data store: auths are '"
            + ((AccumuloDataStore) authDataStore).config().authProvider().getAuthorizations() + "'");
    executeQuery(simpleFeatureTypeName, authDataStore);
    System.out.println("Executing query with UNAUTHORIZED data store: auths are '"
            + ((AccumuloDataStore) noAuthDataStore).config().authProvider().getAuthorizations() + "'");
    executeQuery(simpleFeatureTypeName, noAuthDataStore);
}

From source file:it.isislab.dmason.util.SystemManagement.Worker.thrower.DMasonWorkerWithGui.java

public static void main(String[] args) {
    RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();

    ////from w  ww.  j  av  a 2 s  .  c  o m
    // Get name representing the running Java virtual machine.
    // It returns something like 6460@AURORA. Where the value
    // before the @ symbol is the PID.
    //
    String jvmName = bean.getName();

    //Used for log4j properties
    System.setProperty("logfile.name", "worker" + jvmName);

    //Used for log4j properties
    System.setProperty("steplog.name", "workerStep" + jvmName);

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss_SS");
    Date date = new Date();
    dateFormat.format(date);

    System.setProperty("timestamp", date.toLocaleString());

    System.setProperty("paramsfile.name", "params");
    try {
        File logPath = new File("Logs/workers");
        if (logPath.exists())
            FileUtils.cleanDirectory(logPath);
    } catch (IOException e) {
        //not a problem
    }

    logger = Logger.getLogger(DMasonWorker.class.getCanonicalName());
    logger.debug("StartWorker " + VERSION);

    autoStart = false;

    String ip = null;
    String port = null;
    String topic = "";
    updated = false;
    isBatch = false;
    topicPrefix = "";

    // ip, post, autoconnect
    if (args.length == 3) {
        ip = args[0];
        port = args[1];
        if (args[2].equals("autoconnect")) {
            autoStart = true;
        }
    }
    // ip, post, topic, event 
    if (args.length == 4) {
        autoStart = true;
        if (args[3].equals("update")) {
            updated = true;
        }
        if (args[3].equals("reset")) {
            updated = false;
            isBatch = false;
        }
        if (args[3].contains("Batch")) {
            updated = false;
            isBatch = true;
            topicPrefix = args[3];
        }
        ip = args[0];
        port = args[1];
        topic = args[2];
    }

    /*if(args.length == 2 && args[0].equals("auto"))
    {   autoStart = true;
       updated = true;
       topic = args[1];
    }
    if(args.length == 1 && args[0].equals("auto"))
    {   autoStart = true;
    }*/
    new DMasonWorkerWithGui(autoStart, updated, isBatch, topic, ip, port);
}

From source file:geomesa.tutorial.AuthorizationsTutorial.java

/**
 * Main entry point. Executes queries against an existing GDELT dataset.
 *
 * @param args/* w w w. j  a  v a  2  s.  co m*/
 *
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    // read command line options - this contains the connection to accumulo and the table to query
    CommandLineParser parser = new BasicParser();
    Options options = SetupUtil.getGeomesaDataStoreOptions();
    CommandLine cmd = parser.parse(options, args);

    // verify that we can see this Accumulo destination in a GeoTools manner
    Map<String, String> dsConf = SetupUtil.getAccumuloDataStoreConf(cmd);

    // get an instance of the data store that uses the default authorizations provider, which will use whatever auths the connector has available
    System.setProperty(AuthorizationsProvider.AUTH_PROVIDER_SYS_PROPERTY,
            DefaultAuthorizationsProvider.class.getName());
    DataStore authDataStore = DataStoreFinder.getDataStore(dsConf);
    assert authDataStore != null;

    // get another instance of the data store that uses our authorizations provider that always returns empty auths
    System.setProperty(AuthorizationsProvider.AUTH_PROVIDER_SYS_PROPERTY,
            EmptyAuthorizationsProvider.class.getName());
    DataStore noAuthDataStore = DataStoreFinder.getDataStore(dsConf);

    // create the simple feature type for our test
    String simpleFeatureTypeName = cmd.getOptionValue(SetupUtil.FEATURE_NAME);
    SimpleFeatureType simpleFeatureType = GdeltFeature.buildGdeltFeatureType(simpleFeatureTypeName);

    // execute the query, with and without visibilities
    System.out.println("\nExecuting query with AUTHORIZED data store: auths are '"
            + ((AccumuloDataStore) authDataStore).authorizationsProvider().getAuthorizations() + "'");
    executeQuery(simpleFeatureTypeName, authDataStore);
    System.out.println("Executing query with UNAUTHORIZED data store: auths are '"
            + ((AccumuloDataStore) noAuthDataStore).authorizationsProvider().getAuthorizations() + "'");
    executeQuery(simpleFeatureTypeName, noAuthDataStore);
}

From source file:uk.co.moonsit.rmi.GraphClient.java

@SuppressWarnings("SleepWhileInLoop")
public static void main(String args[]) {
    Properties p = new Properties();
    try {//from  www .j a  va 2s. c  o m
        p.load(new FileReader("graph.properties"));
    } catch (IOException ex) {
        Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    //String[] labels = p.getProperty("labels").split(",");
    GraphClient demo = null;
    int type = 0;
    boolean log = false;
    if (args[0].equals("-l")) {
        log = true;
    }

    switch (type) {
    case 0:
        try {
            System.setProperty("java.security.policy", "file:./client.policy");
            if (System.getSecurityManager() == null) {
                System.setSecurityManager(new RMISecurityManager());
            }
            String name = "GraphServer";
            String host = p.getProperty("host");
            System.out.println(host);
            Registry registry = LocateRegistry.getRegistry(host);
            String[] list = registry.list();
            for (String s : list) {
                System.out.println(s);
            }
            GraphDataInterface gs = null;
            boolean bound = false;
            while (!bound) {
                try {
                    gs = (GraphDataInterface) registry.lookup(name);
                    bound = true;
                } catch (NotBoundException e) {
                    System.err.println("GraphServer exception:" + e.toString());
                    Thread.sleep(500);
                }
            }
            @SuppressWarnings("null")
            String config = gs.getConfig();
            System.out.println(config);
            /*float[] fs = gs.getValues();
             for (float f : fs) {
             System.out.println(f);
             }*/

            demo = new GraphClient(gs, 1000, 700, Float.parseFloat(p.getProperty("frequency")), log);
            demo.init(config);
            demo.run();
        } catch (RemoteException e) {
            System.err.println("GraphClient exception:" + e.toString());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (demo != null) {
                demo.close();
            }
        }
        break;
    case 1:
        try {
            demo = new GraphClient(1000, 700, Float.parseFloat(p.getProperty("frequency")));
            demo.init("A^B|Time|Error|-360|360");

            demo.addData(0, 1, 100);
            demo.addData(0, 2, 200);

            demo.addData(1, 1, 50);
            demo.addData(1, 2, 450);

        } catch (FileNotFoundException ex) {
            Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        break;
    }

}

From source file:de.uniwue.dmir.heatmap.EntryPointIncremental.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws IOException, ParseException {

    DateFormat df = new SimpleDateFormat(DATE_FORMAT);
    SimpleDateFormat backupDf = new SimpleDateFormat(BACKUP_DATE_FORMAT);

    String workDir = System.getProperty("workDir", ".");
    LOGGER.debug("Work dir: {}", workDir);
    String configDir = System.getProperty("configDir", ".");
    LOGGER.debug("Config dir: {}", configDir);

    File seedDir = new File(workDir, SEED_DIR);
    LOGGER.debug("Seed dir: {}", seedDir);
    File currentDir = new File(workDir, CURRENT_DIR);
    LOGGER.debug("Current dir: {}", currentDir);
    File backupDir = new File(workDir, BACKUP_DIR);
    LOGGER.debug("Backup dir: {}", backupDir);

    String initialMinTimeString = System.getProperty("minTime");
    LOGGER.debug("Initial minimal time parameter: {}", initialMinTimeString);
    Date initialMinTime = initialMinTimeString == null ? new Date(0) : df.parse(initialMinTimeString);
    LOGGER.debug("Initial minimal time: {}", df.format(initialMinTime));

    String absoluteMaxTimeString = System.getProperty("maxTime");
    LOGGER.debug("Absolute maximal time parameter: {}", absoluteMaxTimeString);
    Date absoluteMaxTime = absoluteMaxTimeString == null ? new Date()
            : new SimpleDateFormat(DATE_FORMAT).parse(absoluteMaxTimeString);
    LOGGER.debug("Absolute maximal time: {}", df.format(absoluteMaxTime));

    String incrementalFile = new File("file:" + configDir, INCREMENTAL_FILE).getPath();
    String settingsFile = new File("file:" + configDir, HEATMAP_PROCESSOR__FILE).getPath();

    LOGGER.debug("Initializing incremental control file: {}", incrementalFile);
    FileSystemXmlApplicationContext incrementalContext = new FileSystemXmlApplicationContext(incrementalFile);

    // get point limit
    int pointLimit = Integer
            .parseInt(incrementalContext.getBeanFactory().resolveEmbeddedValue("${point.limit}"));
    LOGGER.debug("Print limit: {}", pointLimit);

    // get backups to keep
    int backupsToKeep = Integer
            .parseInt(incrementalContext.getBeanFactory().resolveEmbeddedValue("${backups.to.keep}"));
    LOGGER.debug("Backups to keep: {}", pointLimit);

    LOGGER.debug("Initializing process components (manager and limiter).");
    IProcessManager processManager = incrementalContext.getBean(IProcessManager.class);
    IProcessLimiter processLimiter = incrementalContext.getBean(IProcessLimiter.class);

    LOGGER.debug("Starting incremental loop.");
    while (true) { // break as soon as no new points are available

        // cleanup --- just in case
        LOGGER.debug("Deleting \"current\" dir.");
        FileUtils.deleteDirectory(currentDir);

        // copy from seed to current
        LOGGER.debug("Copying seed.");
        seedDir.mkdirs();/*from  ww w. j  av  a2  s. c o m*/
        FileUtils.copyDirectory(seedDir, currentDir);

        // get min time
        LOGGER.debug("Getting minimal time ...");
        Date minTime = initialMinTime;
        ProcessManagerEntry entry = processManager.getEntry();
        if (entry != null && entry.getMaxTime() != null) {
            minTime = entry.getMaxTime();
        }
        LOGGER.debug("Minimal time: {}", new SimpleDateFormat(DATE_FORMAT).format(minTime));

        // break if we processed all available points (minTime is greater than or equal to absoluteMaxTime)
        if (minTime.getTime() >= absoluteMaxTime.getTime()) {
            LOGGER.debug("Processed all points.");
            break;
        }

        // get the maximal time
        LOGGER.debug("Get maximal time.");

        // get the time from the newest point in our point range (pointMaxTime) ...
        Date pointMaxTime = processLimiter.getMaxTime(minTime, pointLimit);

        // ... and possibly break the loop if no new points are available
        if (pointMaxTime == null)
            break;

        // set the max time and make sure we are not taking to many points 
        // (set max time to the minimum of pointMaxTime and absoluteMaxTime)
        Date maxTime = pointMaxTime.getTime() > absoluteMaxTime.getTime() ? absoluteMaxTime : pointMaxTime;

        LOGGER.debug("Maximal time: {}", new SimpleDateFormat(DATE_FORMAT).format(maxTime));

        // start process
        processManager.start(minTime);

        System.setProperty("minTimestamp", new SimpleDateFormat(DATE_FORMAT).format(minTime));

        System.setProperty("maxTimestamp", new SimpleDateFormat(DATE_FORMAT).format(maxTime));

        FileSystemXmlApplicationContext heatmapContext = new FileSystemXmlApplicationContext(settingsFile);

        IHeatmap heatmap = heatmapContext.getBean(HEATMAP_BEAN, IHeatmap.class);

        ITileProcessor tileProcessor = heatmapContext.getBean(WRITER_BEAN, ITileProcessor.class);

        heatmap.processTiles(tileProcessor);

        tileProcessor.close();
        heatmapContext.close();

        // finish process
        processManager.finish(maxTime);

        // move old seed
        if (backupsToKeep > 0) {
            FileUtils.moveDirectory(seedDir, new File(backupDir, backupDf.format(minTime))); // minTime is the maxTime of the seed

            // cleanup backups
            String[] backups = backupDir.list(DirectoryFileFilter.DIRECTORY);
            File oldestBackup = null;
            if (backups.length > backupsToKeep) {
                for (String bs : backups) {
                    File b = new File(backupDir, bs);
                    if (oldestBackup == null || oldestBackup.lastModified() > b.lastModified()) {
                        oldestBackup = b;
                    }
                }
                FileUtils.deleteDirectory(oldestBackup);
            }

        } else {
            FileUtils.deleteDirectory(seedDir);
        }

        // move new seed
        FileUtils.moveDirectory(currentDir, seedDir);

    }

    incrementalContext.close();

}

From source file:com.clustercontrol.HinemosManagerMain.java

/**
 * Hinemos Manager?main<br/>//from  w w  w.j a va  2  s .  c o  m
 * @param args
 * @throws Exception
 */
public static void main(String args[]) {

    try {
        try {
            if (System.getProperty("systime.iso") != null) {
                String oldVmName = System.getProperty("java.vm.name");

                //System?mock?????HotSpot??????????
                System.setProperty("java.vm.name", "HotSpot 64-Bit Server VM");

                Class.forName("com.clustercontrol.util.SystemTimeShifter");

                System.setProperty("java.vm.name", oldVmName);
            }
        } catch (Exception e) {
            log.error(e);
        } catch (Error e) {
            log.error(e);
        }

        long bootTime = System.currentTimeMillis();
        log.info("Hinemos Manager is starting." + " (startupMode=" + _startupMode + ", clustered="
                + _isClustered + ", locale=" + Locale.getDefault() + ")");

        // Hinemos(??????)???????
        // (???????????????????????)
        long offset = HinemosPropertyUtil.getHinemosPropertyNum("common.time.offset", Long.valueOf(0));
        HinemosTime.setTimeOffsetMillis(offset);

        // Hinemos?(UTC??)??/(??)
        int timeZoneOffset = HinemosPropertyUtil
                .getHinemosPropertyNum("common.timezone", Long.valueOf(TimeZone.getDefault().getRawOffset()))
                .intValue();
        HinemosTime.setTimeZoneOffset(timeZoneOffset);

        // ???HinemosPlugin??(create)?
        HinemosPluginService.getInstance().create();

        // ???HinemosPlugin?(activate)?
        HinemosPluginService.getInstance().activate();

        // Hinemos Manger????
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                log.info("shutdown hook called.");
                synchronized (shutdownLock) {
                    // Hinemos Manager???
                    String[] msgArgsShutdown = { _hostname };
                    AplLogger.put(PriorityConstant.TYPE_INFO, HinemosModuleConstant.HINEMOS_MANAGER_MONITOR,
                            MessageConstant.MESSAGE_SYS_002_MNG, msgArgsShutdown);

                    // ???HinemosPlugin??(deactivate)?
                    HinemosPluginService.getInstance().deactivate();

                    // ???HinemosPlugin?(destroy)?
                    HinemosPluginService.getInstance().destroy();

                    log.info("Hinemos Manager is stopped.");

                    shutdown = true;
                    shutdownLock.notify();
                }
            }
        });

        // ??
        long startupTime = System.currentTimeMillis();
        long initializeSec = (startupTime - bootTime) / 1000;
        long initializeMSec = (startupTime - bootTime) % 1000;
        log.info("Hinemos Manager Started in " + initializeSec + "s:" + initializeMSec + "ms");

        // Hinemos Manager??
        String[] msgArgsStart = { _hostname };
        AplLogger.put(PriorityConstant.TYPE_INFO, HinemosModuleConstant.HINEMOS_MANAGER_MONITOR,
                MessageConstant.MESSAGE_SYS_001_MNG, msgArgsStart);

        // Hinemos Manager???????
        synchronized (shutdownLock) {
            while (!shutdown) {
                try {
                    shutdownLock.wait();
                } catch (InterruptedException e) {
                    log.warn("shutdown lock interrupted.", e);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException sleepE) {
                    }
                    ;
                }
            }
        }

        System.exit(0);

    } catch (Throwable e) {
        log.error("unknown error occured.", e);
    }
}

From source file:com.trsst.Command.java

public static void main(String[] argv) {

    // during alpha period: expire after one week
    Date builtOn = Common.getBuildDate();
    if (builtOn != null) {
        long weekMillis = 1000 * 60 * 60 * 24 * 7;
        Date expiry = new Date(builtOn.getTime() + weekMillis);
        if (new Date().after(expiry)) {
            System.err.println("Build expired on: " + expiry);
            System.err.println("Please obtain a more recent build for testing.");
            System.exit(1);/* w  w w  . j a  va 2 s.  c  o m*/
        } else {
            System.err.println("Build will expire on: " + expiry);
        }
    }

    // experimental tor support
    boolean wantsTor = false;
    for (String s : argv) {
        if ("--tor".equals(s)) {
            wantsTor = true;
            break;
        }
    }
    if (wantsTor && !HAS_TOR) {
        try {
            log.info("Attempting to connect to tor network...");
            Security.addProvider(new BouncyCastleProvider());
            JvmGlobalUtil.init();
            NetLayer netLayer = NetFactory.getInstance().getNetLayerById(NetLayerIDs.TOR);
            JvmGlobalUtil.setNetLayerAndNetAddressNameService(netLayer, true);
            log.info("Connected to tor network");
            HAS_TOR = true;
        } catch (Throwable t) {
            log.error("Could not connect to tor: exiting", t);
            System.exit(1);
        }
    }

    // if unspecified, default relay to home.trsst.com
    if (System.getProperty("com.trsst.server.relays") == null) {
        System.setProperty("com.trsst.server.relays", "https://home.trsst.com/feed");
    }

    // default to user-friendlier file names
    String home = System.getProperty("user.home", ".");
    if (System.getProperty("com.trsst.client.storage") == null) {
        File client = new File(home, "Trsst Accounts");
        System.setProperty("com.trsst.client.storage", client.getAbsolutePath());
    }
    if (System.getProperty("com.trsst.server.storage") == null) {
        File server = new File(home, "Trsst System Cache");
        System.setProperty("com.trsst.server.storage", server.getAbsolutePath());
    }
    // TODO: try to detect if launching from external volume like a flash
    // drive and store on the local flash drive instead

    Console console = System.console();
    int result;
    try {
        if (console == null && argv.length == 0) {
            argv = new String[] { "serve", "--gui" };
        }
        result = new Command().doBegin(argv, System.out, System.in);

        // task queue prevents exit unless stopped
        if (TrsstAdapter.TASK_QUEUE != null) {
            TrsstAdapter.TASK_QUEUE.cancel();
        }
    } catch (Throwable t) {
        result = 1; // "general catchall error code"
        log.error("Unexpected error, exiting.", t);
    }

    // if error
    if (result != 0) {
        // force exit
        System.exit(result);
    }
}

From source file:me.timothy.ddd.DrunkDuckDispatch.java

License:asdf

public static void main(String[] args) throws LWJGLException {
    try {//from w ww .  j  a  va 2  s  .c om
        float defaultDisplayWidth = SizeScaleSystem.EXPECTED_WIDTH / 2;
        float defaultDisplayHeight = SizeScaleSystem.EXPECTED_HEIGHT / 2;
        boolean fullscreen = false, defaultDisplay = !fullscreen;
        File resolutionInfo = new File("graphics.json");

        if (resolutionInfo.exists()) {
            try (FileReader fr = new FileReader(resolutionInfo)) {
                JSONObject obj = (JSONObject) new JSONParser().parse(fr);
                Set<?> keys = obj.keySet();
                for (Object o : keys) {
                    if (o instanceof String) {
                        String key = (String) o;
                        switch (key.toLowerCase()) {
                        case "width":
                            defaultDisplayWidth = JSONCompatible.getFloat(obj, key);
                            break;
                        case "height":
                            defaultDisplayHeight = JSONCompatible.getFloat(obj, key);
                            break;
                        case "fullscreen":
                            fullscreen = JSONCompatible.getBoolean(obj, key);
                            defaultDisplay = !fullscreen;
                            break;
                        }
                    }
                }
            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }
            float expHeight = defaultDisplayWidth
                    * (SizeScaleSystem.EXPECTED_HEIGHT / SizeScaleSystem.EXPECTED_WIDTH);
            float expWidth = defaultDisplayHeight
                    * (SizeScaleSystem.EXPECTED_WIDTH / SizeScaleSystem.EXPECTED_HEIGHT);
            if (Math.round(defaultDisplayWidth) != Math.round(expWidth)) {
                if (defaultDisplayHeight < expHeight) {
                    System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n",
                            defaultDisplayWidth, defaultDisplayHeight, defaultDisplayWidth, expHeight);
                    defaultDisplayHeight = expHeight;
                } else {
                    System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n",
                            defaultDisplayWidth, defaultDisplayHeight, expWidth, defaultDisplayHeight);
                    defaultDisplayWidth = expWidth;
                }
            }
        }
        File dir = null;
        String os = getOS();
        if (os.equals("windows")) {
            dir = new File(System.getenv("APPDATA"), "timgames/");
        } else {
            dir = new File(System.getProperty("user.home"), ".timgames/");
        }
        File lwjglDir = new File(dir, "lwjgl-2.9.1/");
        Resources.init();
        Resources.downloadIfNotExists(lwjglDir, "lwjgl-2.9.1.zip", "http://umad-barnyard.com/lwjgl-2.9.1.zip",
                "Necessary LWJGL natives couldn't be found, I can attempt "
                        + "to download it, but I make no promises",
                "Unfortunately I was unable to download it, so I'll open up the "
                        + "link to the official download. Make sure you get LWJGL version 2.9.1, "
                        + "and you put it at " + dir.getAbsolutePath() + "/lwjgl-2.9.1.zip",
                new Runnable() {

                    @Override
                    public void run() {
                        if (!Desktop.isDesktopSupported()) {
                            JOptionPane.showMessageDialog(null,
                                    "I couldn't " + "even do that! Download it manually and try again");
                            return;
                        }

                        try {
                            Desktop.getDesktop().browse(new URI("http://www.lwjgl.org/download.php"));
                        } catch (IOException | URISyntaxException e) {
                            JOptionPane.showMessageDialog(null,
                                    "Oh cmon.. Address is http://www.lwjgl.org/download.php, good luck");
                            System.exit(1);
                        }
                    }

                }, 5843626);

        Resources.extractIfNotFound(lwjglDir, "lwjgl-2.9.1.zip", "lwjgl-2.9.1");
        System.setProperty("org.lwjgl.librarypath",
                new File(dir, "lwjgl-2.9.1/lwjgl-2.9.1/native/" + os).getAbsolutePath()); // deal w/ it
        System.setProperty("net.java.games.input.librarypath", System.getProperty("org.lwjgl.librarypath"));

        Resources.downloadIfNotExists("entities.json", "http://umad-barnyard.com/ddd/entities.json", 16142);
        Resources.downloadIfNotExists("map.binary", "http://umad-barnyard.com/ddd/map.binary", 16142);
        Resources.downloadIfNotExists("victory.txt", "http://umad-barnyard.com/ddd/victory.txt", 168);
        Resources.downloadIfNotExists("failure.txt", "http://umad-barnyard.com/ddd/failure.txt", 321);
        File resFolder = new File("resources/");
        if (!resFolder.exists() && !new File("player-still.png").exists()) {
            Resources.downloadIfNotExists("resources.zip", "http://umad-barnyard.com/ddd/resources.zip", 54484);
            Resources.extractIfNotFound(new File("."), "resources.zip", "player-still.png");
            new File("resources.zip").delete();
        }
        File soundFolder = new File("sounds/");
        if (!soundFolder.exists()) {
            soundFolder.mkdirs();
            Resources.downloadIfNotExists("sounds/sounds.zip", "http://umad-barnyard.com/ddd/sounds.zip",
                    1984977);
            Resources.extractIfNotFound(soundFolder, "sounds.zip", "asdfasdffadasdf");
            new File(soundFolder, "sounds.zip").delete();
        }
        AppGameContainer appgc;
        ddd = new DrunkDuckDispatch();
        appgc = new AppGameContainer(ddd);
        appgc.setTargetFrameRate(60);
        appgc.setShowFPS(false);
        appgc.setAlwaysRender(true);
        if (fullscreen) {
            DisplayMode[] modes = Display.getAvailableDisplayModes();
            DisplayMode current, best = null;
            float ratio = 0f;
            for (int i = 0; i < modes.length; i++) {
                current = modes[i];
                float rX = (float) current.getWidth() / SizeScaleSystem.EXPECTED_WIDTH;
                float rY = (float) current.getHeight() / SizeScaleSystem.EXPECTED_HEIGHT;
                System.out.println(current.getWidth() + "x" + current.getHeight() + " -> " + rX + "x" + rY);
                if (rX == rY && rX > ratio) {
                    best = current;
                    ratio = rX;
                }
            }
            if (best == null) {
                System.out.println("Failed to find an appropriately scaled resolution, using default display");
                defaultDisplay = true;
            } else {
                appgc.setDisplayMode(best.getWidth(), best.getHeight(), true);
                SizeScaleSystem.setRealHeight(best.getHeight());
                SizeScaleSystem.setRealWidth(best.getWidth());
                System.out.println("I choose " + best.getWidth() + "x" + best.getHeight());
            }
        }

        if (defaultDisplay) {
            SizeScaleSystem.setRealWidth(Math.round(defaultDisplayWidth));
            SizeScaleSystem.setRealHeight(Math.round(defaultDisplayHeight));
            appgc.setDisplayMode(Math.round(defaultDisplayWidth), Math.round(defaultDisplayHeight), false);
        }
        ddd.logger.info(
                "SizeScaleSystem: " + SizeScaleSystem.getRealWidth() + "x" + SizeScaleSystem.getRealHeight());
        appgc.start();
    } catch (SlickException ex) {
        LogManager.getLogger(DrunkDuckDispatch.class.getSimpleName()).catching(Level.ERROR, ex);
    }
}