/** {@inheritDoc} */
  protected ScmResult executeEditCommand(ScmProviderRepository repo, ScmFileSet files)
      throws ScmException {
    Commandline cl =
        createCommandLine((PerforceScmProviderRepository) repo, files.getBasedir(), files);
    PerforceEditConsumer consumer = new PerforceEditConsumer();
    try {
      if (getLogger().isDebugEnabled()) {
        getLogger().debug(PerforceScmProvider.clean("Executing " + cl.toString()));
      }

      CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer();
      int exitCode = CommandLineUtils.executeCommandLine(cl, consumer, err);

      if (exitCode != 0) {
        String cmdLine = CommandLineUtils.toString(cl.getCommandline());

        StringBuffer msg = new StringBuffer("Exit code: " + exitCode + " - " + err.getOutput());
        msg.append('\n');
        msg.append("Command line was:" + cmdLine);

        throw new CommandLineException(msg.toString());
      }
    } catch (CommandLineException e) {
      if (getLogger().isErrorEnabled()) {
        getLogger().error("CommandLineException " + e.getMessage(), e);
      }
    }

    if (consumer.isSuccess()) {
      return new EditScmResult(cl.toString(), consumer.getEdits());
    }

    return new EditScmResult(
        cl.toString(), "Unable to edit file(s)", consumer.getErrorMessage(), false);
  }
  /**
   * @param unusedLocale the wanted locale (actually unused).
   * @throws MavenReportException if any
   */
  protected void executeReport(Locale unusedLocale) throws MavenReportException {

    File config = buildConfigurationFile();

    Commandline cli = new Commandline();
    cli.setWorkingDirectory(getBasedir().getAbsolutePath());
    cli.setExecutable(getExecutablePath());
    cli.createArgument().setValue(config.getAbsolutePath());

    Writer stringWriter = new StringWriter();
    StreamConsumer out = new WriterStreamConsumer(stringWriter);
    StreamConsumer err = new WriterStreamConsumer(stringWriter);

    try {
      int returnCode = CommandLineUtils.executeCommandLine(cli, out, err);

      if (!isQuiet()) {
        // Get all output from doxygen and put it to the log out of Maven.
        String[] lines = stringWriter.toString().split("\n");
        for (int i = 0; i < lines.length; i++) {
          lines[i] = lines[i].replaceAll("\n|\r", "");
          getLog().info("doxygen: " + lines[i]);
        }
      }

      if (returnCode != 0) {
        throw new MavenReportException("Failed to generate Doxygen documentation.");
      }

    } catch (CommandLineException ex) {
      throw new MavenReportException("Error while executing Doxygen.", ex);
    }
  }
  /**
   * Locates the executable for the jarsigner tool.
   *
   * @Copy&paste from org.apache.maven.plugins.jarsigner.AbstractJarsignerMojo
   * @return The executable of the jarsigner tool, never <code>null<code>.
   */
  private String getExecutable() {
    String command = "jarsigner" + (Os.isFamily(Os.FAMILY_WINDOWS) ? ".exe" : "");

    String executable =
        findExecutable(
            command, System.getProperty("java.home"), new String[] {"../bin", "bin", "../sh"});

    if (executable == null) {
      try {
        Properties env = CommandLineUtils.getSystemEnvVars();

        String[] variables = {"JDK_HOME", "JAVA_HOME"};

        for (int i = 0; i < variables.length && executable == null; i++) {
          executable =
              findExecutable(command, env.getProperty(variables[i]), new String[] {"bin", "sh"});
        }
      } catch (IOException e) {
        if (getLog().isDebugEnabled()) {
          getLog()
              .warn("Failed to retrieve environment variables, cannot search for " + command, e);
        } else {
          getLog().warn("Failed to retrieve environment variables, cannot search for " + command);
        }
      }
    }

    if (executable == null) {
      executable = command;
    }

    return executable;
  }
  @Override
  public BlameScmResult executeBlameCommand(
      ScmProviderRepository repo, ScmFileSet workingDirectory, String filename)
      throws ScmException {
    Commandline cl = new Commandline();
    cl.setWorkingDirectory(workingDirectory.getBasedir());
    cl.setExecutable(EXECUTABLE);
    cl.createArg().setValue(filename);

    TfsBlameConsumer consumer = new TfsBlameConsumer(getLogger());
    CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();

    try {
      int exitCode = CommandLineUtils.executeCommandLine(cl, consumer, stderr);

      if (exitCode != 0) {
        return new BlameScmResult(
            cl.toString(),
            "The "
                + EXECUTABLE
                + " command failed. Did you install https://github.com/SonarCommunity/sonar-tfs ?",
            stderr.getOutput(),
            false);
      }
    } catch (CommandLineException ex) {
      throw new ScmException("Error while executing command.", ex);
    }

    return new BlameScmResult(cl.toString(), consumer.getLines());
  }
  /** {@inheritDoc} */
  protected ScmResult executeAddCommand(
      ScmProviderRepository repository, ScmFileSet fileSet, String message, boolean binary)
      throws ScmException {
    Commandline cl = new Commandline();
    cl.setExecutable(accurevExecutable);
    cl.setWorkingDirectory(fileSet.getBasedir().getPath());
    cl.addArguments(new String[] {"add"});
    ArrayList params = new ArrayList();
    AccuRevScmProvider.appendHostToParamsIfNeeded(
        (AccuRevScmProviderRepository) repository, params);
    cl.addArguments((String[]) params.toArray(new String[params.size()]));

    cl.addArguments(makeFileArgs(fileSet.getFileList()));

    final List filesAdded = new ArrayList();
    final CommandLineUtils.StringStreamConsumer stdout =
        new CommandLineUtils.StringStreamConsumer();
    try {
      if (0
          != CommandLineUtils.executeCommandLine(
              cl, new AddCommandStreamConsumer(stdout, filesAdded), stdout)) {
        return new AddScmResult(cl.toString(), null, stdout.getOutput(), false);
      }
    } catch (CommandLineException e) {
      throw new ScmRepositoryException("Cannot exeucute add command", e);
    }
    return new AddScmResult(cl.toString(), filesAdded);
  }
