org.apache.commons.exec.OS Java Examples

The following examples show how to use org.apache.commons.exec.OS. 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: JavaFXRunMojoTestCase.java    From javafx-maven-plugin with Apache License 2.0 6 votes vote down vote up
private String getCommandLineAsString(CommandLine commandline) {
    // for the sake of the test comparisons, cut out the eventual
    // cmd /c *.bat conversion
    String result = commandline.getExecutable();
    boolean isCmd = false;
    if (OS.isFamilyWindows() && result.equals("cmd")) {
        result = "";
        isCmd = true;
    }
    String[] arguments = commandline.getArguments();
    for (int i = 0; i < arguments.length; i++) {
        String arg = arguments[i];
        if (isCmd && i == 0 && "/c".equals(arg)) {
            continue;
        }
        if (isCmd && i == 1 && arg.endsWith(".bat")) {
            arg = arg.substring(0, arg.length() - ".bat".length());
        }
        result += (result.length() == 0 ? "" : " ") + arg;
    }
    return result;
}
 
Example #2
Source File: JavaProfileTest.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
public void executeWSCommand() throws Throwable {
    if (OS.isFamilyWindows()) {
        throw new SkipException("Test not valid for Windows");
    }
    JavaProfile profile = new JavaProfile(LaunchMode.JAVA_WEBSTART).addWSArgument("-verbose").addVMArgument("-Dx.y.z=hello");
    final CommandLine commandLine = profile.getCommandLine();
    AssertJUnit.assertNotNull(commandLine);
    AssertJUnit.assertTrue(commandLine.toString().contains("-javaagent:"));
    AssertJUnit.assertTrue(commandLine.toString().contains("-verbose"));
    AssertJUnit.assertTrue(commandLine.toString().contains("-Dx.y.z=hello"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    commandLine.copyOutputTo(baos);
    commandLine.executeAsync();
    new Wait("Waiting till the command is complete") {
        @Override
        public boolean until() {
            return !commandLine.isRunning();
        }
    };
    BufferedReader reader = new BufferedReader(new StringReader(new String(baos.toByteArray())));
    String line = reader.readLine();
    while (line != null && !line.contains("Web Start")) {
        line = reader.readLine();
    }
    AssertJUnit.assertTrue(line.contains("Web Start"));
}
 
Example #3
Source File: SolrPaths.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that the given path is relative to one of the allowPaths supplied. Typically this will be
 * called from {@link CoreContainer#assertPathAllowed(Path)} and allowPaths pre-filled with the node's
 * SOLR_HOME, SOLR_DATA_HOME and coreRootDirectory folders, as well as any paths specified in
 * solr.xml's allowPaths element. The following paths will always fail validation:
 * <ul>
 *   <li>Relative paths starting with <code>..</code></li>
 *   <li>Windows UNC paths (such as <code>\\host\share\path</code>)</li>
 *   <li>Paths which are not relative to any of allowPaths</li>
 * </ul>
 * @param pathToAssert path to check
 * @param allowPaths list of paths that should be allowed prefixes for pathToAssert
 * @throws SolrException if path is outside allowed paths
 */
public static void assertPathAllowed(Path pathToAssert, Set<Path> allowPaths) throws SolrException {
  if (pathToAssert == null) return;
  if (OS.isFamilyWindows() && pathToAssert.toString().startsWith("\\\\")) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
        "Path " + pathToAssert + " disallowed. UNC paths not supported. Please use drive letter instead.");
  }
  // Conversion Path -> String -> Path is to be able to compare against org.apache.lucene.mockfile.FilterPath instances
  final Path path = Path.of(pathToAssert.toString()).normalize();
  if (path.startsWith("..")) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
        "Path " + pathToAssert + " disallowed due to path traversal..");
  }
  if (!path.isAbsolute()) return; // All relative paths are accepted
  if (allowPaths.contains(Paths.get("_ALL_"))) return; // Catch-all path "*"/"_ALL_" will allow all other paths
  if (allowPaths.stream().noneMatch(p -> path.startsWith(Path.of(p.toString())))) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
        "Path " + path + " must be relative to SOLR_HOME, SOLR_DATA_HOME coreRootDirectory. Set system property 'solr.allowPaths' to add other allowed paths.");
  }
}
 
