Java Code Examples for org.apache.commons.lang.SystemUtils#IS_OS_WINDOWS

The following examples show how to use org.apache.commons.lang.SystemUtils#IS_OS_WINDOWS . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AccumuloInstanceDriver.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Copies the HADOOP_HOME bin directory to the {@link MiniAccumuloCluster} temp directory.
 * {@link MiniAccumuloCluster} expects to find bin/winutils.exe in the MAC temp
 * directory instead of HADOOP_HOME for some reason.
 * @throws IOException
 */
private void copyHadoopHomeToTemp() throws IOException {
    if (IS_COPY_HADOOP_HOME_ENABLED && SystemUtils.IS_OS_WINDOWS) {
        final String hadoopHomeEnv = PathUtils.clean(System.getenv("HADOOP_HOME"));
        if (hadoopHomeEnv != null) {
            final File hadoopHomeDir = new File(hadoopHomeEnv);
            if (hadoopHomeDir.exists()) {
                final File binDir = Paths.get(hadoopHomeDir.getAbsolutePath(), "/bin").toFile();
                if (binDir.exists()) {
                    FileUtils.copyDirectoryToDirectory(binDir, tempDir);
                } else {
                    log.warn("The specified path for the Hadoop bin directory does not exist: " + binDir.getAbsolutePath());
                }
            } else {
                log.warn("The specified path for HADOOP_HOME does not exist: " + hadoopHomeDir.getAbsolutePath());
            }
        } else {
            log.warn("The HADOOP_HOME environment variable was not found.");
        }
    }
}
 
Example 2
Source File: AccumuloInstanceDriver.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Copies the HADOOP_HOME bin directory to the {@link MiniAccumuloCluster} temp directory.
 * {@link MiniAccumuloCluster} expects to find bin/winutils.exe in the MAC temp
 * directory instead of HADOOP_HOME for some reason.
 * @throws IOException
 */
private void copyHadoopHomeToTemp() throws IOException {
    if (IS_COPY_HADOOP_HOME_ENABLED && SystemUtils.IS_OS_WINDOWS) {
        final String hadoopHomeEnv = PathUtils.clean(System.getenv("HADOOP_HOME"));
        if (hadoopHomeEnv != null) {
            final File hadoopHomeDir = new File(hadoopHomeEnv);
            if (hadoopHomeDir.exists()) {
                final File binDir = Paths.get(hadoopHomeDir.getAbsolutePath(), "/bin").toFile();
                if (binDir.exists()) {
                    FileUtils.copyDirectoryToDirectory(binDir, tempDir);
                } else {
                    log.warn("The specified path for the Hadoop bin directory does not exist: " + binDir.getAbsolutePath());
                }
            } else {
                log.warn("The specified path for HADOOP_HOME does not exist: " + hadoopHomeDir.getAbsolutePath());
            }
        } else {
            log.warn("The HADOOP_HOME environment variable was not found.");
        }
    }
}
 
Example 3
Source File: CLIProcessManager.java    From IGUANA with GNU Affero General Public License v3.0 6 votes vote down vote up
public static Process createProcess(String command) {
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.redirectErrorStream(true);

    Process process = null;
    try {
        if (SystemUtils.IS_OS_LINUX) {

            processBuilder.command("bash", "-c", command);

        } else if (SystemUtils.IS_OS_WINDOWS) {
            processBuilder.command("cmd.exe", "-c", command);
        }
        process = processBuilder.start();

    } catch (IOException e) {
        System.out.println("New process could not be created: " + e.getLocalizedMessage());
    }

    return process;
}
 
Example 4
Source File: ITestUtils.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
/**
 * Run maven process with commands and params (-D arguments) in workingDir directory.
 *
 * @param commands - String representing maven command(s), e.g. "clean install".
 * @param params - Map of String keys and values representing -D arguments.
 * @param workingDir - Working directory.
 * @return Exit value
 * @throws Exception if an error occurs
 */
static Integer runMaven( String commands, Map<String, String> params, String workingDir )
    throws Exception
{
    String stringParams = toJavaParams( params );
    String commandMaven;

    if ( SystemUtils.IS_OS_WINDOWS )
    {
        commandMaven = String.format( "cmd.exe /X /C \"mvn %s %s\"", commands, stringParams );
    }
    else
    {
        commandMaven = String.format( "mvn %s %s", commands, stringParams );
    }

    logger.info( "Maven command: {} (cwd: {})", commandMaven, workingDir );

    return runCommandAndWait( commandMaven, workingDir, MVN_LOCATION + File.separator + "bin" );
}
 
