Example usage for org.apache.commons.lang SystemUtils IS_OS_WINDOWS

List of usage examples for org.apache.commons.lang SystemUtils IS_OS_WINDOWS

Introduction

In this page you can find the example usage for org.apache.commons.lang SystemUtils IS_OS_WINDOWS.

Prototype

boolean IS_OS_WINDOWS

To view the source code for org.apache.commons.lang SystemUtils IS_OS_WINDOWS.

Click Source Link

Document

Is true if this is Windows.

The field will return false if OS_NAME is null.

Usage

From source file:org.alfresco.utilities.LdtpUtils.java

/**
 * Check if process identified by <processName> is currently running
 * /*from   w  w w  .  j a  v  a  2 s  . c o m*/
 * @param processName
 * @return
 */
public static boolean isProcessRunning(String processName) {
    processName = processName.toLowerCase();
    Process p = null;
    try {
        if (SystemUtils.IS_OS_MAC) {
            p = Runtime.getRuntime().exec("ps -ef");
        } else if (SystemUtils.IS_OS_WINDOWS) {
            p = Runtime.getRuntime().exec(new String[] { "cmd", "/c", "tasklist" });
        }
        InputStream inputStream = p.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferReader = new BufferedReader(inputStreamReader);
        String line;
        while ((line = bufferReader.readLine()) != null) {
            if (line.toLowerCase().contains(processName))
                return true;
        }
        inputStream.close();
        inputStreamReader.close();
        bufferReader.close();
    } catch (Exception err) {
        err.printStackTrace();
    }
    return false;
}

From source file:org.apache.airavata.core.gfac.services.impl.LocalProviderTest.java

@BeforeTest
public void setUp() throws Exception {

    URL resource = this.getClass().getClassLoader()
            .getResource(org.apache.airavata.common.utils.Constants.GFAC_CONFIG_XML);
    File configFile = new File(resource.getPath());
    GFacConfiguration gFacConfiguration = GFacConfiguration.create(configFile, null, null);
    //have to set InFlwo Handlers and outFlowHandlers
    ApplicationContext applicationContext = new ApplicationContext();
    HostDescription host = new HostDescription();
    host.getType().setHostName("localhost");
    host.getType().setHostAddress("localhost");
    applicationContext.setHostDescription(host);
    /*//w ww . j av  a2 s  .c  o  m
       * App
       */
    ApplicationDescription appDesc = new ApplicationDescription();
    ApplicationDeploymentDescriptionType app = appDesc.getType();
    ApplicationDeploymentDescriptionType.ApplicationName name = ApplicationDeploymentDescriptionType.ApplicationName.Factory
            .newInstance();
    name.setStringValue("EchoLocal");
    app.setApplicationName(name);

    /*
       * Use bat file if it is compiled on Windows
       */
    if (SystemUtils.IS_OS_WINDOWS) {
        URL url = this.getClass().getClassLoader().getResource("echo.bat");
        app.setExecutableLocation(url.getFile());
    } else {
        //for unix and Mac
        app.setExecutableLocation("/bin/echo");
    }

    /*
       * Default tmp location
       */
    String tempDir = System.getProperty("java.io.tmpdir");
    if (tempDir == null) {
        tempDir = "/tmp";
    }

    app.setScratchWorkingDirectory(tempDir);
    app.setStaticWorkingDirectory(tempDir);
    app.setInputDataDirectory(tempDir + File.separator + "input");
    app.setOutputDataDirectory(tempDir + File.separator + "output");
    app.setStandardOutput(tempDir + File.separator + "echo.stdout");
    app.setStandardError(tempDir + File.separator + "echo.stderr");

    applicationContext.setApplicationDeploymentDescription(appDesc);

    /*
       * Service
       */
    ServiceDescription serv = new ServiceDescription();
    serv.getType().setName("SimpleEcho");

    List<InputParameterType> inputList = new ArrayList<InputParameterType>();
    InputParameterType input = InputParameterType.Factory.newInstance();
    input.setParameterName("echo_input");
    input.setParameterType(StringParameterType.Factory.newInstance());
    inputList.add(input);
    InputParameterType[] inputParamList = inputList.toArray(new InputParameterType[inputList.size()]);

    List<OutputParameterType> outputList = new ArrayList<OutputParameterType>();
    OutputParameterType output = OutputParameterType.Factory.newInstance();
    output.setParameterName("echo_output");
    output.setParameterType(StringParameterType.Factory.newInstance());
    outputList.add(output);
    OutputParameterType[] outputParamList = outputList.toArray(new OutputParameterType[outputList.size()]);

    serv.getType().setInputParametersArray(inputParamList);
    serv.getType().setOutputParametersArray(outputParamList);

    jobExecutionContext = new JobExecutionContext(gFacConfiguration, serv.getType().getName());
    jobExecutionContext.setApplicationContext(applicationContext);
    /*
    * Host
    */
    applicationContext.setServiceDescription(serv);

    MessageContext inMessage = new MessageContext();
    ActualParameter echo_input = new ActualParameter();
    ((StringParameterType) echo_input.getType()).setValue("echo_output=hello");
    inMessage.addParameter("echo_input", echo_input);

    jobExecutionContext.setInMessageContext(inMessage);

    MessageContext outMessage = new MessageContext();
    ActualParameter echo_out = new ActualParameter();
    outMessage.addParameter("echo_output", echo_out);

    jobExecutionContext.setOutMessageContext(outMessage);

    jobExecutionContext.setExperimentID("test123");
    jobExecutionContext.setExperiment(new Experiment("test123", "project1", "admin", "testExp"));
    jobExecutionContext.setTaskData(new TaskDetails(jobExecutionContext.getExperimentID()));
    jobExecutionContext.setRegistry(new LoggingRegistryImpl());
    jobExecutionContext.setWorkflowNodeDetails(
            new WorkflowNodeDetails(jobExecutionContext.getExperimentID(), "none", ExecutionUnit.APPLICATION));

}

