Example usage for java.lang System setProperties

List of usage examples for java.lang System setProperties

Introduction

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

Prototype

public static void setProperties(Properties props) 

Source Link

Document

Sets the system properties to the Properties argument.

Usage

From source file:com.baidu.jprotobuf.mojo.PreCompileMojo.java

/**
 * Execute goal./*w  ww.  ja v  a  2s.  c  o  m*/
 * 
 * @throws MojoExecutionException execution of the main class or one of the threads it generated failed.
 * @throws MojoFailureException something bad happened...
 */
public void execute() throws MojoExecutionException, MojoFailureException {
    if (isSkip()) {
        getLog().info("skipping execute as per configuraion");
        return;
    }
    if (killAfter != -1) {
        getLog().warn("Warning: killAfter is now deprecated. Do you need it ? Please comment on MEXEC-6.");
    }

    arguments = new String[] { outputParentDirectory.getAbsolutePath(), outputDirectory.getAbsolutePath(),
            filterClassPackage };

    if (getLog().isDebugEnabled()) {
        StringBuffer msg = new StringBuffer("Invoking : ");
        msg.append(mainClass);
        msg.append(".main(");
        for (int i = 0; i < arguments.length; i++) {
            if (i > 0) {
                msg.append(", ");
            }
            msg.append(arguments[i]);
        }
        msg.append(")");
        getLog().debug(msg);
    }

    final Log log = getLog();
    IsolatedThreadGroup threadGroup = new IsolatedThreadGroup(mainClass /* name */);
    Thread bootstrapThread = new Thread(threadGroup, new Runnable() {
        public void run() {
            long current = System.currentTimeMillis();
            try {

                Method main = Thread.currentThread().getContextClassLoader().loadClass(mainClass)
                        .getMethod("main", new Class[] { String[].class });
                if (!main.isAccessible()) {
                    getLog().debug("Setting accessibility to true in order to invoke main().");
                    main.setAccessible(true);
                }
                if (!Modifier.isStatic(main.getModifiers())) {
                    throw new MojoExecutionException(
                            "Can't call main(String[])-method because it is not static.");
                }
                main.invoke(null, new Object[] { arguments });
            } catch (NoSuchMethodException e) { // just pass it on
                Thread.currentThread().getThreadGroup().uncaughtException(Thread.currentThread(), new Exception(
                        "The specified mainClass doesn't contain a main method with appropriate signature.",
                        e));
            } catch (Exception e) { // just pass it on
                Thread.currentThread().getThreadGroup().uncaughtException(Thread.currentThread(), e);
            } finally {
                log.info("JProtobuf pre compile done time took: " + (System.currentTimeMillis() - current)
                        + "ms");
            }
        }
    }, mainClass + ".main()");
    bootstrapThread.setContextClassLoader(getClassLoader());
    setSystemProperties();

    bootstrapThread.start();
    joinNonDaemonThreads(threadGroup);
    // It's plausible that spontaneously a non-daemon thread might be created as we try and shut down,
    // but it's too late since the termination condition (only daemon threads) has been triggered.
    if (keepAlive) {
        getLog().warn(
                "Warning: keepAlive is now deprecated and obsolete. Do you need it? Please comment on MEXEC-6.");
        waitFor(0);
    }

    if (cleanupDaemonThreads) {

        terminateThreads(threadGroup);

        try {
            threadGroup.destroy();
        } catch (IllegalThreadStateException e) {
            getLog().warn("Couldn't destroy threadgroup " + threadGroup, e);
        }
    }

    if (originalSystemProperties != null) {
        System.setProperties(originalSystemProperties);
    }

    synchronized (threadGroup) {
        if (threadGroup.uncaughtException != null) {
            throw new MojoExecutionException("An exception occured while executing the Java class. "
                    + threadGroup.uncaughtException.getMessage(), threadGroup.uncaughtException);
        }
    }

    registerSourceRoots();
}

From source file:org.ikasan.filetransfer.xml.transform.DefaultXSLTransformer.java

/**
 * Creates a new <code>Templates</code> instance based on
 * the specified stylesheet./*from  w  ww  .j  a  v  a  2  s . c  o m*/
 *
 * @param xslSource - the source object that holds an XSL stylesheet URI,
 *                     input stream, etc.
 * @return Templates
 * @throws TransformerConfigurationException
 */
