Example usage for java.lang System getProperties

List of usage examples for java.lang System getProperties

Introduction

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

Prototype

public static Properties getProperties() 

Source Link

Document

Determines the current system properties.

Usage

From source file:fr.jayasoft.ivy.Main.java

public static void main(String[] args) throws Exception {
    Options options = getOptions();//from  w  ww .j a  v  a2s.c  o m

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("?")) {
            usage(options);
            return;
        }

        if (line.hasOption("debug")) {
            Message.init(new DefaultMessageImpl(Message.MSG_DEBUG));
        } else if (line.hasOption("verbose")) {
            Message.init(new DefaultMessageImpl(Message.MSG_VERBOSE));
        } else if (line.hasOption("warn")) {
            Message.init(new DefaultMessageImpl(Message.MSG_WARN));
        } else if (line.hasOption("error")) {
            Message.init(new DefaultMessageImpl(Message.MSG_ERR));
        } else {
            Message.init(new DefaultMessageImpl(Message.MSG_INFO));
        }

        boolean validate = line.hasOption("novalidate") ? false : true;

        Ivy ivy = new Ivy();
        ivy.addAllVariables(System.getProperties());
        if (line.hasOption("m2compatible")) {
            ivy.setVariable("ivy.default.configuration.m2compatible", "true");
        }

        configureURLHandler(line.getOptionValue("realm", null), line.getOptionValue("host", null),
                line.getOptionValue("username", null), line.getOptionValue("passwd", null));

        String confPath = line.getOptionValue("conf", "");
        if ("".equals(confPath)) {
            ivy.configureDefault();
        } else {
            File conffile = new File(confPath);
            if (!conffile.exists()) {
                error(options, "ivy configuration file not found: " + conffile);
            } else if (conffile.isDirectory()) {
                error(options, "ivy configuration file is not a file: " + conffile);
            }
            ivy.configure(conffile);
        }

        File cache = new File(
                ivy.substitute(line.getOptionValue("cache", ivy.getDefaultCache().getAbsolutePath())));
        if (!cache.exists()) {
            cache.mkdirs();
        } else if (!cache.isDirectory()) {
            error(options, cache + " is not a directory");
        }

        String[] confs;
        if (line.hasOption("confs")) {
            confs = line.getOptionValues("confs");
        } else {
            confs = new String[] { "*" };
        }

        File ivyfile;
        if (line.hasOption("dependency")) {
            String[] dep = line.getOptionValues("dependency");
            if (dep.length != 3) {
                error(options,
                        "dependency should be expressed with exactly 3 arguments: organisation module revision");
            }
            ivyfile = File.createTempFile("ivy", ".xml");
            ivyfile.deleteOnExit();
            DefaultModuleDescriptor md = DefaultModuleDescriptor
                    .newDefaultInstance(ModuleRevisionId.newInstance(dep[0], dep[1] + "-caller", "working"));
            DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md,
                    ModuleRevisionId.newInstance(dep[0], dep[1], dep[2]), false, false, true);
            for (int i = 0; i < confs.length; i++) {
                dd.addDependencyConfiguration("default", confs[i]);
            }
            md.addDependency(dd);
            XmlModuleDescriptorWriter.write(md, ivyfile);
            confs = new String[] { "default" };
        } else {
            ivyfile = new File(ivy.substitute(line.getOptionValue("ivy", "ivy.xml")));
            if (!ivyfile.exists()) {
                error(options, "ivy file not found: " + ivyfile);
            } else if (ivyfile.isDirectory()) {
                error(options, "ivy file is not a file: " + ivyfile);
            }
        }

        ResolveReport report = ivy.resolve(ivyfile.toURL(), null, confs, cache, null, validate, false, true,
                line.hasOption("useOrigin"), null);
        if (report.hasError()) {
            System.exit(1);
        }
        ModuleDescriptor md = report.getModuleDescriptor();

        if (confs.length == 1 && "*".equals(confs[0])) {
            confs = md.getConfigurationsNames();
        }
        if (line.hasOption("retrieve")) {
            String retrievePattern = ivy.substitute(line.getOptionValue("retrieve"));
            if (retrievePattern.indexOf("[") == -1) {
                retrievePattern = retrievePattern + "/lib/[conf]/[artifact].[ext]";
            }
            ivy.retrieve(md.getModuleRevisionId().getModuleId(), confs, cache, retrievePattern, null, null,
                    line.hasOption("sync"), line.hasOption("useOrigin"));
        }
        if (line.hasOption("cachepath")) {
            outputCachePath(ivy, cache, md, confs, line.getOptionValue("cachepath", "ivycachepath.txt"));
        }

        if (line.hasOption("revision")) {
            ivy.deliver(md.getResolvedModuleRevisionId(), ivy.substitute(line.getOptionValue("revision")),
                    cache, ivy.substitute(line.getOptionValue("deliverto", "ivy-[revision].xml")),
                    ivy.substitute(line.getOptionValue("status", "release")), null,
                    new DefaultPublishingDRResolver(), validate);
            if (line.hasOption("publish")) {
                ivy.publish(md.getResolvedModuleRevisionId(), ivy.substitute(line.getOptionValue("revision")),
                        cache,
                        ivy.substitute(line.getOptionValue("publishpattern",
                                "distrib/[type]s/[artifact]-[revision].[ext]")),
                        line.getOptionValue("publish"),
                        ivy.substitute(line.getOptionValue("deliverto", "ivy-[revision].xml")), validate);

            }
        }
        if (line.hasOption("main")) {
            invoke(ivy, cache, md, confs, line.getOptionValue("main"), line.getOptionValues("args"));
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());

        usage(options);
    }
}