From source file:org.apache.airavata.core.gfac.services.impl.PropertiesBasedServiceImplTest.java

@Before
public void setUp() throws Exception {
    /*//from ww w  .j  a v  a2 s .  c  o m
     * Create database
     */
    Map<String, String> config = new HashMap<String, String>();
    config.put("org.apache.jackrabbit.repository.home", "target");
    AiravataJCRRegistry jcrRegistry = new AiravataJCRRegistry(null,
            "org.apache.jackrabbit.core.RepositoryFactoryImpl", "admin", "admin", config);

    /*
     * Host
     */
    HostDescription host = new HostDescription();
    host.getType().setHostName("localhost");
    host.getType().setHostAddress("localhost");

    /*
     * App
     */
    ApplicationDeploymentDescription appDesc = new ApplicationDeploymentDescription();
    ApplicationDeploymentDescriptionType app = appDesc.getType();
    ApplicationName name = ApplicationName.Factory.newInstance();
    name.setStringValue("EchoLocal");
    app.setApplicationName(name);

    /*
     * Use bat file if it is compiled on Windows
     */
    if (SystemUtils.IS_OS_WINDOWS) {
        URL url = this.getClass().getClassLoader().getResource("echo.bat");
        app.setExecutableLocation(url.getFile());
    } else {
        //for unix and Mac
        app.setExecutableLocation("/bin/echo");
    }

    /*
     * Default tmp location
     */
    String tempDir = System.getProperty("java.io.tmpdir");
    if (tempDir == null) {
        tempDir = "/tmp";
    }

    app.setScratchWorkingDirectory(tempDir);
    app.setStaticWorkingDirectory(tempDir);
    app.setInputDataDirectory(tempDir + File.separator + "input");
    app.setOutputDataDirectory(tempDir + File.separator + "output");
    app.setStandardOutput(tempDir + File.separator + "echo.stdout");
    app.setStandardError(tempDir + File.separator + "echo.stdout");

    /*
     * Service
     */
    ServiceDescription serv = new ServiceDescription();
    serv.getType().setName("SimpleEcho");

    List<InputParameterType> inputList = new ArrayList<InputParameterType>();
    InputParameterType input = InputParameterType.Factory.newInstance();
    input.setParameterName("echo_input");
    input.setParameterType(StringParameterType.Factory.newInstance());
    inputList.add(input);
    InputParameterType[] inputParamList = inputList.toArray(new InputParameterType[inputList.size()]);

    List<OutputParameterType> outputList = new ArrayList<OutputParameterType>();
    OutputParameterType output = OutputParameterType.Factory.newInstance();
    output.setParameterName("echo_output");
    output.setParameterType(StringParameterType.Factory.newInstance());
    outputList.add(output);
    OutputParameterType[] outputParamList = outputList.toArray(new OutputParameterType[outputList.size()]);

    serv.getType().setInputParametersArray(inputParamList);
    serv.getType().setOutputParametersArray(outputParamList);

    /*
     * Save to registry
     */
    jcrRegistry.saveHostDescription(host);
    jcrRegistry.saveDeploymentDescription(serv.getType().getName(), host.getType().getHostName(), appDesc);
    jcrRegistry.saveServiceDescription(serv);
    jcrRegistry.deployServiceOnHost(serv.getType().getName(), host.getType().getHostName());
}