private Templates newTemplates(Source xslSource) throws TransformerConfigurationException {
    // Set the TransformerFactory system property to utilise translets
    // For more flexibility, load properties from a properties file
    // This will do the job for the time being
    logger.debug("Current TransformerFactory =[" + System.getProperty(TX_FACTORY_KEY) + "].");

    logger.debug("Setting a new TransformerFactory [" + TX_FACTORY_VALUE + "].");
    Properties props = System.getProperties();
    props.put(TX_FACTORY_KEY, TX_FACTORY_VALUE);
    System.setProperties(props);
    logger.debug("New TransformerFactory =[" + System.getProperty(TX_FACTORY_KEY) + "].");

    // Get a new TransformerFactory instance
    TransformerFactory tFactory = this.newTransformerFactory();

    // Create a new translet as a Templates object
    return tFactory.newTemplates(xslSource);
}

From source file:org.metaeffekt.dcc.commons.script.CommandScriptExecutor.java

private void executeCommandScriptForked(Commands command, File scriptFile, final Id<UnitId> unitId,
        Id<PackageId> packageId, final File executionPropertiesFile, File prerequisitesPropertiesFile) {

    // produce a properties file that serves as input for the forked ant execution
    Properties properties = new SortedProperties();
    properties.setProperty(DCC_COMMAND, command.toString());
    properties.setProperty(DCC_TARGET_DIR, executionContext.getTargetDir().getAbsolutePath());
    properties.setProperty(DCC_UNIT_ID, unitId.getValue());
    properties.setProperty(DCC_SOLUTION_DIR, executionContext.getSolutionDir().getAbsolutePath());
    properties.setProperty(DCC_PACKAGE_ID, packageId.getValue());
    properties.setProperty(DCC_PACKAGE_DIR, executionContext.getPackageDir().getAbsolutePath());
    properties.setProperty(DCC_JAVA_HOME, System.getProperty("java.home"));
    properties.setProperty(DCC_DEPLOYMENT_ID, executionContext.getDeploymentId().getValue());

    if (executionPropertiesFile != null) {
        properties.setProperty(DCC_EXECUTION_PROPERTIES, executionPropertiesFile.getAbsolutePath());
    }/*from w w  w  .  j a  v a 2  s  .c o m*/

    if (prerequisitesPropertiesFile != null) {
        properties.setProperty(DCC_PREREQUISITES_PROPERTIES, prerequisitesPropertiesFile.getAbsolutePath());
    }

    if (executionContext.getUpgradePropertiesFile() != null) {
        properties.setProperty(DCC_UPGRADE_PROPERTIES,
                executionContext.getUpgradePropertiesFile().getAbsolutePath());
    }

    // write the file to the file system to be ready for later
    String filename = unitId + "." + scriptFile.getName();
    filename = filename.replace(".xml", "_exec.properties");
    final File execPropertiesDir = new File(getExecutionContext().getWorkingDir(), "exec");
    File execProperties = new File(execPropertiesDir, filename);
    execProperties.getParentFile().mkdirs();

    try {
        PropertyUtils.writeToFile(properties, execProperties, "Properties exported for script " + scriptFile);
    } catch (IOException e) {
        throw new IllegalStateException("Cannot export properties for script " + scriptFile, e);
    }

    final File packageDir = new File(executionContext.getPackageDir(), packageId.getValue());
    final Project project = new ProjectAdapter();

    // all executions are relative to the package
    project.setBaseDir(packageDir);

    ExecTask exec = new ExecTask();
    exec.setProject(project);
    exec.setOutputproperty("exec.output");
    exec.setErrorProperty("exec.error");
    exec.setDir(packageDir);
    exec.setFailIfExecutionFails(true);
    exec.setResultProperty("exec.result");

    File antHome = determineAntHome();
    File antBin = determineAntExecutable(antHome);
    exec.setExecutable(antBin.getAbsolutePath());

    // provide ANT_HOME (may be not available or set to some other ANT causing unexpected issues)
    final Variable antHomeVar = new Variable();
    antHomeVar.setKey("ANT_HOME");
    antHomeVar.setValue(antHome.getPath());
    exec.addEnv(antHomeVar);

    // supply the JAVA_HOME (using the java the curren jvm runs with)
    final Variable javaHomeVar = new Variable();
    javaHomeVar.setKey("JAVA_HOME");
    javaHomeVar.setValue(System.getProperty("java.home"));
    exec.addEnv(javaHomeVar);

    // configure log4j for forked ant
    try {
        final URL log4jFileUrl = getClass().getResource("/log4j2.xml");
        if (log4jFileUrl != null) {
            File file = new File(log4jFileUrl.getFile());
            String log4jConfig = file.getAbsolutePath();
            File parentFile = file.getParentFile();
            File scriptLog4JFile = new File(parentFile, "log4j2-script-execution.xml");
            if (scriptLog4JFile.exists()) {
                log4jConfig = scriptLog4JFile.getAbsolutePath();
            }
            LOG.debug("Log4j2 configuration detected: " + log4jConfig);
            final Variable antOptsVar = new Variable();
            antOptsVar.setKey("ANT_OPTS");
            antOptsVar.setValue("-Dlog4j.configurationFile=" + log4jConfig);
            exec.addEnv(antOptsVar);
        } else {
            LOG.warn(
                    "Log4j2 configuration not detected. Script execution may report errors initializing logging.");
        }
    } catch (RuntimeException e) {
        LOG.error("Cannot configure ant to use log4j.", e);
    }

    Argument scriptFileArg = exec.createArg();
    String sfLine = "-f " + scriptFile.getAbsolutePath();
    scriptFileArg.setDescription(sfLine);
    scriptFileArg.setLine(sfLine);

    Argument propertyFileArg = exec.createArg();
    final String pfLine = "-propertyfile " + execProperties.getAbsolutePath();
    propertyFileArg.setLine(pfLine);
    propertyFileArg.setDescription(pfLine);

    // preserve properties to avoid side-effects in between script executions
    final Properties originalSystemProperties = isolateSystemProperties();
    try {
        // execute the scripts default target
        LOG.info("Executing [{}] [{}] [{}]", antBin.getAbsolutePath(), scriptFileArg.getDescription(),
                propertyFileArg.getDescription());
        exec.execute();
    } finally {
        // restore original properties
        System.setProperties(originalSystemProperties);
    }

    final String output = project.getProperty("exec.output");
    logOutput(output, false);

    final String errorContent = project.getProperty("exec.error");

    String[] lines = errorContent.split("\\r?\\n");

    for (int i = 0; i < lines.length; i++) {
        final boolean error = lines[i].startsWith("BUILD FAILED");
        // NOTE the error content alone is not sufficient. It may be an intermediate error from
        //   a script embedded exec call (with failonerror="false"). It is important that the
        //   line starts with "BUILD FAILED".
        if (error) {
            if (!StringUtils.isBlank(errorContent)) {
                StringBuilder sb = new StringBuilder();
                for (int j = i + 1; j < lines.length; j++) {
                    if (!StringUtils.isBlank(lines[j])) {
                        if (!lines[j].trim().startsWith("Total time:")) {
                            if (j != i + 1) {
                                sb.append("\n");
                            }
                            sb.append(lines[j].trim());
                        }
                    }
                }
                throw new BuildException(sb.toString());
            }
        }
    }

}