Example 5
Source File: AtoumUtils.java    From phpstorm-plugin with MIT License 6 votes vote down vote up
public static String findAtoumBinPath(VirtualFile dir)
{
    String defaultBinPath = dir.getPath() + "/vendor/bin/atoum";
    String atoumBinPath = defaultBinPath;

    String binDir = getComposerBinDir(dir.getPath() + "/composer.json");
    String binPath = dir.getPath() + "/" + binDir + "/atoum";
    if (null != binDir && new File(binPath).exists()) {
        atoumBinPath = binPath;
    }

    if (SystemUtils.IS_OS_WINDOWS) {
        atoumBinPath += ".bat";
    }

    return atoumBinPath;
}
 
Example 6
Source File: DialectFactory.java    From MogwaiERDesignerNG with GNU General Public License v3.0 6 votes vote down vote up
public static synchronized DialectFactory getInstance() {
    if (me == null) {
        me = new DialectFactory();
        me.registerDialect(new DB2Dialect());
        me.registerDialect(new MSSQLDialect());
        me.registerDialect(new MySQLDialect());
        me.registerDialect(new MySQLInnoDBDialect());
        me.registerDialect(new OracleDialect());
        me.registerDialect(new PostgresDialect());
        me.registerDialect(new H2Dialect());
        me.registerDialect(new HSQLDBDialect());

        // provide MSAccessDialect only on Windows-Systems due to the
        // requirement of the JET/ACE-Engine
        if (SystemUtils.IS_OS_WINDOWS) {
            me.registerDialect(new MSAccessDialect());
        }
    }

    return me;
}
 
Example 7
Source File: ModelUtilsTest.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testToFile() throws Exception{
  if (SystemUtils.IS_OS_WINDOWS)
    assertEquals("P:\\Some text document.txt",new MMapURI("file://P:/Some%20text%20document.txt").asFile(null).getAbsolutePath());
  else
    assertEquals("/Some text document.txt",new MMapURI("file:///Some%20text%20document.txt").asFile(null).getAbsolutePath());
}
 
Example 8
Source File: FolderObserverTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testException() throws Exception {
    ModelRepoDummy modelRepo = new ModelRepoDummy() {
        @Override
        public boolean addOrRefreshModel(String name, InputStream inputStream) {
            super.addOrRefreshModel(name, inputStream);
            throw new RuntimeException("intentional failure.");
        }
    };
    folderObserver.setModelRepository(modelRepo);

    String validExtension = "java";
    configProps.put(EXISTING_SUBDIR_NAME, "txt,jpg," + validExtension);
    folderObserver.activate(context);

    File mockFileWithValidExt = new File(EXISTING_SUBDIR_PATH, "MockFileForModification." + validExtension);
    mockFileWithValidExt.createNewFile();
    if (!SystemUtils.IS_OS_WINDOWS) {
        FileUtils.writeStringToFile(mockFileWithValidExt, INITIAL_FILE_CONTENT);
    }

    waitForAssert(() -> assertThat(modelRepo.isAddOrRefreshModelMethodCalled, is(true)), DFL_TIMEOUT * 2,
            DFL_SLEEP_TIME);

    modelRepo.clean();
    FileUtils.writeStringToFile(mockFileWithValidExt, "Additional content", true);

    waitForAssert(() -> assertThat(modelRepo.isAddOrRefreshModelMethodCalled, is(true)), DFL_TIMEOUT * 2,
            DFL_SLEEP_TIME);
}
 
Example 9
Source File: MountableFile.java    From testcontainers-java with MIT License 5 votes vote down vote up
/**
 * Obtain a path in local filesystem that the Docker daemon should be able to use to volume mount a file/resource
 * into a container. If this is a classpath resource residing in a JAR, it will be extracted to
 * a temporary location so that the Docker daemon is able to access it.
 *
 * TODO: rename method accordingly and check if really needed like this
 *
 * @return
 */
private String resolveFilesystemPath() {
    String result = getResourcePath();

    if (SystemUtils.IS_OS_WINDOWS && result.startsWith("/")) {
        result = PathUtils.createMinGWPath(result).substring(1);
    }

    return result;
}
 