From source file:org.apache.airavata.core.gfac.services.impl.SSHProviderTestWithSSHAuth.java

@Before
public void setUp() throws Exception {

    URL resource = SSHProviderTestWithSSHAuth.class.getClassLoader()
            .getResource(org.apache.airavata.common.utils.Constants.GFAC_CONFIG_XML);
    GFacConfiguration gFacConfiguration = GFacConfiguration.create(new File(resource.getPath()), null, null);
    //        gFacConfiguration.s
    //have to set InFlwo Handlers and outFlowHandlers
    ApplicationContext applicationContext = new ApplicationContext();
    HostDescription host = new HostDescription(SSHHostType.type);
    host.getType().setHostName("bigred");
    host.getType().setHostAddress("bigred2.uits.iu.edu");
    applicationContext.setHostDescription(host);
    /*/*from w w w  . ja v a 2  s.co  m*/
       * App
       */
    ApplicationDescription appDesc = new ApplicationDescription();
    ApplicationDeploymentDescriptionType app = appDesc.getType();
    ApplicationDeploymentDescriptionType.ApplicationName name = ApplicationDeploymentDescriptionType.ApplicationName.Factory
            .newInstance();
    name.setStringValue("EchoSSH");
    app.setApplicationName(name);

    /*
       * Use bat file if it is compiled on Windows
       */
    if (SystemUtils.IS_OS_WINDOWS) {
        URL url = this.getClass().getClassLoader().getResource("echo.bat");
        app.setExecutableLocation(url.getFile());
    } else {
        //for unix and Mac
        app.setExecutableLocation("/bin/echo");
    }

    /*
     * Job location
    */
    String tempDir = "/tmp";
    String date = (new Date()).toString();
    date = date.replaceAll(" ", "_");
    date = date.replaceAll(":", "_");

    tempDir = tempDir + File.separator + "EchoSSH" + "_" + date + "_" + UUID.randomUUID();

    app.setScratchWorkingDirectory(tempDir);
    app.setStaticWorkingDirectory(tempDir);
    app.setInputDataDirectory(tempDir + File.separator + "input");
    app.setOutputDataDirectory(tempDir + File.separator + "output");
    app.setStandardOutput(tempDir + File.separator + "echo.stdout");
    app.setStandardError(tempDir + File.separator + "echo.stderr");

    applicationContext.setApplicationDeploymentDescription(appDesc);

    /*
       * Service
       */
    ServiceDescription serv = new ServiceDescription();
    serv.getType().setName("EchoSSH");

    List<InputParameterType> inputList = new ArrayList<InputParameterType>();
    InputParameterType input = InputParameterType.Factory.newInstance();
    input.setParameterName("echo_input");
    input.setParameterType(StringParameterType.Factory.newInstance());
    inputList.add(input);
    InputParameterType[] inputParamList = inputList.toArray(new InputParameterType[inputList.size()]);

    List<OutputParameterType> outputList = new ArrayList<OutputParameterType>();
    OutputParameterType output = OutputParameterType.Factory.newInstance();
    output.setParameterName("echo_output");
    output.setParameterType(StringParameterType.Factory.newInstance());
    outputList.add(output);
    OutputParameterType[] outputParamList = outputList.toArray(new OutputParameterType[outputList.size()]);

    serv.getType().setInputParametersArray(inputParamList);
    serv.getType().setOutputParametersArray(outputParamList);

    jobExecutionContext = new JobExecutionContext(gFacConfiguration, serv.getType().getName());
    jobExecutionContext.setApplicationContext(applicationContext);

    // Add security context
    jobExecutionContext.addSecurityContext(SSHSecurityContext.SSH_SECURITY_CONTEXT, getSecurityContext());
    /*
    * Host
    */
    applicationContext.setServiceDescription(serv);

    MessageContext inMessage = new MessageContext();
    ActualParameter echo_input = new ActualParameter();
    ((StringParameterType) echo_input.getType()).setValue("echo_output=hello");
    inMessage.addParameter("echo_input", echo_input);

    jobExecutionContext.setInMessageContext(inMessage);

    MessageContext outMessage = new MessageContext();
    ActualParameter echo_out = new ActualParameter();
    //      ((StringParameterType)echo_input.getType()).setValue("echo_output=hello");
    outMessage.addParameter("echo_output", echo_out);

    jobExecutionContext.setOutMessageContext(outMessage);

}

