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:com.dlmu.heipacker.crawler.client.ClientKerberosAuthentication.java

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

    System.setProperty("java.security.auth.login.config", "login.conf");
    System.setProperty("java.security.krb5.conf", "krb5.conf");
    System.setProperty("sun.security.krb5.debug", "true");
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*  w w  w .j  a va  2 s  . co m*/
        httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory());

        Credentials use_jaas_creds = new Credentials() {

            public String getPassword() {
                return null;
            }

            public Principal getUserPrincipal() {
                return null;
            }

        };

        httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), use_jaas_creds);

        HttpUriRequest request = new HttpGet("http://kerberoshost/");
        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        System.out.println("----------------------------------------");
        if (entity != null) {
            System.out.println(EntityUtils.toString(entity));
        }
        System.out.println("----------------------------------------");

        // This ensures the connection gets released back to the manager
        EntityUtils.consume(entity);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:io.s4.MainApp.java

public static void main(String args[]) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(//w ww. j av  a2  s. com
            OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a"));

    options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d"));

    options.addOption(OptionBuilder.withArgName("seedtime").hasArg()
            .withDescription("event clock initialization time").create("s"));

    options.addOption(
            OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e"));

    options.addOption(
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;
    String clockType = "wall";

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    if (commandLine.hasOption("a")) {
        appsHome = commandLine.getOptionValue("a");
    }

    if (commandLine.hasOption("d")) {
        clockType = commandLine.getOptionValue("d");
    }

    if (commandLine.hasOption("e")) {
        extsHome = commandLine.getOptionValue("e");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    long seedTime = 0;
    if (commandLine.hasOption("s")) {
        seedTime = Long.parseLong(commandLine.getOptionValue("s"));
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    File appsHomeFile = new File(appsHome);
    if (!appsHomeFile.isDirectory()) {
        System.err.println("Bad applications home: " + appsHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    List loArgs = commandLine.getArgList();

    if (loArgs.size() < 1) {
        // System.err.println("No bean configuration file specified");
        // System.exit(1);
    }

    // String s4ConfigXml = (String) loArgs.get(0);
    // System.out.println("s4ConfigXml is " + s4ConfigXml);

    ClassPathResource propResource = new ClassPathResource("s4-core.properties");
    Properties prop = new Properties();
    if (propResource.exists()) {
        prop.load(propResource.getInputStream());
    } else {
        System.err.println("Unable to find s4-core.properties. It must be available in classpath");
        System.exit(1);
    }

    ApplicationContext coreContext = null;
    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = "";
    List<String> coreConfigUrls = new ArrayList<String>();
    File configFile = null;

    // load clock configuration
    configPath = configBase + File.separatorChar + clockType + "-clock.xml";
    coreConfigUrls.add(configPath);

    // load core config xml
    configPath = configBase + File.separatorChar + "s4-core-conf.xml";
    configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("S4 core config file %s does not exist\n", configPath);
        System.exit(1);
    }

    coreConfigUrls.add(configPath);
    String[] coreConfigFiles = new String[coreConfigUrls.size()];
    coreConfigUrls.toArray(coreConfigFiles);

    String[] coreConfigFileUrls = new String[coreConfigFiles.length];
    for (int i = 0; i < coreConfigFiles.length; i++) {
        coreConfigFileUrls[i] = "file:" + coreConfigFiles[i];
    }

    coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext);
    ApplicationContext context = coreContext;

    Clock s4Clock = (Clock) context.getBean("clock");
    if (s4Clock instanceof EventClock && seedTime > 0) {
        EventClock s4EventClock = (EventClock) s4Clock;
        s4EventClock.updateTime(seedTime);
        System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime());
    }

    PEContainer peContainer = (PEContainer) context.getBean("peContainer");

    Watcher w = (Watcher) context.getBean("watcher");
    w.setConfigFilename(configPath);

    // load extension modules
    String[] configFileNames = getModuleConfigFiles(extsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
    }

    // load application modules
    configFileNames = getModuleConfigFiles(appsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
        // attach any beans that implement ProcessingElement to the PE
        // Container
        String[] processingElementBeanNames = context.getBeanNamesForType(ProcessingElement.class);
        for (String processingElementBeanName : processingElementBeanNames) {
            Object bean = context.getBean(processingElementBeanName);
            try {
                Method getS4ClockMethod = bean.getClass().getMethod("getS4Clock");

                if (getS4ClockMethod.getReturnType().equals(Clock.class)) {
                    if (getS4ClockMethod.invoke(bean) == null) {
                        Method setS4ClockMethod = bean.getClass().getMethod("setS4Clock", Clock.class);
                        setS4ClockMethod.invoke(bean, coreContext.getBean("clock"));
                    }
                }
            } catch (NoSuchMethodException mnfe) {
                // acceptable
            }
            System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id "
                    + ((ProcessingElement) bean).getId());
            peContainer.addProcessor((ProcessingElement) bean, processingElementBeanName);
        }
    }
}

From source file:com.fusesource.customer.wssec.client.Main.java

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

    try {//from  www . j  a  v  a 2  s  .co m
        CommandLine cli = new PosixParser().parse(opts, args);

        timestamp = cli.hasOption("timestamp");
        encrypt = cli.hasOption("encrypt");
        sign = cli.hasOption("sign");
        usernameToken = cli.hasOption("username-token");
        passwordDigest = cli.hasOption("password-digest");
        user = cli.getOptionValue("user");
        pw = cli.getOptionValue("pw");
        disableCNCheck = !cli.hasOption("ecnc");

        if (cli.hasOption("help") || !(sign | encrypt | usernameToken | timestamp)) {
            printUsageAndExit();
        }

        if (sign) {
            sigCertAlias = cli.getOptionValue("sa");
            sigCertPw = cli.getOptionValue("spw");
            sigKsLoc = cli.getOptionValue("sk");
            sigKsPw = cli.getOptionValue("skpw");

            if (sigCertAlias == null || sigKsLoc == null || sigKsPw == null || sigCertPw == null) {
                printUsageAndExit(
                        "You must provide keystore, keystore password, cert alias and cert password for signing certificate");
            }
        }

        if (encrypt) {
            encCertAlias = cli.getOptionValue("ea");
            encKsLoc = cli.getOptionValue("ek");
            encKsPw = cli.getOptionValue("ekpw");

            if (encCertAlias == null || encKsLoc == null || encKsPw == null) {
                printUsageAndExit(
                        "You must provide keystore, keystore password, and cert alias for encryption certificate");
            }
        }

    } catch (ParseException ex) {
        printUsageAndExit();
    }

    // Here we set the truststore for the client - by trusting the CA (in the 
    // truststore.jks file) we implicitly trust all services presenting certificates
    // signed by this CA.
    //
    System.setProperty("javax.net.ssl.trustStore", "../certs/truststore.jks");
    System.setProperty("javax.net.ssl.trustStorePassword", "truststore");

    URL wsdl = new URL("https://localhost:8443/cxf/Customers?wsdl");

    // The demo certs provided with this example configure the server with a certificate 
    // called 'fuse-esb'. As this probably won't match the fully-qualified domain
    // name of the machine you're running on, we need to disable Common Name matching
    // to allow the JVM runtime to happily resolve the WSDL for the server. Note that
    // we also have to do something similar on the CXf proxy itself (see below).
    //
    if (disableCNCheck) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        });
    }

    // Initialise the bus
    //
    Bus bus = SpringBusFactory.newInstance().createBus();
    SpringBusFactory.setDefaultBus(bus);

    // Define the properties to configure the WS Security Handler
    //
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(WSHandlerConstants.ACTION, getWSSecActions());

    // Specify the callback handler for passwords.
    //
    PasswordCallback passwords = new PasswordCallback();
    props.put(WSHandlerConstants.PW_CALLBACK_REF, passwords);

    if (usernameToken) {
        passwords.addUser(user, pw);
        props.put(WSHandlerConstants.USER, user);
        props.put(WSHandlerConstants.PASSWORD_TYPE, passwordDigest ? "PasswordDigest" : "PasswordText");
    }

    if (encrypt) {
        props.put(WSHandlerConstants.ENCRYPTION_USER, encCertAlias);
        props.put(WSHandlerConstants.ENC_PROP_REF_ID, "encProps");
        props.put("encProps", merlinCrypto(encKsLoc, encKsPw, encCertAlias));
        props.put(WSHandlerConstants.ENC_KEY_ID, "IssuerSerial");
        props.put(WSHandlerConstants.ENCRYPTION_PARTS, TIMESTAMP_AND_BODY);
    }

    if (sign) {
        props.put(WSHandlerConstants.SIGNATURE_USER, sigCertAlias);
        props.put(WSHandlerConstants.SIG_PROP_REF_ID, "sigProps");
        props.put("sigProps", merlinCrypto(sigKsLoc, sigKsPw, sigCertAlias));
        props.put(WSHandlerConstants.SIG_KEY_ID, "DirectReference");
        props.put(WSHandlerConstants.SIGNATURE_PARTS, TIMESTAMP_AND_BODY);

        passwords.addUser(sigCertAlias, sigCertPw);
    }

    // Here we add the WS Security interceptor to perform security processing
    // on the outgoing SOAP messages. Also, we configure a logging interceptor
    // to log the message payload for inspection. 
    //
    bus.getOutInterceptors().add(new WSS4JOutInterceptor(props));
    bus.getOutInterceptors().add(new LoggingOutInterceptor());

    CustomerService svc = new CustomerService_Service(wsdl).getPort(
            new QName("http://demo.fusesource.com/wsdl/CustomerService/", "SOAPOverHTTP"),
            CustomerService.class);

    // The demo certs provided with this example configure the server with a certificate 
    // called 'fuse-esb'. As this probably won't match the fully-qualified domain
    // name of the machine you're running on, we need to disable Common Name matching
    // to allow the CXF runtime to happily invoke on the server.
    //
    if (disableCNCheck) {
        HTTPConduit httpConduit = (HTTPConduit) ClientProxy.getClient(svc).getConduit();
        TLSClientParameters tls = new TLSClientParameters();
        tls.setDisableCNCheck(true);
        httpConduit.setTlsClientParameters(tls);
    }
    System.out.println("Looking up the customer...");

    // Here's the part where we invoke on the web service. 
    //
    Customer c = svc.lookupCustomer("007");

    System.out.println("Got customer " + c.getFirstName());

}