From source file:net.sf.joost.plugins.traxfilter.THResolver.java

/**
 * Creates new TH instance out of TrAX factory
 * @param method/* w ww. j  av a  2 s . co  m*/
 * @param source
 * @return TH
 */
protected TransformerHandler newTHOutOfTrAX(String method, Source source, Hashtable params,
        ErrorListener errorListener, URIResolver uriResolver) throws SAXException {
    if (DEBUG)
        log.debug("newTHOutOfTrAX()");

    SAXTransformerFactory saxtf;

    if (FACTORY.getValueStr().length() > 0) {
        // create factory as asked by the client
        try {
            saxtf = (SAXTransformerFactory) (Class.forName(FACTORY.getValueStr())).newInstance();
            if (DEBUG)
                log.debug("newTHOutOfTrAX(): use custom TrAX factory " + FACTORY.getValueStr());
        } catch (InstantiationException e) {
            throw new SAXException(e);
        } catch (ClassNotFoundException e) {
            throw new SAXException(e);
        } catch (IllegalAccessException e) {
            throw new SAXException(e);
        }

    } else if (STX_METHOD.equals(method)) {
        saxtf = new TransformerFactoryImpl();
        if (DEBUG)
            log.debug("newTHOutOfTrAX(): use default Joost factory " + saxtf.getClass().toString());
    } else {
        final String TFPROP = "javax.xml.transform.TransformerFactory";
        final String STXIMP = "net.sf.joost.trax.TransformerFactoryImpl";

        synchronized (SYNCHRONIZE_GUARD) {

            String propVal = System.getProperty(TFPROP);
            boolean propChanged = false;

            String xsltFac = System.getProperty(TrAXConstants.KEY_XSLT_FACTORY);
            if (xsltFac != null || STXIMP.equals(propVal)) {
                // change this property,
                // otherwise we wouldn't get an XSLT transformer
                if (xsltFac != null)
                    System.setProperty(TFPROP, xsltFac);
                else {
                    Properties props = System.getProperties();
                    props.remove(TFPROP);
                    System.setProperties(props);
                }
                propChanged = true;
            }

            saxtf = (SAXTransformerFactory) TransformerFactory.newInstance();

            if (propChanged) {
                // reset property
                if (propVal != null)
                    System.setProperty(TFPROP, propVal);
                else {
                    Properties props = System.getProperties();
                    props.remove(TFPROP);
                    System.setProperties(props);
                }
            }
        }

        if (DEBUG)
            log.debug("newTHOutOfTrAX(): use default TrAX factory " + saxtf.getClass().toString());
    }

    // set factory attributes
    setTraxFactoryAttributes(saxtf, params);
    setupTransformerFactory(saxtf, errorListener, uriResolver);

    try {
        if (DEBUG)
            log.debug("newTHOutOfTrAX(): creating factory's reusable TH");
        // TrAX way to create TH
        TransformerHandler th = saxtf.newTransformerHandler(source);
        setupTransformer(th.getTransformer(), errorListener, uriResolver);
        return th;
    } catch (TransformerConfigurationException ex) {
        throw new SAXException(ex);
    }

}