From source file:org.apache.ambari.server.notifications.dispatchers.AlertScriptDispatcher.java

/**
 * Gets a {@link ProcessBuilder} initialized with a script command to run with
 * the parameters from the notification.
 *
 * @param script//  w ww. java2 s  .  co m
 *          the absolute path to the script (not {@code null}).
 * @param notification
 *          the notification to parameterie (not {@code null}).
 * @return
 */
ProcessBuilder getProcessBuilder(String script, AlertNotification notification) {
    final String shellCommand;
    final String shellCommandOption;
    if (SystemUtils.IS_OS_WINDOWS) {
        shellCommand = "cmd";
        shellCommandOption = "/c";
    } else {
        shellCommand = "sh";
        shellCommandOption = "-c";
    }

    AlertInfo alertInfo = notification.getAlertInfo();
    AlertDefinitionEntity definition = alertInfo.getAlertDefinition();
    String definitionName = definition.getDefinitionName();
    AlertState alertState = alertInfo.getAlertState();
    String serviceName = alertInfo.getServiceName();

    // these could have spaces in them, so quote them so they don't mess up the
    // command line
    String alertLabel = "\"" + SHELL_ESCAPE.escape(definition.getLabel()) + "\"";
    String alertText = "\"" + SHELL_ESCAPE.escape(alertInfo.getAlertText()) + "\"";

    Object[] params = new Object[] { script, definitionName, alertLabel, serviceName, alertState.name(),
            alertText };

    String foo = StringUtils.join(params, " ");

    // sh -c '/foo/sys_logger.py ambari_server_agent_heartbeat "Agent Heartbeat"
    // AMBARI CRITICAL "Something went wrong with the host"'
    return new ProcessBuilder(shellCommand, shellCommandOption, foo);
}

From source file:org.apache.archiva.proxy.DefaultRepositoryProxyConnectors.java

@Override
public File fetchFromProxies(ManagedRepositoryContent repository, ArtifactReference artifact)
        throws ProxyDownloadException {
    File localFile = toLocalFile(repository, artifact);

    Properties requestProperties = new Properties();
    requestProperties.setProperty("filetype", "artifact");
    requestProperties.setProperty("version", artifact.getVersion());
    requestProperties.setProperty("managedRepositoryId", repository.getId());

    List<ProxyConnector> connectors = getProxyConnectors(repository);
    Map<String, Exception> previousExceptions = new LinkedHashMap<>();
    for (ProxyConnector connector : connectors) {
        if (connector.isDisabled()) {
            continue;
        }/*from  w w  w  .  j  a  v a 2  s. com*/

        RemoteRepositoryContent targetRepository = connector.getTargetRepository();
        requestProperties.setProperty("remoteRepositoryId", targetRepository.getId());

        String targetPath = targetRepository.toPath(artifact);

        if (SystemUtils.IS_OS_WINDOWS) {
            // toPath use system PATH_SEPARATOR so on windows url are \ which doesn't work very well :-)
            targetPath = FilenameUtils.separatorsToUnix(targetPath);
        }

        try {
            File downloadedFile = transferFile(connector, targetRepository, targetPath, repository, localFile,
                    requestProperties, true);

            if (fileExists(downloadedFile)) {
                log.debug("Successfully transferred: {}", downloadedFile.getAbsolutePath());
                return downloadedFile;
            }
        } catch (NotFoundException e) {
            log.debug("Artifact {} not found on repository \"{}\".", Keys.toKey(artifact),
                    targetRepository.getRepository().getId());
        } catch (NotModifiedException e) {
            log.debug("Artifact {} not updated on repository \"{}\".", Keys.toKey(artifact),
                    targetRepository.getRepository().getId());
        } catch (ProxyException | RepositoryAdminException e) {
            validatePolicies(this.downloadErrorPolicies, connector.getPolicies(), requestProperties, artifact,
                    targetRepository, localFile, e, previousExceptions);
        }
    }

    if (!previousExceptions.isEmpty()) {
        throw new ProxyDownloadException("Failures occurred downloading from some remote repositories",
                previousExceptions);
    }

    log.debug("Exhausted all target repositories, artifact {} not found.", Keys.toKey(artifact));

    return null;
}

