Java Code Examples for org.apache.commons.exec.OS#isFamilyWindows()

The following examples show how to use org.apache.commons.exec.OS#isFamilyWindows() . 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: 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 5
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 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: 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 8
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 9
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);
}