Example 10
Source File: MountableFile.java    From testcontainers-java with MIT License 5 votes vote down vote up
/**
 * Obtain a path that the Docker daemon should be able to use to volume mount a file/resource
 * into a container. If this is a classpath resource residing in a JAR, it will be extracted to
 * a temporary location so that the Docker daemon is able to access it.
 *
 * @return a volume-mountable path.
 */
private String resolvePath() {
    String result = getResourcePath();

    // Special case for Windows
    if (SystemUtils.IS_OS_WINDOWS && result.startsWith("/")) {
        // Remove leading /
        result = result.substring(1);
    }

    return result;
}
 
Example 11
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-21168")
private void checkSymlinkSetting(WorkingArea area) throws IOException {
    String expected = SystemUtils.IS_OS_WINDOWS ? "false" : "";
    String symlinkValue;
    try {
        symlinkValue = w.launchCommand(true, "git", "config", "core.symlinks").trim();
    } catch (Exception e) {
        symlinkValue = e.getMessage();
    }
    assertEquals(expected, symlinkValue);
}
 
Example 12
Source File: ConfigTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void honorClientAuthenticatorCommands() throws Exception {
  if (SystemUtils.IS_OS_WINDOWS) {
    System.setProperty(Config.KUBERNETES_KUBECONFIG_FILE, TEST_KUBECONFIG_EXEC_WIN_FILE);
  } else {
    Files.setPosixFilePermissions(Paths.get(TEST_TOKEN_GENERATOR_FILE), PosixFilePermissions.fromString("rwxrwxr-x"));
    System.setProperty(Config.KUBERNETES_KUBECONFIG_FILE, TEST_KUBECONFIG_EXEC_FILE);
  }

  Config config = Config.autoConfigure(null);
  assertNotNull(config);
  assertEquals("HELLO WORLD", config.getOauthToken());
}
 
Example 13
Source File: PathValidatorTest.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsValid() throws Exception {
    final String existingFile = new File(this.getClass().getResource("/i-exists.txt").getPath()).getAbsolutePath();

    Set<ConstraintViolation<PathsWrapper>> constraintViolations =
            validator.validate(new PathsWrapper("c:/test", "c:/test/jdk.zip", existingFile));
    assertTrue(constraintViolations.isEmpty());

    constraintViolations = validator.validate(new PathsWrapper("c:\\test", "c:/test/jdk.jar", existingFile));
    assertTrue(constraintViolations.isEmpty());

    constraintViolations = validator.validate(new PathsWrapper("c:\\test/any", "c:\\jdk.war", existingFile));
    assertTrue(constraintViolations.isEmpty());

    constraintViolations = validator.validate(new PathsWrapper("c:\\test/any", "c:\\jdk", existingFile));
    assertTrue(constraintViolations.size() == 1);
    assertEquals("invalid dirAndFilename", constraintViolations.iterator().next().getMessage());

    constraintViolations = validator.validate(new PathsWrapper("c:\\test/any", "c:\\jdk.peanuts", existingFile));
    assertEquals("invalid dirAndFilename", constraintViolations.iterator().next().getMessage());
    assertTrue(constraintViolations.size() == 1);

    if (SystemUtils.IS_OS_WINDOWS) {
        constraintViolations = validator.validate(new PathsWrapper("c::\\test/any", "c:\\jdk.zip", existingFile));
        assertEquals("invalid dir", constraintViolations.iterator().next().getMessage());
        assertTrue(constraintViolations.size() == 1);
    }

    constraintViolations = validator.validate(new PathsWrapper("/unix/path", "/jdk.zip", existingFile));
    assertTrue(constraintViolations.isEmpty());

    constraintViolations = validator.validate(new PathsWrapper("/unix/path", "/jdk.zip", "/this/should/not/point/to/an/existing/file"));
    assertTrue(constraintViolations.size() == 1);
    assertEquals("invalid existingPath", constraintViolations.iterator().next().getMessage());
}
 
Example 14
Source File: LanguageServerLauncher.java    From solidity-ide with Eclipse Public License 1.0 5 votes vote down vote up
private static CharSequence getOS() {
	if (SystemUtils.IS_OS_LINUX) {
		return "linux";
	} else if (SystemUtils.IS_OS_WINDOWS) {
		return "win32";
	} else if (SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_MAC_OSX) {
		return "macosx";
	} else {
		throw new IllegalArgumentException("Unsupported OS");
	}
}
 