Example #4
Source File: TestCoreContainer.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void assertAllowPathFromSolrXml() throws Exception {
  Assume.assumeFalse(OS.isFamilyWindows());
  System.setProperty("solr.allowPaths", "/var/solr");
  CoreContainer cc = init(ALLOW_PATHS_SOLR_XML);
  cc.assertPathAllowed(Paths.get("/var/solr/foo"));
  try {
    cc.assertPathAllowed(Paths.get("/tmp"));
    fail("Path /tmp should not be allowed");
  } catch(SolrException e) {
    /* Ignore */
  } finally {
    cc.shutdown();
    System.clearProperty("solr.allowPaths");
  }
}
 
Example #5
Source File: TestCoreContainer.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void assertAllowPathFromSolrXmlWin() throws Exception {
  Assume.assumeTrue(OS.isFamilyWindows());
  System.setProperty("solr.allowPaths", "C:\\solr");
  CoreContainer cc = init(ALLOW_PATHS_SOLR_XML);
  cc.assertPathAllowed(Paths.get("C:\\solr\\foo"));
  try {
    cc.assertPathAllowed(Paths.get("C:\\tmp"));
    fail("Path C:\\tmp should not be allowed");
  } catch(SolrException e) {
    /* Ignore */
  } finally {
    cc.shutdown();
    System.clearProperty("solr.allowPaths");
  }
}
 
Example #6
Source File: ExecMojoTest.java    From exec-maven-plugin with Apache License 2.0 5 votes vote down vote up
private String getCommandLineAsString( CommandLine commandline )
{
    // for the sake of the test comparisons, cut out the eventual
    // cmd /c *.bat conversion
    String result = commandline.getExecutable();
    boolean isCmd = false;
    if ( OS.isFamilyWindows() && result.equals( "cmd" ) )
    {
        result = "";
        isCmd = true;
    }
    String[] arguments = commandline.getArguments();
    for ( int i = 0; i < arguments.length; i++ )
    {
        String arg = arguments[i];
        if ( isCmd && i == 0 && "/c".equals( arg ) )
        {
            continue;
        }
        if ( isCmd && i == 1 && arg.endsWith( ".bat" ) )
        {
            arg = arg.substring( 0, arg.length() - ".bat".length() );
        }
        result += ( result.length() == 0 ? "" : " " ) + arg;
    }
    return result;
}
 
Example #7
Source File: ExecMojoTest.java    From exec-maven-plugin with Apache License 2.0 5 votes vote down vote up
public void testGetExecutablePathPreferExecutableExtensionsOnWindows()
		throws IOException
{
	// this test is for Windows
	if (!OS.isFamilyWindows()) {
		return;
	}
	final ExecMojo realMojo = new ExecMojo();
	
	final String tmp = System.getProperty("java.io.tmpdir");
	final File workdir = new File(tmp, "testGetExecutablePathPreferExecutableExtensionsOnWindows");
	workdir.mkdirs();
	
	final Map<String, String> enviro = new HashMap<String, String>();
	
	final File f = new File(workdir, "mycmd");
	final File fCmd = new File(workdir, "mycmd.cmd");
	f.createNewFile();
	fCmd.createNewFile();
	assertTrue( "file exists...", f.exists() );
	assertTrue( "file exists...", fCmd.exists() );
	
	realMojo.setExecutable( "mycmd" );
	
	final CommandLine cmd = realMojo.getExecutablePath( enviro, workdir );
	// cmdline argumets are: [/c, %path-to-temp%\mycmd.cmd], so check second argument
	assertTrue( "File should have cmd extension",
			cmd.getArguments()[1].endsWith( "mycmd.cmd" ) );
	
	f.delete();
	fCmd.delete();
	assertFalse( "file deleted...", f.exists() );
	assertFalse( "file deleted...", fCmd.exists() );
	
}
 