From source file:au.com.jwatmuff.eventmanager.Main.java

/**
 * Main method.//ww w . j  av a  2 s .  c o  m
 */
public static void main(String args[]) {
    LogUtils.setupUncaughtExceptionHandler();

    /* Set timeout for RMI connections - TODO: move to external file */
    System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000");
    updateRmiHostName();

    /*
     * Set up menu bar for Mac
     */
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager");

    /*
     * Set look and feel to 'system' style
     */
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        log.info("Failed to set system look and feel");
    }

    /*
     * Set workingDir to a writable folder for storing competitions, settings etc.
     */
    String applicationData = System.getenv("APPDATA");
    if (applicationData != null) {
        workingDir = new File(applicationData, "EventManager");
        if (workingDir.exists() || workingDir.mkdirs()) {
            // redirect logging to writable folder
            LogUtils.reconfigureFileAppenders("log4j.properties", workingDir);
        } else {
            workingDir = new File(".");
        }
    }

    // log version for debugging
    log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")");

    /*
     * Copy license if necessary
     */
    File license1 = new File("license.lic");
    File license2 = new File(workingDir, "license.lic");
    if (license1.exists() && !license2.exists()) {
        try {
            FileUtils.copyFile(license1, license2);
        } catch (IOException e) {
            log.warn("Failed to copy license from " + license1 + " to " + license2, e);
        }
    }
    if (license1.exists() && license2.exists()) {
        if (license1.lastModified() > license2.lastModified()) {
            try {
                FileUtils.copyFile(license1, license2);
            } catch (IOException e) {
                log.warn("Failed to copy license from " + license1 + " to " + license2, e);
            }
        }
    }

    /*
     * Check if run lock exists, if so ask user if it is ok to continue
     */
    if (!obtainRunLock(false)) {
        int response = JOptionPane.showConfirmDialog(null,
                "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?",
                "Run-lock detected", JOptionPane.YES_NO_OPTION);
        if (response == JOptionPane.YES_OPTION)
            obtainRunLock(true);
        else
            System.exit(0);
    }

    try {
        LoadWindow loadWindow = new LoadWindow();
        loadWindow.setVisible(true);

        loadWindow.addMessage("Reading settings..");

        /*
         * Read properties from file
         */
        final Properties props = new Properties();
        try {
            Properties defaultProps = PropertiesLoaderUtils
                    .loadProperties(new ClassPathResource("eventmanager.properties"));
            props.putAll(defaultProps);
        } catch (IOException ex) {
            log.error(ex);
        }

        props.putAll(System.getProperties());

        File databaseStore = new File(workingDir, "comps");
        int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port"));

        loadWindow.addMessage("Loading Peer Manager..");
        log.info("Loading Peer Manager");

        ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService();
        JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat"));
        peerManager.addDiscoveryService(manualDiscoveryService);

        monitorNetworkInterfaceChanges(peerManager);

        loadWindow.addMessage("Loading Database Manager..");
        log.info("Loading Database Manager");

        DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager);
        LicenseManager licenseManager = new LicenseManager(workingDir);

        loadWindow.addMessage("Loading Load Competition Dialog..");
        log.info("Loading Load Competition Dialog");

        LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager,
                peerManager);
        loadCompetitionWindow.setTitle(WINDOW_TITLE);

        loadWindow.dispose();
        log.info("Starting Load Competition Dialog");

        while (true) {
            // reset permission checker to use our license
            licenseManager.updatePermissionChecker();

            GUIUtils.runModalJFrame(loadCompetitionWindow);

            if (loadCompetitionWindow.getSuccess()) {
                DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo();

                if (!databaseManager.checkLock(info.id)) {
                    String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n"
                            + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n"
                            + "3) Delete the competition from this computer\n"
                            + "4) If possible, reload this competition from another computer on the network\n"
                            + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked.";
                    String title = "WARNING: Potential Data Corruption Detected";

                    int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION,
                            JOptionPane.ERROR_MESSAGE, null,
                            new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)");

                    if (status == 0)
                        continue; // return to load competition window
                }

                SynchronizingWindow syncWindow = new SynchronizingWindow();
                syncWindow.setVisible(true);
                long t = System.nanoTime();
                DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash);
                long dt = System.nanoTime() - t;
                log.debug(String.format("Initial sync in %dms",
                        TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS)));
                syncWindow.dispose();

                if (loadCompetitionWindow.isNewDatabase()) {
                    GregorianCalendar calendar = new GregorianCalendar();
                    Date today = calendar.getTime();
                    calendar.set(Calendar.MONTH, Calendar.DECEMBER);
                    calendar.set(Calendar.DAY_OF_MONTH, 31);
                    Date endOfYear = new java.sql.Date(calendar.getTimeInMillis());

                    CompetitionInfo ci = new CompetitionInfo();
                    ci.setName(info.name);
                    ci.setStartDate(today);
                    ci.setEndDate(today);
                    ci.setAgeThresholdDate(endOfYear);
                    //ci.setPasswordHash(info.passwordHash);
                    License license = licenseManager.getLicense();
                    if (license != null) {
                        ci.setLicenseName(license.getName());
                        ci.setLicenseType(license.getType().toString());
                        ci.setLicenseContact(license.getContactPhoneNumber());
                    }
                    database.add(ci);
                }

                // Set PermissionChecker to use database's license type
                String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType();
                PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType));

                TransactionNotifier notifier = new TransactionNotifier();
                database.setListener(notifier);

                MainWindow mainWindow = new MainWindow();
                mainWindow.setDatabase(database);
                mainWindow.setNotifier(notifier);
                mainWindow.setPeerManager(peerManager);
                mainWindow.setLicenseManager(licenseManager);
                mainWindow.setManualDiscoveryService(manualDiscoveryService);
                mainWindow.setTitle(WINDOW_TITLE);
                mainWindow.afterPropertiesSet();

                TestUtil.setActivatedDatabase(database);

                // show main window (modally)
                GUIUtils.runModalJFrame(mainWindow);

                // shutdown procedures

                // System.exit();

                database.shutdown();
                databaseManager.deactivateDatabase(1500);

                if (mainWindow.getDeleteOnExit()) {
                    for (File file : info.localDirectory.listFiles())
                        if (!file.isDirectory())
                            file.delete();
                    info.localDirectory.deleteOnExit();
                }
            } else {
                // This can cause an RuntimeException - Peer is disconnected
                peerManager.stop();
                System.exit(0);
            }
        }
    } catch (Throwable e) {
        log.error("Error in main function", e);
        String message = e.getMessage();
        if (message == null)
            message = "";
        if (message.length() > 100)
            message = message.substring(0, 97) + "...";
        GUIUtils.displayError(null,
                "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message);
        System.exit(0);
    }
}