Example 15
Source File: OpenAction.java    From AndroidGodEye with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
    try {
        Project project = anActionEvent.getProject();
        String path = parseAndroidSDKPath(Objects.requireNonNull(project));
        if (TextUtils.isEmpty(path)) {
            Notifications.Bus.notify(new Notification("AndroidGodEye", "Open AndroidGodEye Failed", "Can not parse sdk.dir, Please add 'sdk.dir' to 'local.properties'.", NotificationType.ERROR));
            return;
        }
        mLogger.info("Current os name is " + SystemUtils.OS_NAME);
        String adbPath = String.format("%s/platform-tools/adb", path);
        mLogger.info("ADB path is " + adbPath);
        String parsedPort = parsePortByLogcatWithTimeout(project, adbPath);
        mLogger.info("Parse AndroidGodEye port is running at " + parsedPort);
        String inputPort = askForPort(project, parsedPort, getSavedPort(project));
        if (inputPort == null) {
            mLogger.warn("inputPort == null");
            return;
        }
        saveDefaultPort(project, inputPort);
        final String commandTcpProxy = String.format("%s forward tcp:%s tcp:%s", adbPath, inputPort, inputPort);
        mLogger.info("Exec [" + commandTcpProxy + "].");
        Runtime.getRuntime().exec(commandTcpProxy);
        String commandOpenUrl;
        if (SystemUtils.IS_OS_WINDOWS) {
            commandOpenUrl = String.format("cmd /c start http://localhost:%s/index.html", inputPort);
        } else {
            commandOpenUrl = String.format("open http://localhost:%s/index.html", inputPort);
        }
        mLogger.info("Exec [" + commandOpenUrl + "].");
        Runtime.getRuntime().exec(commandOpenUrl);
        Notifications.Bus.notify(new Notification("AndroidGodEye", "Open AndroidGodEye Success", String.format("http://localhost:%s/index.html", inputPort), NotificationType.INFORMATION));
    } catch (Throwable e) {
        mLogger.warn(e);
        Notifications.Bus.notify(new Notification("AndroidGodEye", "Open AndroidGodEye Failed", String.valueOf(e), NotificationType.ERROR));
    }
}
 
Example 16
Source File: GitClientTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void test_git_ssh_executable_found_on_windows() {
    assumeThat(gitImplName, is("git"));
    cliGitAPIImplTest.setTimeoutVisibleInCurrentTest(false);
    if (!SystemUtils.IS_OS_WINDOWS) {
        return;
    }

    CliGitAPIImpl git = new CliGitAPIImpl("git", new File("."), cliGitAPIImplTest.listener, cliGitAPIImplTest.env);
    assertTrue("ssh.exe not found", git.getSSHExecutable().exists());
}
 
Example 17
Source File: VirtualFileSystemView.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private File[] getOSRoots() {
    File[] osRoots = this.defaultFileSystemView.getRoots();
    if (SystemUtils.IS_OS_WINDOWS) {
        try {
            Class<?> nativeOsFileClass = Class.forName("sun.awt.shell.ShellFolder");
            osRoots = (File[]) nativeOsFileClass.getMethod("get", String.class).invoke(null, "fileChooserComboBoxFolders");
        } catch (Exception ignored) {
            //leave default
        }
    }
    return osRoots;
}
 
Example 18
Source File: DockerComposeContainer.java    From testcontainers-java with MIT License 4 votes vote down vote up
private String getDockerSocketHostPath() {
    return SystemUtils.IS_OS_WINDOWS
        ? "/" + DOCKER_SOCKET_PATH
        : DOCKER_SOCKET_PATH;
}
 