Example #8
Source File: TestCoreContainer.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void assertPathBlocked(String path) {
  try {

    SolrPaths.assertPathAllowed(Path.of(path), OS.isFamilyWindows() ? ALLOWED_PATHS_WIN : ALLOWED_PATHS);
    fail("Path " + path + " sould have been blocked.");
  } catch (SolrException e) { /* Expected */ }
}
 
Example #9
Source File: TestCoreContainer.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void assertAllowPathWindows() {
  Assume.assumeTrue(OS.isFamilyWindows());
  assertPathAllowed("C:\\var\\solr\\foo");
  assertPathAllowed("C:\\var\\log\\..\\solr\\foo");
  assertPathAllowed("relative");

  assertPathBlocked("..\\..\\false");
  assertPathBlocked(".\\../\\..\\false");
  assertPathBlocked("C:\\var\\solr\\..\\..\\etc");

  // UNC paths are always blocked
  assertPathBlocked("\\\\unc-server\\share\\path");
}
 
Example #10
Source File: TestCoreContainer.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void assertAllowPath() {
  Assume.assumeFalse(OS.isFamilyWindows());
  assertPathAllowed("/var/solr/foo");
  assertPathAllowed("/var/log/../solr/foo");
  assertPathAllowed("relative");

  assertPathBlocked("../../false");
  assertPathBlocked("./../../false");
  assertPathBlocked("/var/solr/../../etc");
}
 
Example #11
Source File: LaunchAppletTest.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
public void checkGivenExecutableIsUsed() throws Throwable {
    JavaProfile profile = new JavaProfile(LaunchMode.JAVA_APPLET);
    File f = findFile();
    profile.setAppletURL(f.getAbsolutePath());
    profile.setStartWindowTitle("Applet Viewer: SwingSet3Init.class");
    String actual = "";
    if (OS.isFamilyWindows()) {
        String path = System.getenv("Path");
        String[] split = path.split(";");
        File file = new File(split[0]);
        File[] listFiles = file.listFiles();
        if (listFiles != null) {
            for (File listFile : listFiles) {
                if (listFile.getName().contains(".exe")) {
                    profile.setJavaCommand(listFile.getAbsolutePath());
                    actual = listFile.getAbsolutePath();
                    break;
                }
            }
        }
    } else {
        actual = "ls";
        profile.setJavaCommand(actual);
    }
    CommandLine commandLine = profile.getCommandLine();
    AssertJUnit.assertTrue(commandLine.toString().contains(actual));
}
 