Exemple #6
0
  public static String getValue(String valueType, String folderName, String folderKey)
      throws NativeBuildException {
    Commandline cl = new Commandline();
    cl.setExecutable("reg");
    cl.createArg().setValue("query");
    cl.createArg().setValue(folderName);
    cl.createArg().setValue("/v");
    cl.createArg().setValue(folderKey);

    CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer();
    CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();

    try {
      int ok = CommandLineUtils.executeCommandLine(cl, stdout, stderr);

      if (ok != 0) {
        return null;
      }
    } catch (CommandLineException e) {
      throw new NativeBuildException(e.getMessage(), e);
    }

    String result = stdout.getOutput();

    int p = result.indexOf(valueType);

    if (p == -1) {
      return null;
    }

    return result.substring(p + valueType.length()).trim();
  }
 private String[] parseArgs(String arguments) {
   if (arguments == null || arguments.trim().isEmpty()) {
     return NO_ARGS;
   }
   try {
     arguments = arguments.replace('\n', ' ').replace('\t', ' ');
     return CommandLineUtils.translateCommandline(arguments);
   } catch (Exception ex) {
     throw new IllegalArgumentException("Failed to parse arguments [" + arguments + "]", ex);
   }
 }
  public static int execute(
      Commandline cl,
      CommandLineUtils.StringStreamConsumer stdout,
      CommandLineUtils.StringStreamConsumer stderr,
      ScmLogger logger)
      throws CommandLineException {
    int exitCode = CommandLineUtils.executeCommandLine(cl, stdout, stderr);

    exitCode = checkIfCleanUpIsNeeded(exitCode, cl, stdout, stderr, logger);

    return exitCode;
  }
  private void executeTests(final Set<File> dartPackageRoots)
      throws MojoExecutionException, MojoFailureException {

    final Commandline cl = createBaseCommandline();

    final Arg scriptArg = cl.createArg(true);

    final StreamConsumer output = new WriterStreamConsumer(new OutputStreamWriter(System.out));
    final StreamConsumer error = new WriterStreamConsumer(new OutputStreamWriter(System.err));

    final Set<File> testSources = computeTestToRun(dartPackageRoots);

    System.out.println();
    System.out.println();

    boolean fail = false;

    for (final File dartTestFile : testSources) {
      try {

        scriptArg.setValue(dartTestFile.getAbsolutePath());

        getLog().info("Execute test: " + dartTestFile.getAbsolutePath());

        if (getLog().isDebugEnabled()) {
          getLog().debug("Execute test command: " + cl.toString());
        }

        final int returnValue = CommandLineUtils.executeCommandLine(cl, output, error);
        System.out.println();
        System.out.println();

        if (getLog().isDebugEnabled()) {
          getLog().debug("test return code: " + returnValue);
        }
        if (returnValue != 0 && returnValue != 255) {
          throw new MojoExecutionException("Test fail returned error code " + returnValue);
        } else if (returnValue != 255) {
          fail = true;
        }

      } catch (final CommandLineException e) {
        getLog().error("error running tests: ", e);
        fail = true;
      }
    }

    reportExecution(testSources, fail);

    System.out.println();
    System.out.println();
  }
  public void execute() throws MojoExecutionException {
    getLog()
        .info("Invoking xgettext for Java files in '" + sourceDirectory.getAbsolutePath() + "'.");

    Commandline cl = new Commandline();
    cl.setExecutable(xgettextCmd);
    cl.createArg().setValue("--from-code=" + encoding);
    cl.createArg().setValue("--output=" + new File(poDirectory, keysFile).getAbsolutePath());
    cl.createArg().setValue("--language=Java");
    cl.createArg().setValue("--sort-output");
    // cl.createArg().setValue("--join-existing");
    cl.createArg().setLine(keywords);
    cl.setWorkingDirectory(sourceDirectory.getAbsolutePath());

    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(sourceDirectory);
    ds.setIncludes(new String[] {"**/*.java"});
    ds.scan();
    String[] files = ds.getIncludedFiles();
    List<String> fileNameList = Collections.emptyList();
    if (extraSourceFiles != null && extraSourceFiles.getDirectory() != null) {
      try {
        fileNameList =
            FileUtils.getFileNames(
                new File(extraSourceFiles.getDirectory()),
                StringUtils.join(extraSourceFiles.getIncludes().iterator(), ","),
                StringUtils.join(extraSourceFiles.getExcludes().iterator(), ","),
                false);
      } catch (IOException e) {
        throw new MojoExecutionException("error finding extra source files", e);
      }
    }

    File file = createListFile(files, fileNameList);
    if (file != null) {
      cl.createArg().setValue("--files-from=" + file.getAbsolutePath());
    } else {
      for (String file1 : files) {
        cl.createArg().setValue(getAbsolutePath(file1));
      }
    }

    getLog().debug("Executing: " + cl.toString());
    StreamConsumer out = new LoggerStreamConsumer(getLog(), LoggerStreamConsumer.INFO);
    StreamConsumer err = new LoggerStreamConsumer(getLog(), LoggerStreamConsumer.WARN);
    try {
      CommandLineUtils.executeCommandLine(cl, out, err);
    } catch (CommandLineException e) {
      throw new MojoExecutionException("Could not execute " + xgettextCmd + ".", e);
    }
  }
 private List<String> getJvmArgs() {
   List<String> extra = new ArrayList<String>();
   String userExtraJvmArgs = getExtraJvmArgs();
   if (userExtraJvmArgs != null) {
     try {
       return new ArrayList<String>(
           Arrays.asList(
               CommandLineUtils.translateCommandline(
                   StringUtils.removeDuplicateWhitespace(userExtraJvmArgs))));
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
   return extra;
 }
  public static int execute(
      Commandline cl,
      StreamConsumer consumer,
      CommandLineUtils.StringStreamConsumer stderr,
      ScmLogger logger)
      throws CommandLineException {
    // SCM-482: force English resource bundle
    cl.addEnvironment("LC_MESSAGES", "en");

    int exitCode = CommandLineUtils.executeCommandLine(cl, consumer, stderr);

    exitCode = checkIfCleanUpIsNeeded(exitCode, cl, consumer, stderr, logger);

    return exitCode;
  }
  public void testFolderJava7() throws IOException, CommandLineException {

    if (Os.isFamily(Os.FAMILY_WINDOWS) || Os.isFamily(Os.FAMILY_WIN9X)) {
      return; // Nothing to do here.
    }

    URL resource =
        Thread.currentThread()
            .getContextClassLoader()
            .getResource(getClass().getName().replace('.', '/') + ".class");

    if (resource == null) {
      throw new IllegalStateException(
          "SOMETHING IS VERY WRONG. CANNOT FIND THIS TEST CLASS IN THE CLASSLOADER.");
    }

    File f = new File(resource.getPath().replaceAll("%20", " "));
    final File aDir = f.getParentFile().getParentFile().getParentFile();

    Commandline commandLine = new Commandline("chmod");
    commandLine.addArguments(new String[] {"763", f.getAbsolutePath()});

    CommandLineUtils.executeCommandLine(commandLine, null, null);
    Map attrs =
        PlexusIoResourceAttributeUtils.getFileAttributesByPath(
            aDir, new ConsoleLogger(Logger.LEVEL_INFO, "test"), Logger.LEVEL_DEBUG);

    PlexusIoResourceAttributes fileAttrs =
        (PlexusIoResourceAttributes) attrs.get(f.getAbsolutePath());

    assertTrue(fileAttrs.isGroupReadable());
    assertTrue(fileAttrs.isGroupWritable());
    assertFalse(fileAttrs.isGroupExecutable());

    assertTrue(fileAttrs.isOwnerExecutable());
    assertTrue(fileAttrs.isOwnerReadable());
    assertTrue(fileAttrs.isOwnerWritable());

    assertTrue(fileAttrs.isWorldExecutable());
    assertFalse(fileAttrs.isWorldReadable());
    assertTrue(fileAttrs.isWorldWritable());

    assertNotNull(fileAttrs);
  }
  void signFile(File archive) throws MojoExecutionException {
    getLog().info("Executing jarsigner on " + archive.getAbsolutePath());

    Commandline commandLine = new Commandline();

    commandLine.setExecutable(this.executable);

    commandLine.setWorkingDirectory(this.project.getBasedir());

    commandLine = getCommandline(archive, commandLine);

    getLog().debug("Executing: " + commandLine);

    StreamConsumer out =
        new StreamConsumer() {
          public void consumeLine(String line) {
            getLog().debug(line);
          }
        };

    StreamConsumer err =
        new StreamConsumer() {
          public void consumeLine(String line) {
            getLog().warn(line);
          }
        };

    try {
      int rc = CommandLineUtils.executeCommandLine(commandLine, out, err);

      if (rc != 0) {
        throw new MojoExecutionException(
            "Could not sign jar "
                + archive
                + " (return code "
                + rc
                + "), command line was "
                + commandLine);
      }
    } catch (CommandLineException e) {
      throw new MojoExecutionException("Could not sign jar " + archive, e);
    }
  }
  /** {@inheritDoc} */
  protected ExportScmResult executeCvsCommand(Commandline cl) throws ScmException {
    CvsUpdateConsumer consumer = new CvsUpdateConsumer(getLogger());

    CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();

    int exitCode;

    try {
      exitCode = CommandLineUtils.executeCommandLine(cl, consumer, stderr);
    } catch (CommandLineException ex) {
      throw new ScmException("Error while executing command.", ex);
    }

    if (exitCode != 0) {
      return new ExportScmResult(
          cl.toString(), "The cvs command failed.", stderr.getOutput(), false);
    }

    return new ExportScmResult(cl.toString(), consumer.getUpdatedFiles());
  }
  public static int executeCleanUp(
      File workinDirectory, StreamConsumer stdout, StreamConsumer stderr, ScmLogger logger)
      throws CommandLineException {
    Commandline cl = new Commandline();

    cl.setExecutable("svn");

    cl.setWorkingDirectory(workinDirectory.getAbsolutePath());

    if (logger != null) {
      if (logger.isInfoEnabled()) {
        logger.info("Executing: " + SvnCommandLineUtils.cryptPassword(cl));

        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
          logger.info("Working directory: " + cl.getWorkingDirectory().getAbsolutePath());
        }
      }
    }

    return CommandLineUtils.executeCommandLine(cl, stdout, stderr);
  }
  private static int checkIfCleanUpIsNeeded(
      int exitCode,
      Commandline cl,
      StreamConsumer consumer,
      CommandLineUtils.StringStreamConsumer stderr,
      ScmLogger logger)
      throws CommandLineException {
    if (exitCode != 0
        && stderr.getOutput() != null
        && stderr.getOutput().indexOf("'svn cleanup'") > 0
        && stderr.getOutput().indexOf("'svn help cleanup'") > 0) {
      if (logger.isInfoEnabled()) {
        logger.info(
            "Svn command failed due to some locks in working copy. We try to run a 'svn cleanup'.");
      }

      if (executeCleanUp(cl.getWorkingDirectory(), consumer, stderr, logger) == 0) {
        exitCode = CommandLineUtils.executeCommandLine(cl, consumer, stderr);
      }
    }
    return exitCode;
  }
Exemple #18
0
  private List compileOutOfProcess(File workingDirectory, String executable, String[] args)
      throws CompilerException {
    Commandline cli = new Commandline();

    cli.setWorkingDirectory(workingDirectory.getAbsolutePath());

    cli.setExecutable(executable);

    cli.addArguments(args);

    CommandLineUtils.StringStreamConsumer out = new CommandLineUtils.StringStreamConsumer();

    CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer();

    int returnCode;

    List messages;

    try {
      returnCode = CommandLineUtils.executeCommandLine(cli, out, err);

      messages = parseModernStream(new BufferedReader(new StringReader(err.getOutput())));
    } catch (CommandLineException e) {
      throw new CompilerException("Error while executing the external compiler.", e);
    } catch (IOException e) {
      throw new CompilerException("Error while executing the external compiler.", e);
    }

    if (returnCode != 0 && messages.isEmpty()) {
      // TODO: exception?
      messages.add(
          new CompilerError(
              "Failure executing javac,  but could not parse the error:" + EOL + err.getOutput(),
              true));
    }

    return messages;
  }
Exemple #19
0
 @Override
 public void execute() throws MojoExecutionException, MojoFailureException {
   Commandline cl = new Commandline();
   cl.setExecutable(msginitCmd);
   cl.createArg().setValue("-i");
   cl.createArg().setFile(keysFile);
   cl.createArg().setValue("-l");
   cl.createArg().setValue(locale);
   cl.createArg().setValue("-o");
   File poFile = new File(poDirectory, locale + ".po");
   cl.createArg().setFile(poFile);
   cl.createArg().setValue("--no-translator");
   StreamConsumer out = new LoggerStreamConsumer(getLog(), LoggerStreamConsumer.INFO);
   StreamConsumer err = new LoggerStreamConsumer(getLog(), LoggerStreamConsumer.WARN);
   try {
     CommandLineUtils.executeCommandLine(cl, out, err);
     if (poFile.exists() && buildContext != null) {
       buildContext.refresh(poFile);
     }
   } catch (CommandLineException e) {
     throw new MojoExecutionException("Could not execute " + msginitCmd, e);
   }
 }
  private List compileOutOfProcess(
      File workingDirectory, File target, String executable, String[] args)
      throws CompilerException {
    // ----------------------------------------------------------------------
    // Build the @arguments file
    // ----------------------------------------------------------------------

    File file;

    PrintWriter output = null;

    try {
      file = new File(target, ARGUMENTS_FILE_NAME);

      output = new PrintWriter(new FileWriter(file));

      for (int i = 0; i < args.length; i++) {
        String arg = args[i];

        output.println(arg);
      }
    } catch (IOException e) {
      throw new CompilerException("Error writing arguments file.", e);
    } finally {
      IOUtil.close(output);
    }

    // ----------------------------------------------------------------------
    // Execute!
    // ----------------------------------------------------------------------

    Commandline cli = new Commandline();

    cli.setWorkingDirectory(workingDirectory.getAbsolutePath());

    cli.setExecutable(executable);

    cli.createArgument().setValue("@" + file.getAbsolutePath());

    Writer stringWriter = new StringWriter();

    StreamConsumer out = new WriterStreamConsumer(stringWriter);

    StreamConsumer err = new WriterStreamConsumer(stringWriter);

    int returnCode;

    List messages;

    try {
      returnCode = CommandLineUtils.executeCommandLine(cli, out, err);

      messages = parseCompilerOutput(new BufferedReader(new StringReader(stringWriter.toString())));
    } catch (CommandLineException e) {
      throw new CompilerException("Error while executing the external compiler.", e);
    } catch (IOException e) {
      throw new CompilerException("Error while executing the external compiler.", e);
    }

    if (returnCode != 0 && messages.isEmpty()) {
      // TODO: exception?
      messages.add(
          new CompilerError(
              "Failure executing the compiler, but could not parse the error:"
                  + EOL
                  + stringWriter.toString(),
              true));
    }

    return messages;
  }
  private void runForked(Set<URI> classPath, Class<?> cls, String[] args)
      throws MojoExecutionException {
    getLog().info("Running wsdl2java in fork mode...");

    Commandline cmd = new Commandline();
    cmd.getShell().setQuotedArgumentsEnabled(true); // for JVM args
    cmd.setWorkingDirectory(project.getBuild().getDirectory());
    try {
      cmd.setExecutable(getJavaExecutable().getAbsolutePath());
    } catch (IOException e) {
      getLog().debug(e);
      throw new MojoExecutionException(e.getMessage(), e);
    }

    cmd.createArg().setLine(additionalJvmArgs);

    File file = null;
    try {
      // file = new File("/tmp/test.jar");
      file = FileUtils.createTempFile("cxf-codegen", ".jar");

      JarArchiver jar = new JarArchiver();
      jar.setDestFile(file.getAbsoluteFile());

      Manifest manifest = new Manifest();
      Attribute attr = new Attribute();
      attr.setName("Class-Path");
      StringBuilder b = new StringBuilder(8000);
      for (URI cp : classPath) {
        b.append(cp.toURL().toExternalForm()).append(' ');
      }
      attr.setValue(b.toString());
      manifest.getMainSection().addConfiguredAttribute(attr);

      attr = new Attribute();
      attr.setName("Main-Class");
      attr.setValue(cls.getName());
      manifest.getMainSection().addConfiguredAttribute(attr);

      jar.addConfiguredManifest(manifest);
      jar.createArchive();

      cmd.createArg().setValue("-jar");
      cmd.createArg().setValue(file.getAbsolutePath());

    } catch (Exception e1) {
      throw new MojoExecutionException("Could not create runtime jar", e1);
    }
    cmd.addArguments(args);

    CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer();
    CommandLineUtils.StringStreamConsumer out = new CommandLineUtils.StringStreamConsumer();

    int exitCode;
    try {
      exitCode = CommandLineUtils.executeCommandLine(cmd, out, err);
    } catch (CommandLineException e) {
      getLog().debug(e);
      throw new MojoExecutionException(e.getMessage(), e);
    }

    String output = StringUtils.isEmpty(out.getOutput()) ? null : '\n' + out.getOutput().trim();

    String cmdLine = CommandLineUtils.toString(cmd.getCommandline());

    if (exitCode != 0) {
      if (StringUtils.isNotEmpty(output)) {
        getLog().info(output);
      }

      StringBuffer msg = new StringBuffer("\nExit code: ");
      msg.append(exitCode);
      if (StringUtils.isNotEmpty(err.getOutput())) {
        msg.append(" - ").append(err.getOutput());
      }
      msg.append('\n');
      msg.append("Command line was: ").append(cmdLine).append('\n').append('\n');

      throw new MojoExecutionException(msg.toString());
    }

    if (file != null) {
      file.delete();
    }
    if (StringUtils.isNotEmpty(err.getOutput()) && err.getOutput().contains("WSDL2Java Error")) {
      StringBuffer msg = new StringBuffer();
      msg.append(err.getOutput());
      msg.append('\n');
      msg.append("Command line was: ").append(cmdLine).append('\n').append('\n');
      throw new MojoExecutionException(msg.toString());
    }
  }