From source file:org.ops4j.pax.runner.Run.java

/**
 * By using provision service it installs provisioned bundles.
 *
 * @param provisionService installed provision service
 * @param schemaResolver   a provision schema resolver
 * @param context          the running context
 *//* www  . j  av  a  2 s.  co m*/
void installBundles(final ProvisionService provisionService, final ProvisionSchemaResolver schemaResolver,
        final Context context) {
    if (provisionService == null) {
        throw new RuntimeException("Could not resolve a provision service");
    }
    // build list of provisioning specs out of command line arguments and profiles
    final List<String> provisionSpecs = new ArrayList<String>();
    provisionSpecs.addAll(context.getCommandLine().getArguments());
    provisionSpecs.addAll(transformProfilesToProvisionSpecs(context));

    // backup properties and replace them with audited properties
    final Properties sysPropsBackup = System.getProperties();
    try {
        context.setSystemProperties(new AuditedProperties(sysPropsBackup));
        System.setProperties(context.getSystemProperties());

        final Set<ScannedBundle> scannedBundles = new HashSet<ScannedBundle>();
        // then scan those url's
        for (String provisionSpec : provisionSpecs) {
            try {
                try {
                    provisionService.wrap(filterUnique(scannedBundles, provisionService.scan(provisionSpec)))
                            .install();
                } catch (UnsupportedSchemaException e) {
                    final String resolvedProvisionURL = schemaResolver.resolve(provisionSpec);
                    if (resolvedProvisionURL != null && !resolvedProvisionURL.equals(provisionSpec)) {
                        provisionService
                                .wrap(filterUnique(scannedBundles, provisionService.scan(resolvedProvisionURL)))
                                .install();
                    } else {
                        throw e;
                    }
                }
            } catch (MalformedSpecificationException e) {
                throw new RuntimeException(e);
            } catch (ScannerException e) {
                throw new RuntimeException(e);
            } catch (BundleException e) {
                throw new RuntimeException(e);
            }
        }
    } finally {
        // restore the backup-ed properties
        System.setProperties(sysPropsBackup);
    }
}