Example #12
Source File: SolrCLI.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
protected Map<String,Object> startSolr(File solrHomeDir,
                                       boolean cloudMode,
                                       CommandLine cli,
                                       int port,
                                       String zkHost,
                                       int maxWaitSecs)
    throws Exception
{

  String extraArgs = readExtraArgs(cli.getArgs());

  String host = cli.getOptionValue('h');
  String memory = cli.getOptionValue('m');

  String hostArg = (host != null && !"localhost".equals(host)) ? " -h "+host : "";
  String zkHostArg = (zkHost != null) ? " -z "+zkHost : "";
  String memArg = (memory != null) ? " -m "+memory : "";
  String cloudModeArg = cloudMode ? "-cloud " : "";
  String forceArg = cli.hasOption("force") ? " -force" : "";

  String addlOpts = cli.getOptionValue('a');
  String addlOptsArg = (addlOpts != null) ? " -a \""+addlOpts+"\"" : "";

  File cwd = new File(System.getProperty("user.dir"));
  File binDir = (new File(script)).getParentFile();

  boolean isWindows = (OS.isFamilyDOS() || OS.isFamilyWin9x() || OS.isFamilyWindows());
  String callScript = (!isWindows && cwd.equals(binDir.getParentFile())) ? "bin/solr" : script;

  String cwdPath = cwd.getAbsolutePath();
  String solrHome = solrHomeDir.getAbsolutePath();

  // don't display a huge path for solr home if it is relative to the cwd
  if (!isWindows && cwdPath.length() > 1 && solrHome.startsWith(cwdPath))
    solrHome = solrHome.substring(cwdPath.length()+1);

  String startCmd =
      String.format(Locale.ROOT, "\"%s\" start %s -p %d -s \"%s\" %s %s %s %s %s %s",
          callScript, cloudModeArg, port, solrHome, hostArg, zkHostArg, memArg, forceArg, extraArgs, addlOptsArg);
  startCmd = startCmd.replaceAll("\\s+", " ").trim(); // for pretty printing

  echo("\nStarting up Solr on port " + port + " using command:");
  echo(startCmd + "\n");

  String solrUrl =
      String.format(Locale.ROOT, "%s://%s:%d/solr", urlScheme, (host != null ? host : "localhost"), port);

  Map<String,Object> nodeStatus = checkPortConflict(solrUrl, solrHomeDir, port, cli);
  if (nodeStatus != null)
    return nodeStatus; // the server they are trying to start is already running

  int code = 0;
  if (isWindows) {
    // On Windows, the execution doesn't return, so we have to execute async
    // and when calling the script, it seems to be inheriting the environment that launched this app
    // so we have to prune out env vars that may cause issues
    Map<String,String> startEnv = new HashMap<>();
    Map<String,String> procEnv = EnvironmentUtils.getProcEnvironment();
    if (procEnv != null) {
      for (Map.Entry<String, String> entry : procEnv.entrySet()) {
        String envVar = entry.getKey();
        String envVarVal = entry.getValue();
        if (envVarVal != null && !"EXAMPLE".equals(envVar) && !envVar.startsWith("SOLR_")) {
          startEnv.put(envVar, envVarVal);
        }
      }
    }
    DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();
    executor.execute(org.apache.commons.exec.CommandLine.parse(startCmd), startEnv, handler);

    // wait for execution.
    try {
      handler.waitFor(3000);
    } catch (InterruptedException ie) {
      // safe to ignore ...
      Thread.interrupted();
    }
    if (handler.hasResult() && handler.getExitValue() != 0) {
      throw new Exception("Failed to start Solr using command: "+startCmd+" Exception : "+handler.getException());
    }
  } else {
    try {
      code = executor.execute(org.apache.commons.exec.CommandLine.parse(startCmd));
    } catch(ExecuteException e){
      throw new Exception("Failed to start Solr using command: "+startCmd+" Exception : "+ e);
    }
  }
  if (code != 0)
    throw new Exception("Failed to start Solr using command: "+startCmd);

  return getNodeStatus(solrUrl, maxWaitSecs);
}
 
Example #13
Source File: LaunchCommandLineTest.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
private File findFile() {
    if (OS.isFamilyWindows()) {
        return new File(new File(ClassPathHelper.getClassPath(SwingSet3.class)).getParentFile(), "swingset3.bat");
    }
    return new File(new File(ClassPathHelper.getClassPath(SwingSet3.class)).getParentFile(), "swingset3.sh");
}
 
Example #14
Source File: TestCoreContainer.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private void assertPathAllowed(String path) {
  SolrPaths.assertPathAllowed(Path.of(path), OS.isFamilyWindows() ? ALLOWED_PATHS_WIN : ALLOWED_PATHS);
}
 