From source file:com.alvermont.terraj.fracplanet.GLTerrainViewer.java

/**
 * The entrypoint to the program/*from w w w. ja  v a  2s.com*/
 *
 * @param args The command line arguments
 */
public static void main(String[] args) {
    try {

        System.setProperty("sun.java2d.opengl", "false");
        System.setProperty("sun.java2d.noddraw", "true");

        final GLTerrainViewer me = new GLTerrainViewer();

        me.run();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.ibm.replication.iidr.utils.Bookmarks.java

public static void main(String[] args) throws ConfigurationException, IllegalArgumentException,
        IllegalAccessException, FileNotFoundException, IOException {
    System.setProperty("log4j.configurationFile",
            System.getProperty("user.dir") + File.separatorChar + "conf" + File.separatorChar + "log4j2.xml");
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig("com.ibm.replication.iidr.utils.Bookmarks");
    loggerConfig.setLevel(Level.DEBUG);
    ctx.updateLoggers();//from ww  w  .  j a v a 2  s  . c o m
    new Bookmarks("EventLogBookmarks.properties");
}

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

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

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

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

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

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

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

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

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

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

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

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

From source file:com.palantir.atlasdb.shell.AtlasShellCli.java

public static void main(String[] args) {
    System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "WARN");
    AtlasShellCli.create(new DefaultAtlasShellContextFactory()).run(args);
}

From source file:com.ict.dtube.tools.command.MQAdminStartup.java

public static void main(String[] args) {
    System.setProperty(RemotingCommand.RemotingVersionKey, Integer.toString(MQVersion.CurrentVersion));

    try {/*from   w  w w.  ja  va  2 s  .c  o  m*/
        initLogback();
        switch (args.length) {
        case 0:
            printHelp();
            break;
        case 2:
            if (args[0].equals("help")) {
                SubCommand cmd = findSubCommand(args[1]);
                if (cmd != null) {
                    Options options = ServerUtil.buildCommandlineOptions(new Options());
                    options = cmd.buildCommandlineOptions(options);
                    if (options != null) {
                        ServerUtil.printCommandLineHelp("mqadmin " + cmd.commandName(), options);
                    }
                } else {
                    System.out.println("The sub command \'" + args[1] + "\' not exist.");
                }
                break;
            }
        case 1:
        default:
            SubCommand cmd = findSubCommand(args[0]);
            if (cmd != null) {
                // mainargs?args?
                String[] subargs = parseSubArgs(args);

                // ?
                Options options = ServerUtil.buildCommandlineOptions(new Options());
                final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs,
                        cmd.buildCommandlineOptions(options), new PosixParser());
                if (null == commandLine) {
                    System.exit(-1);
                    return;
                }

                if (commandLine.hasOption('n')) {
                    String namesrvAddr = commandLine.getOptionValue('n');
                    System.setProperty(MixAll.NAMESRV_ADDR_PROPERTY, namesrvAddr);
                }

                cmd.execute(commandLine, options);
            } else {
                System.out.println("The sub command \'" + args[0] + "\' not exist.");
            }
            break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.github.retz.cli.Launcher.java

public static void main(String... argv) {
    System.setProperty("org.slf4j.simpleLogger.log.defaultLogLevel", "DEBUG");

    if (argv.length < 1) {
        help();//  w  ww.  j av a2 s.  c  o  m
        System.exit(-1);
    }

    int status = execute(argv);
    System.exit(status);
}

From source file:ch.systemsx.cisd.openbis.generic.server.dataaccess.db.IndexCreationUtil.java

public static void main(final String[] args) throws Exception {
    Parameters parameters = null;//from ww w  .  j a va  2 s . com
    try {
        parameters = new Parameters(args);
    } catch (IllegalArgumentException e) {
        System.out.println(Parameters.getUsage());
        System.exit(1);
        return; // for Eclipse
    }
    LogInitializer.init();
    String databaseKind = parameters.getDatabaseKind();
    String duplicatedDatabaseKind = parameters.getDuplicatedDatabaseKind();
    String indexFolder = parameters.getIndexFolder();
    if (duplicatedDatabaseKind != null) {

        String databaseName = DATABASE_NAME_PREFIX + databaseKind;
        String duplicatedDatabaseName = DATABASE_NAME_PREFIX + duplicatedDatabaseKind;
        boolean ok = duplicateDatabase(duplicatedDatabaseName, databaseName);
        if (ok == false) {
            System.exit(1);
        }
        File dumpFile = parameters.getDumpFile();
        operationLog.info("Dump '" + duplicatedDatabaseName + "' into '" + dumpFile + "'.");
        DumpPreparator.createDatabaseDump(duplicatedDatabaseName, dumpFile);
        databaseKind = duplicatedDatabaseKind;
        FileUtilities.deleteRecursively(new File(indexFolder));
    }
    System.setProperty("database.kind", databaseKind);
    // Deactivate the indexing in the application context loaded by Spring.
    System.setProperty("hibernate.search.index-mode", "NO_INDEX");
    System.setProperty("hibernate.search.index-base", indexFolder);
    System.setProperty("database.create-from-scratch", "false");
    hibernateSearchContext = createHibernateSearchContext(indexFolder);
    hibernateSearchContext.afterPropertiesSet();
    operationLog.info("=========== Start indexing ===========");
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    performFullTextIndex();
    stopWatch.stop();
    operationLog.info("Index of database '" + DATABASE_NAME_PREFIX + databaseKind + "' successfully built in '"
            + indexFolder + "' after " + ((stopWatch.getTime() + 30000) / 60000) + " minutes.");
    System.exit(0);
}