From source file:org.metaeffekt.dcc.commons.script.CommandScriptExecutor.java

private static final Properties isolateSystemProperties() {
    final Properties originalSystemProperties = System.getProperties();
    final Properties tmpSystemProperties = new SortedProperties();
    tmpSystemProperties.putAll(originalSystemProperties);
    System.setProperties(tmpSystemProperties);
    return originalSystemProperties;
}

From source file:it.infn.ct.GridEngineInterface.java

/**
 * Retrieve the APIServerDaemon PATH to the GridEngineLogConfig.xml file and
 * setup the GridEngineLogConfig.path environment variable accordingly This
 * variable will be taken by GridEngine while building up its log.
 *//*w w w  . j  a v a2s  .c  o m*/
private void setupGELogConfig() {
    URL geLogConfig = this.getClass().getResource("GridEngineLogConfig.xml");
    String geLogConfigEnvVar = geLogConfig.getPath();

    LOG.debug("GridEngineLogConfig.xml at '" + geLogConfigEnvVar + "'");

    Properties props = System.getProperties();

    props.setProperty("GridEngineLogConfig.path", geLogConfigEnvVar);
    System.setProperties(props);
}

From source file:com.agilejava.docbkx.maven.AbstractTransformerMojo.java

/**
 * Allows classes to add their own specific post-processing logic.
 *
 * @throws MojoExecutionException If the Mojo fails to post-process the results.
 *//*from w ww .j ava2  s .  c  o  m*/
public void postProcess() throws MojoExecutionException {
    if (getPostProcess() != null) {
        executeTasks(getPostProcess(), getMavenProject());
    }

    // restore system properties
    if (originalSystemProperties != null) {
        System.setProperties(originalSystemProperties);
    }
}

From source file:net.sf.firemox.tools.MToolKit.java

/**
 * Create, and return the connection established with a http server. May use a
 * http proxy if the settings have been set
 * /*from   w ww.j  a v a 2s .  c o m*/
 * @param url
 *          the requested url.
 * @return Http connection.
 */
public static URLConnection getHttpConnection(URL url) {
    try {
        if (Configuration.getBoolean("useProxy", false)) {
            // we use the proxy configuration
            Properties systPrp = System.getProperties();
            systPrp.put("proxySet", "true");
            systPrp.put("http.proxyHost", Configuration.getString("proxyHost", "192.168.0.252"));
            systPrp.put("http.proxyPort", Configuration.getString("proxyPort", "1299"));
            System.setProperties(systPrp);

            HttpURLConnection uc = (HttpURLConnection) url.openConnection();
            BASE64Encoder encoder = new sun.misc.BASE64Encoder();
            String encodedUserPwd = encoder.encode(
                    Password.deobfuscate(Configuration.getString("proxyObfuscatedLoginPwd", "")).getBytes());
            if (encodedUserPwd.length() > 0) {
                uc.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
            }
            uc.connect();
            return uc;
        }
        return url.openConnection();
    } catch (IOException e) {
        return null;
    }
}

From source file:org.fusesource.cloudmix.agent.InstallerAgent.java

protected void installProperties(Feature feature, List<ConfigurationUpdate> featureCfgOverrides) {
    Properties applicationProperties = feature.getProperties("applicationProperties");
    Properties systemProperties = System.getProperties();
    boolean changed = false;

    // time to apply the application's configuration overrides
    if (featureCfgOverrides != null && featureCfgOverrides.size() > 0) {
        if (applicationProperties == null) {
            applicationProperties = new Properties();
        }/*from w  ww  . j  a  v  a 2 s . co  m*/
        for (ConfigurationUpdate cfgUpdate : featureCfgOverrides) {
            applicationProperties.put(cfgUpdate.getProperty(), cfgUpdate.getValue());
        }
    }

    if (applicationProperties != null) {
        systemProperties.putAll(applicationProperties);
        changed = true;
        LOG.info(" ===>> adding app props to system");
    }

    if (changed) {
        System.setProperties(systemProperties);
        LOG.info(" ===>> applying props updates");
    }

}