Example 19
Source File: ComponentReasoningKB.java    From wings with Apache License 2.0 4 votes vote down vote up
public ComponentInvocation getComponentInvocation(ComponentPacket details) {
	HashMap<String, KBObject> omap = this.objPropMap;
	HashMap<String, KBObject> dmap = this.dataPropMap;

	// Extract info from details object
	ComponentVariable c = details.getComponent();
	Map<Variable, Role> varMap = details.getVariableMap();

	// Get Component
	KBObject comp = this.kb.getResource(c.getBinding().getID());
	String exepath = this.getComponentLocation(comp.getID());
	String exedir = null;
	if(exepath != null) {
		File f = new File(exepath);
		if(f.isDirectory()) {
		  exedir = exepath;
			File shexef = new File(exepath + File.separator + "run");
			File winexef = new File(exepath + File.separator + "run.bat");
			if(SystemUtils.IS_OS_WINDOWS && winexef.exists())
				exepath = winexef.getAbsolutePath();
			else
				exepath = shexef.getAbsolutePath();
		}
	}
	
	ComponentInvocation invocation = new ComponentInvocation();
	invocation.setComponentId(comp.getID());
	invocation.setComponentLocation(exepath);
	invocation.setComponentDirectory(exedir);

	this.start_read();
	boolean batchok = this.start_batch_operation();
	
	ArrayList<KBObject> inputs = this.kb.getPropertyValues(comp, omap.get("hasInput"));
	ArrayList<KBObject> outputs = this.kb.getPropertyValues(comp, omap.get("hasOutput"));
	ArrayList<KBObject> args = new ArrayList<KBObject>(inputs);
	args.addAll(outputs);
	
	for (KBObject arg : args) {
		KBObject argid = this.kb.getDatatypePropertyValue(arg, dmap.get("hasArgumentID"));
		String role = (String) argid.getValue();
		for(Variable var : varMap.keySet()) {
		  Role r = varMap.get(var);
			if(r.getRoleId().equals(role))
				setInvocationArguments(invocation, arg, var, inputs.contains(arg));
		}
	}
	
	if(batchok)
	  this.stop_batch_operation();
	this.end();
	
	return invocation;
}
 
Example 20
Source File: NativeHelper.java    From systemds with Apache License 2.0 4 votes vote down vote up
private static void performLoading(String customLibPath, String userSpecifiedBLAS) {
	if((customLibPath != null) && customLibPath.equalsIgnoreCase("none"))
			customLibPath = null;

	// attemptedLoading variable ensures that we don't try to load SystemDS and other dependencies
	// again and again especially in the parfor (hence the double-checking with synchronized).
	if(shouldReload(customLibPath) && isSupportedBLAS(userSpecifiedBLAS) && isSupportedArchitecture()) {
		long start = System.nanoTime();
		synchronized(NativeHelper.class) {
			if(shouldReload(customLibPath)) {
				// Set attempted loading unsuccessful in case of exception
				CURRENT_NATIVE_BLAS_STATE = NativeBlasState.ATTEMPTED_LOADING_NATIVE_BLAS_UNSUCCESSFULLY;
				String [] blas = new String[] { userSpecifiedBLAS }; 
				if(userSpecifiedBLAS.equalsIgnoreCase("auto")) {
					blas = new String[] { "mkl", "openblas" };
				}

				if(SystemUtils.IS_OS_WINDOWS) {
					if (checkAndLoadBLAS(customLibPath, blas) &&
							(loadLibraryHelper("systemds_" + blasType + "-Windows-AMD64") ||
							loadBLAS(customLibPath, "systemds_" + blasType + "-Windows-AMD64", null))
					)
					{
						LOG.info("Using native blas: " + blasType + getNativeBLASPath());
						CURRENT_NATIVE_BLAS_STATE = NativeBlasState.SUCCESSFULLY_LOADED_NATIVE_BLAS_AND_IN_USE;
					}
				}
				else {
					if (checkAndLoadBLAS(customLibPath, blas) &&
							loadLibraryHelper("libsystemds_" + blasType + "-Linux-x86_64.so")) {
						LOG.info("Using native blas: " + blasType + getNativeBLASPath());
						CURRENT_NATIVE_BLAS_STATE = NativeBlasState.SUCCESSFULLY_LOADED_NATIVE_BLAS_AND_IN_USE;
					}
				}
			}
		}
		double timeToLoadInMilliseconds = (System.nanoTime()-start)*1e-6;
		if(timeToLoadInMilliseconds > 1000) 
			LOG.warn("Time to load native blas: " + timeToLoadInMilliseconds + " milliseconds.");
	}
	else if(LOG.isDebugEnabled() && !isSupportedBLAS(userSpecifiedBLAS)) {
		LOG.debug("Using internal Java BLAS as native BLAS support the configuration 'sysds.native.blas'=" +
				userSpecifiedBLAS + ".");
	}
}