Example #15
Source File: TestSolrXml.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public void testAllInfoPresent() throws IOException {
  Path testSrcRoot = TEST_PATH();
  Files.copy(testSrcRoot.resolve("solr-50-all.xml"), solrHome.resolve("solr.xml"));

  System.setProperty("solr.allowPaths", OS.isFamilyWindows() ? "C:\\tmp,C:\\home\\john" : "/tmp,/home/john");
  NodeConfig cfg = SolrXmlConfig.fromSolrHome(solrHome, new Properties());
  CloudConfig ccfg = cfg.getCloudConfig();
  UpdateShardHandlerConfig ucfg = cfg.getUpdateShardHandlerConfig();
  PluginInfo[] backupRepoConfigs = cfg.getBackupRepositoryPlugins();

  assertEquals("maxBooleanClauses", (Integer) 42, cfg.getBooleanQueryMaxClauseCount());
  assertEquals("core admin handler class", "testAdminHandler", cfg.getCoreAdminHandlerClass());
  assertEquals("collection handler class", "testCollectionsHandler", cfg.getCollectionsHandlerClass());
  assertEquals("info handler class", "testInfoHandler", cfg.getInfoHandlerClass());
  assertEquals("config set handler class", "testConfigSetsHandler", cfg.getConfigSetsHandlerClass());
  assertEquals("core load threads", 11, cfg.getCoreLoadThreadCount(false));
  assertEquals("replay update threads", 100, cfg.getReplayUpdatesThreads());
  assertThat("core root dir", cfg.getCoreRootDirectory().toString(), containsString("testCoreRootDirectory"));
  assertEquals("distrib conn timeout", 22, cfg.getUpdateShardHandlerConfig().getDistributedConnectionTimeout());
  assertEquals("distrib socket timeout", 33, cfg.getUpdateShardHandlerConfig().getDistributedSocketTimeout());
  assertEquals("max update conn", 3, cfg.getUpdateShardHandlerConfig().getMaxUpdateConnections());
  assertEquals("max update conn/host", 37, cfg.getUpdateShardHandlerConfig().getMaxUpdateConnectionsPerHost());
  assertEquals("distrib conn timeout", 22, ucfg.getDistributedConnectionTimeout());
  assertEquals("distrib socket timeout", 33, ucfg.getDistributedSocketTimeout());
  assertEquals("max update conn", 3, ucfg.getMaxUpdateConnections());
  assertEquals("max update conn/host", 37, ucfg.getMaxUpdateConnectionsPerHost());
  assertEquals("host", "testHost", ccfg.getHost());
  assertEquals("zk host context", "testHostContext", ccfg.getSolrHostContext());
  assertEquals("solr host port", 44, ccfg.getSolrHostPort());
  assertEquals("leader vote wait", 55, ccfg.getLeaderVoteWait());
  assertEquals("logging class", "testLoggingClass", cfg.getLogWatcherConfig().getLoggingClass());
  assertEquals("log watcher", true, cfg.getLogWatcherConfig().isEnabled());
  assertEquals("log watcher size", 88, cfg.getLogWatcherConfig().getWatcherSize());
  assertEquals("log watcher thresh", "99", cfg.getLogWatcherConfig().getWatcherThreshold());
  assertEquals("manage path", "testManagementPath", cfg.getManagementPath());
  assertEquals("shardLib", "testSharedLib", cfg.getSharedLibDirectory());
  assertEquals("schema cache", true, cfg.hasSchemaCache());
  assertEquals("trans cache size", 66, cfg.getTransientCacheSize());
  assertEquals("zk client timeout", 77, ccfg.getZkClientTimeout());
  assertEquals("zk host", "testZkHost", ccfg.getZkHost());
  assertEquals("zk ACL provider", "DefaultZkACLProvider", ccfg.getZkACLProviderClass());
  assertEquals("zk credentials provider", "DefaultZkCredentialsProvider", ccfg.getZkCredentialsProviderClass());
  assertEquals(1, backupRepoConfigs.length);
  assertEquals("local", backupRepoConfigs[0].name);
  assertEquals("a.b.C", backupRepoConfigs[0].className);
  assertEquals("true", backupRepoConfigs[0].attributes.get("default"));
  assertEquals(0, backupRepoConfigs[0].initArgs.size());
  assertTrue("allowPaths", cfg.getAllowPaths().containsAll(OS.isFamilyWindows() ?
          Set.of("C:\\tmp", "C:\\home\\john").stream().map(s -> Path.of(s)).collect(Collectors.toSet()) :
          Set.of("/tmp", "/home/john").stream().map(s -> Path.of(s)).collect(Collectors.toSet())
      )
  );
  System.clearProperty("solr.allowPaths");
}
 
Example #16
Source File: LaunchCommandLineTest.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
private File findFile() {
    if (OS.isFamilyWindows()) {
        return new File(new File(ClassPathHelper.getClassPath(SwingSet3.class)).getParentFile(), "swingset3.bat");
    }
    return new File(new File(ClassPathHelper.getClassPath(SwingSet3.class)).getParentFile(), "swingset3.sh");
}
 
Example #17
Source File: DeviceInfoImpl.java    From MobileDeviceInfo with Apache License 2.0 4 votes vote down vote up
private boolean isOperationSystemMacOs() {
    return OS.isFamilyMac();
}