From source file:io.janusproject.Boot.java

/** Main function that is parsing the command line and launching
 * the first agent./*from   w  w w . j  av  a 2 s.co m*/
 *
 * @param args - command line arguments
 * @see #startJanus(Class, Class, Object...)
 */
public static void main(String[] args) {
    try {
        List<URL> propertyFiles = new ArrayList<>();
        Object[] freeArgs = parseCommandLine(args, propertyFiles);
        if (JanusConfig.getSystemPropertyAsBoolean(JanusConfig.JANUS_LOGO_SHOW_NAME,
                JanusConfig.JANUS_LOGO_SHOW)) {
            showJanusLogo();
        }
        if (freeArgs.length == 0) {
            showError(Locale.getString("NO_AGENT_QUALIFIED_NAME"), //$NON-NLS-1$
                    null);
        }
        String agentToLaunch = freeArgs[0].toString();
        freeArgs = Arrays.copyOfRange(freeArgs, 1, freeArgs.length, String[].class);
        // Load the agent class
        Class<? extends Agent> agent = loadAgentClass(agentToLaunch);
        assert (agent != null);
        // Load property files
        Properties systemProperties = System.getProperties();
        for (URL url : propertyFiles) {
            try (InputStream stream = url.openStream()) {
                systemProperties.load(stream);
            }
        }
        // Set the boot agent classname
        System.setProperty(JanusConfig.BOOT_AGENT, agent.getCanonicalName());

        startJanus(null, (Class<? extends Agent>) agent, freeArgs);
    } catch (Exception e) {
        showError(Locale.getString("LAUNCHING_ERROR", //$NON-NLS-1$
                e.getLocalizedMessage()), e);
        return;
    }
}