From source file:org.apache.archiva.repository.scanner.RepositoryContentConsumersTest.java

/**
 * Create an OS specific version of the filepath.
 * Provide path in unix "/" format.//from  w w w  . j  a v  a 2 s  .  co  m
 */
private String _OS(String path) {
    if (SystemUtils.IS_OS_WINDOWS) {
        return path.replace('/', '\\');
    }
    return path;
}

From source file:org.apache.archiva.repository.scanner.RepositoryScannerInstance.java

public RepositoryScannerInstance(ManagedRepository repository,
        List<KnownRepositoryContentConsumer> knownConsumerList,
        List<InvalidRepositoryContentConsumer> invalidConsumerList) {
    this.repository = repository;
    this.knownConsumers = knownConsumerList;
    this.invalidConsumers = invalidConsumerList;

    consumerTimings = new HashMap<>();
    consumerCounts = new HashMap<>();

    this.consumerProcessFile = new ConsumerProcessFileClosure();
    consumerProcessFile.setExecuteOnEntireRepo(true);
    consumerProcessFile.setConsumerTimings(consumerTimings);
    consumerProcessFile.setConsumerCounts(consumerCounts);

    this.consumerWantsFile = new ConsumerWantsFilePredicate(repository);

    stats = new RepositoryScanStatistics();
    stats.setRepositoryId(repository.getId());

    Closure triggerBeginScan = new TriggerBeginScanClosure(repository, new Date(System.currentTimeMillis()),
            true);//from  ww  w. j a  v  a 2 s . c  o  m

    CollectionUtils.forAllDo(knownConsumerList, triggerBeginScan);
    CollectionUtils.forAllDo(invalidConsumerList, triggerBeginScan);

    if (SystemUtils.IS_OS_WINDOWS) {
        consumerWantsFile.setCaseSensitive(false);
    }
}

From source file:org.apache.asterix.test.runtime.LangExecutionUtil.java

private static void checkOpenRunFileLeaks() throws IOException {
    if (SystemUtils.IS_OS_WINDOWS) {
        return;/*w  w w .jav  a2  s  .co  m*/
    }
    // Only run the check on Linux and MacOS.
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    String processName = runtimeMXBean.getName();
    String processId = processName.split("@")[0];

    // Checks whether there are leaked run files from operators.
    Process process = Runtime.getRuntime()
            .exec(new String[] { "bash", "-c", "lsof -p " + processId + "|grep waf|wc -l" });
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        int runFileCount = Integer.parseInt(reader.readLine().trim());
        if (runFileCount != 0) {
            System.out.print(takeDumpJSON(ManagementFactory.getThreadMXBean()));
            outputLeakedOpenFiles(processId);
            throw new AssertionError("There are " + runFileCount + " leaked run files.");
        }
    }
}

From source file:org.apache.cxf.maven_plugin.AbstractCodegenMoho.java

private File getJavaExecutable() throws IOException {
    if (javaExecutable != null) {
        getLog().debug("Plugin configuration set the 'javaExecutable' parameter to " + javaExecutable);
    } else {/*from  w ww  .  j a  v a2s  .  c o  m*/
        Toolchain tc = toolchainManager.getToolchainFromBuildContext("jdk", mavenSession);
        if (tc != null) {
            getLog().info("Using toolchain " + tc + " to find the java executable");
            javaExecutable = tc.findTool("java");
        } else {
            getLog().debug("The java executable is set to default value");
            javaExecutable = SystemUtils.getJavaHome() + File.separator + "bin" + File.separator + "java";
        }
    }
    String exe = SystemUtils.IS_OS_WINDOWS && !javaExecutable.endsWith(".exe") ? ".exe" : "";
    File javaExe = new File(javaExecutable + exe);
    if (!javaExe.isFile()) {
        throw new IOException("The java executable '" + javaExe + "' doesn't exist or is not a file."
                + "Verify the <javaExecutable/> parameter or toolchain configuration.");
    }
    getLog().info("The java executable is " + javaExe.getAbsolutePath());
    return javaExe;
}