From source file:Main.java

public static boolean isMacOs() {

    Properties prop = System.getProperties();
    String os = prop.getProperty("os.name");
    // log.info("platform is:"+os);
    if (os.equals("Mac OS X")) {
        return true;
    }//  www . ja v a2  s . co  m

    return false;
}

From source file:Main.java

public static boolean isWindowsOS() {

    Properties prop = System.getProperties();
    String os = prop.getProperty("os.name");
    // log.info("platform is:"+os);
    if (os.contains("Windows")) {
        return true;
    }//from   www  .  j a va2s  . c o  m

    return false;
}

From source file:Main.java

private static String getProperty(String property) {
    return (String) System.getProperties().get(property);
}

From source file:com.cic.datacrawl.ui.Main.java

/**
 * Main entry point. Creates a debugger attached to a Rhino
 * {@link com.cic.datacrawl.ui.shell.Shell} shell session.
 *///from  w w w .  j av a 2  s .c  om
public static void main(final String[] args) {
    if (System.getProperties().get("os.name").toString().toLowerCase().indexOf("linux") >= 0)
        System.setProperty("sun.awt.xembedserver", "true");
    try {
        String path = null;
        boolean reflash = true;
        if (args != null && args.length > 0) {
            if (args[0].equalsIgnoreCase("-h")) {
                System.out.println("Command Format: \n" + "\t%JAVA_HOME%\\BIN\\JAVA -jar homepageCatcher.jar "
                        + "[-d config path]\n" + "\t%JAVA_HOME%\\BIN\\JAVA -jar homepageCatcher.jar "
                        + "[-d config path_1;path_2;....;path_n]\n");
            }

            int pathIndex = ArrayUtils.indexOf(args, "-d");
            if (pathIndex >= 0) {
                try {
                    path = args[pathIndex + 1];
                    File f = new File(path);
                    if (!f.exists()) {
                        LOG.warn("Invalid path of configuration. " + "Using default configuration.");
                    }
                } catch (Throwable e) {
                    LOG.warn("Invalid path of configuration. " + "Using default configuration.");
                }
            }
            // int reflashIndex = ArrayUtils.indexOf(args, "-r");
            //
            // reflash = new Boolean(args[reflashIndex + 1]).booleanValue();
        }
        if (path == null || path.trim().length() == 0)
            path = Config.INSTALL_PATH + File.separator + "config" + File.separator + "beans";

        LOG.debug("Config Path: \"" + path + "\"");
        // ?IOC
        // ????
        // ?
        ApplicationContext.initialiaze(path, reflash);
        System.setProperty(ApplicationContext.CONFIG_PATH, path);
        // js???
        InitializerRegister.getInstance().execute();
        // ???
        //VerifyCodeInputDialog.init();
        // ??
        //initTestData();
        // ?GUI
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                startupGUI(args);
            }
        });
        thread.setName("UI_Thread");
        thread.start();

    } catch (Throwable e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:Main.java

public static byte[] retrieveImageData_fromUrl(String imageUrl) throws IOException {
    URL url = new URL(imageUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");

    // determine the image size and allocate a buffer
    int fileSize = connection.getContentLength();
    byte[] imageData = new byte[fileSize];

    // download the file
    Log.d(TAG, "fetching image " + imageUrl + " (" + fileSize + ")");

    if (fileSize > 0) {

        BufferedInputStream istream = new BufferedInputStream(connection.getInputStream());
        int bytesRead = 0;
        int offset = 0;
        while (bytesRead != -1 && offset < fileSize) {
            bytesRead = istream.read(imageData, offset, fileSize - offset);
            offset += bytesRead;/* ww w. j  av a  2s . c o  m*/
        }

        istream.close();
    } else
        Log.d(TAG, "fileSize is 0! skipping");

    // clean up
    connection.disconnect();

    return imageData;
}

From source file:Main.java

public static String deleteUrl(String url, Bundle params) throws MalformedURLException, IOException {
    System.setProperty("http.keepAlive", "false");
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " agent");
    conn.setRequestMethod("DELETE");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setDoOutput(false);//  ww w.j  a  va2 s . c  o m
    conn.setDoInput(true);
    //conn.setRequestProperty("Connection", "Keep-Alive");
    conn.connect();

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:Main.java

public static String getUserHomeDir() {
    return System.getProperties().getProperty("user.home");
}