/**
   * Executes the ffmpeg process with the previous given arguments.
   *
   * @return The standard output of the child process.
   * @throws IOException If the process call fails.
   */
  public String execute() throws IOException {
    CommandLine cmdLine = new CommandLine(ffmpegExecutablePath);

    int fileNumber = 0;
    Map<String, File> map = new HashMap<String, File>();
    for (int i = 0; i < args.size(); i++) {
      final String arg = args.get(i);
      final Boolean isFile = argIsFile.get(i);
      if (isFile) {
        String key = "file" + fileNumber;
        map.put(key, new File(arg));
        cmdLine.addArgument("${" + key + "}", false);
        fileNumber++;
      } else {
        cmdLine.addArgument(arg);
      }
    }
    cmdLine.setSubstitutionMap(map);
    LOG.fine("Execute: " + cmdLine);
    DefaultExecutor executor = new DefaultExecutor();
    // 5minutes wait
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000 * 5);
    executor.setWatchdog(watchdog);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(out));
    int[] exitValues = {0, 1};
    executor.setExitValues(exitValues);
    executor.execute(cmdLine);
    return out.toString();
  }
Example #2
0
  /**
   * Create a complete command line, including path and arguments.
   *
   * @return Configured command line, ready for execution
   */
  private CommandLine createCommandLine() {
    final String javaPath = getJavaPath();

    final String gsHome = Environment.getHomeDirectory();
    final String[] commandParams = {
      "-Dcom.gs.home=" + gsHome,
      "-Dorg.hyperic.sigar.path=" + gsHome + "/lib/platform/sigar",
      "-Dcom.gs.usm.RecipeShutdownTimeout=" + timeout,
      IntegratedProcessingUnitContainer.class.getName(),
      "-cluster",
      "id=1",
      "total_members=1"
    };
    final CommandLine cmdLine = new CommandLine(javaPath);

    for (final String param : commandParams) {
      cmdLine.addArgument(param);
    }
    if (this.serviceFileName != null) {
      cmdLine.addArgument("-properties");
      cmdLine.addArgument(
          "embed://"
              + CloudifyConstants.CONTEXT_PROPERTY_SERVICE_FILE_NAME
              + "="
              + this.serviceFileName);
    }

    // -Dcom.gs.usm.RecipeShutdownTimeout=10

    return cmdLine;
  }
 private CommandLine getWindowsKillCommand(int pid) {
   CommandLine command = new CommandLine("taskkill");
   command.addArgument("/F");
   command.addArgument("/PID");
   command.addArgument("" + pid);
   command.addArgument("/T");
   return command;
 }
Example #4
0
 /**
  * Generates a CommandLine to execute a program.
  *
  * @param mode
  * @param executable
  * @return
  */
 public static CommandLine getCommandLine(ExecutionMode mode, String executable) {
   CommandLine command = null;
   if (ExecutionMode.INTERACTIVE.equals(mode) && SystemUtils.IS_OS_WINDOWS) {
     command = new CommandLine("cmd");
     command.addArgument("/c");
     command.addArgument("start");
     command.addArgument(executable);
   } else {
     command = new CommandLine(executable);
   }
   return command;
 }
Example #5
0
  /**
   * Create user on the system. Synchronized to prevent multiple threads from trying to create user
   * at the same time.
   *
   * @param user user id
   * @param group group id
   * @throws GenieException If there is any problem.
   */
  protected synchronized void createUser(final String user, final String group)
      throws GenieException {

    // First check if user already exists
    final CommandLine idCheckCommandLine =
        new CommandLine("id").addArgument("-u").addArgument(user);

    try {
      this.executor.execute(idCheckCommandLine);
      log.debug("User already exists");
    } catch (final IOException ioe) {
      log.debug("User does not exist. Creating it now.");

      // Determine if the group is valid by checking that its not null and not same as user.
      final boolean isGroupValid = StringUtils.isNotBlank(group) && !group.equals(user);

      // Create the group for the user if its not the same as the user.
      if (isGroupValid) {
        log.debug("Group and User are different so creating group now.");
        final CommandLine groupCreateCommandLine =
            new CommandLine("sudo").addArgument("groupadd").addArgument(group);

        // We create the group and ignore the error as it will fail if group already exists.
        // If the failure is due to some other reason, then user creation will fail and we catch
        // that.
        try {
          log.debug(
              "Running command to create group:  [" + groupCreateCommandLine.toString() + "]");
          this.executor.execute(groupCreateCommandLine);
        } catch (IOException ioexception) {
          log.debug("Group creation threw an error as it might already exist");
        }
      }

      final CommandLine userCreateCommandLine =
          new CommandLine("sudo").addArgument("useradd").addArgument(user);
      if (isGroupValid) {
        userCreateCommandLine.addArgument("-G").addArgument(group);
      }
      userCreateCommandLine.addArgument("-M");

      try {
        log.debug("Running command to create user: [" + userCreateCommandLine.toString() + "]");
        this.executor.execute(userCreateCommandLine);
      } catch (IOException ioexception) {
        throw new GenieServerException(
            "Could not create user " + user + " with exception " + ioexception);
      }
    }
  }
Example #6
0
  /** For console commands on Windows only */
  protected org.apache.commons.exec.CommandLine getConsoleCommandLine(
      String scriptName, String... args) {
    org.apache.commons.exec.CommandLine result;

    result = new org.apache.commons.exec.CommandLine("cmd.exe");
    result.addArgument("/C");
    result.addArgument("start");
    result.addArgument("/I");
    result.addArgument(scriptName.replace('/', '\\') + ".bat");

    for (String arg : args) {
      result.addArgument(arg);
    }

    return result;
  }
  private boolean repoExists(File targetDir) throws Exception {
    validateExecutableInstance(EXECUTABLE);

    CommandLine command = CommandLine.parse(EXECUTABLE);

    command.addArgument("status");

    CommandResults commandResults;
    try {
      commandResults = commandLineExecutor.executeCommandForOutput(log, command, targetDir);
    } catch (Exception e) {
      log.error("Failure executing SVN Command", e);
      commandResults = null;
    }

    if (commandResults != null && commandResults.getStatus() == 0) {

      // warning message of form "svn: warning: W155007: 'C:\SVNFiles' is
      // not a working copy" only
      // printed when repository is not checked out to directory
      if (commandResults.getOutput().trim().contains("warning")) {
        log.info("repository does not exist in directory: " + targetDir.getAbsolutePath());
        return false;
      }

      log.info("repository exists in directory: " + targetDir.getAbsolutePath());

      return true;
    } else {
      log.info("repository does not exist in directory: " + targetDir.getAbsolutePath());
      return false;
    }
  }
  private CommandLine makeCommandLine(String program, List<String> args)
      throws NotAuthorizedException, IOException {
    String path = validateProgram(program);
    CommandLine cmd = new CommandLine(path);
    if (args != null) for (String arg : args) cmd.addArgument(arg, false);

    return cmd;
  }
Example #9
0
  /**
   * Executes <code>commandLine</code>. Sometimes (especially observed on MacOS) the commandLine
   * isn't executed properly. In that cases another exec-method is to be used. To accomplish this
   * please use the special delimiter '<code>@@</code>'. If <code>commandLine</code> contains this
   * delimiter it is split into a String[] array and the special exec-method is used.
   *
   * <p>A possible {@link IOException} gets logged but no further processing is done.
   *
   * @param commandLine the command line to execute
   * @param timeout timeout for execution in milliseconds
   * @return response data from executed command line
   */
  public static String executeCommandLineAndWaitResponse(String commandLine, int timeout) {
    String retval = null;

    CommandLine cmdLine = null;

    if (commandLine.contains(CMD_LINE_DELIMITER)) {
      String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
      cmdLine = new CommandLine(cmdArray[0]);

      for (int i = 1; i < cmdArray.length; i++) {
        cmdLine.addArgument(cmdArray[i], false);
      }
    } else {
      cmdLine = CommandLine.parse(commandLine);
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    Executor executor = new DefaultExecutor();

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);

    executor.setExitValue(1);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);

    try {
      executor.execute(cmdLine, resultHandler);
      logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
      logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    } catch (IOException e) {
      logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    }

    // some time later the result handler callback was invoked so we
    // can safely request the exit code
    try {
      resultHandler.waitFor();
      int exitCode = resultHandler.getExitValue();
      retval = StringUtils.chomp(stdout.toString());
      if (resultHandler.getException() != null) {
        logger.warn(resultHandler.getException().getMessage());
      } else {
        logger.debug("exit code '{}', result '{}'", exitCode, retval);
      }

    } catch (InterruptedException e) {
      logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }

    return retval;
  }
Example #10
0
  protected org.apache.commons.exec.CommandLine getCommandLine(
      boolean addShExt, String scriptName, String... args) {
    org.apache.commons.exec.CommandLine result;

    if (isWindows()) {
      result = new org.apache.commons.exec.CommandLine("cmd.exe");
      result.addArgument("/C");
      result.addArgument(scriptName.replace('/', '\\') + ".bat");
    } else {
      result =
          new org.apache.commons.exec.CommandLine(
              "./" + (addShExt ? scriptName + ".sh" : scriptName));
    }

    for (String arg : args) {
      result.addArgument(arg);
    }

    return result;
  }
  public String toString() {
    CommandLine cmdLine = new CommandLine(ffmpegExecutablePath);

    int fileNumber = 0;
    Map<String, File> map = new HashMap<String, File>();
    for (int i = 0; i < args.size(); i++) {
      final String arg = args.get(i);
      final Boolean isFile = argIsFile.get(i);
      if (isFile) {
        String key = "file" + fileNumber;
        map.put(key, new File(arg));
        cmdLine.addArgument("${" + key + "}", false);
        fileNumber++;
      } else {
        cmdLine.addArgument(arg);
      }
    }
    cmdLine.setSubstitutionMap(map);
    return cmdLine.toString();
  }
Example #12
0
  public static String sync_getVerificationOutput(
      String lolaBinPath,
      String modelToVerify,
      String propertyToVerify,
      boolean useCoverabilitySearch,
      final int timeoutInSeconds)
      throws Exception {

    int cores = Runtime.getRuntime().availableProcessors();
    String filePath =
        System.getProperty("java.io.tmpdir") + "/" + java.util.UUID.randomUUID() + ".lola";
    IOUtils.writeFile(modelToVerify.getBytes(), filePath, false);
    // IOUtils.writeFile(propertyToVerify.getBytes(), filePath+".ctl", false);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine cmdLine = new CommandLine(lolaBinPath);

    cmdLine.addArgument("--nolog");

    // cmdLine.addArgument("--formula="+filePath+".ctl", false);
    cmdLine.addArgument("--formula=" + propertyToVerify, false);
    cmdLine.addArgument("--threads=" + cores);
    if (useCoverabilitySearch) cmdLine.addArgument("--search=cover");
    cmdLine.addArgument("-p");
    // cmdLine.addArgument("--path=\""+filePath+".out\"", false);
    // cmdLine.addArgument("--state=\""+filePath+".out\"", false);
    cmdLine.addArgument(filePath, false);

    DefaultExecutor exec = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(1000 * timeoutInSeconds);

    exec.setWatchdog(watchdog);
    exec.setStreamHandler(streamHandler);
    exec.setExitValues(new int[] {0, 1, 2, 139, 35584});
    int exitVal = exec.execute(cmdLine);

    String output = outputStream.toString();

    if (watchdog.killedProcess())
      throw new Exception(
          "ERROR: Timeout occurred. LOLA has reached the execution time limit of "
              + timeoutInSeconds
              + " seconds, so it has been aborted.\nPartial Output:\n"
              + output);

    if (exitVal != 0 || output.equals("") || output.contains("aborting [#"))
      throw new Exception(
          "ERROR: LOLA internal error\nExit code:"
              + exitVal
              + "\nExec: "
              + cmdLine.toString()
              + "\nOutput:\n"
              + output);
    new File(filePath).delete();
    return output;
  }
  @Override
  public int sync() {

    int exitStatus = -1;

    try {
      File targetDir = new File(getFinalSourceDirectory());

      CommandLine command = CommandLine.parse(EXECUTABLE);

      if (!repoExists(targetDir)) {
        command.addArgument("co");
        command.addArgument(repositoryURL);
      } else {
        command.addArgument("up");
      }

      // now add destination
      // command.addArgument(targetDir.getAbsolutePath());
      if (user != null && !user.isEmpty()) {
        command.addArgument("--username");
        command.addArgument(user);
        if (!password.isEmpty()) {
          command.addArgument("--password");
          command.addArgument(password);
        }
      }

      command.addArgument("--non-interactive");

      for (String svnFlag : svnFlagsList) {
        command.addArgument(svnFlag);
      }

      exitStatus = commandLineExecutor.executeCommand(log, command, targetDir);

    } catch (Exception e) {
      log.error("Unable to perform sync: " + e.getMessage());
    }
    return exitStatus;
  }
  @Override
  public void init() throws Exception {

    // pdf2json settings
    for (final Map.Entry<String, String> entry : System.getenv().entrySet()) {
      if ("path".equals(entry.getKey().toLowerCase())) {
        try {
          CommandLine commandLine = new CommandLine("pdf2json");
          commandLine.addArgument("-v");
          ExternalExecution.exec(
              commandLine, Config.init().successfulExitStatusValueIs(1).doNotDisplayErrorTrace());
          isActivated = true;
        } catch (final Exception e) {
          // pdf2json is not installed
          System.err.println("pdf2json is not installed");
        }
      }
    }
  }
Example #15
0
 /**
  * Executes a java command from within
  *
  * @param session
  * @param toolchainManager
  * @param mode
  * @param mainClass
  * @param vmargs
  * @param mainArgs
  * @throws MojoExecutionException
  */
 @SuppressWarnings("rawtypes")
 public static void executeJava(
     MavenSession session,
     ToolchainManager toolchainManager,
     ExecutionMode mode,
     String mainClass,
     String[] vmargs,
     String[] mainArgs)
     throws MojoExecutionException {
   String javaExecutable = getJavaExecutable(session, toolchainManager);
   CommandLine command = getCommandLine(mode, javaExecutable);
   if (vmargs != null) {
     command.addArguments(vmargs, false);
   }
   command.addArgument(mainClass);
   if (mainArgs != null) {
     command.addArguments(mainArgs, false);
   }
   execute(session, command, null, new HashMap());
 }
Example #16
0
  public String getDockerHostIpAddress(Map<String, String> environment) {
    String ipAddress = LOCALHOST; // Default of localhost
    String dockerMachineName = getDockerMachineName(environment);

    if (!dockerMachineName.isEmpty()) {
      LOG.debug("Docker machine name = " + dockerMachineName);
      CommandLine commandline = CommandLine.parse(DOCKER_MACHINE_IP);
      commandline.addArgument(dockerMachineName);
      LOG.debug("Running exec: " + commandline.toString());
      try {
        ipAddress = StringUtils.strip(runCommand(commandline));
      } catch (IOException e) {
        LOG.error("Unable to run exec command to find ip address.", e);
      }
    } else {
      ipAddress = getDocker0AdapterIPAddress();
    }
    LOG.debug("Returned IP address: " + ipAddress);
    return ipAddress;
  }
  public int retrievePageCount(File source) {

    File target =
        new File(
            System.getProperty("java.io.tmpdir"),
            FilenameUtils.removeExtension(source.getName()) + ".pdf");

    Map<String, Object> args = newHashMap();
    args.put("source", source);
    args.put("targetDir", target.getParentFile());

    CommandLine cmd = new CommandLine("loffice");
    cmd.addArgument("--headless");
    cmd.addArgument("--convert-to");
    cmd.addArgument("pdf");
    cmd.addArgument("--outdir");
    cmd.addArgument("${targetDir}");
    cmd.addArgument("${source}");
    cmd.setSubstitutionMap(args);

    try {
      DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

      ExecuteWatchdog watchdog = new ExecuteWatchdog(10L * 1000L);
      executor.setWatchdog(watchdog);
      logger.trace("About to execute command {}", cmd.toString());
      executor.execute(cmd, resultHandler);

      resultHandler.waitFor();
      final int exitValue = resultHandler.getExitValue();

      if (exitValue != 0) {
        logger.error(
            "Unable to convert Microsoft Word file {} to PDF. Exit code = {}",
            source.getAbsolutePath(),
            exitValue);
        return -1;
      }
      final int pageCount = pdfDocumentInspector.retrievePageCount(target);
      deleteFileIfNeeded(target);
      return pageCount;

    } catch (IOException | InterruptedException e) {
      logger.error("Unable to create a PDF from {}", source.getAbsolutePath(), e);
      deleteFileIfNeeded(target);
      return -1;
    }
  }
Example #18
0
  public void runScript(String command) {
    sCommandString = command;
    CommandLine oCmdLine = CommandLine.parse(sCommandString);

    oCmdLine.addArgument("sanga.txt");

    DefaultExecutor oDefaultExecutor = new DefaultExecutor();
    // oDefaultExecutor.setWorkingDirectory(new File(command.getWorkingDir()).getAbsoluteFile());
    // oDefaultExecutor.setExitValue(1);
    try {
      oDefaultExecutor.setWorkingDirectory(new File("/Users/212433329/bharshell"));
      iExitValue = oDefaultExecutor.execute(oCmdLine);
    } catch (ExecuteException e) {
      // TODO Auto-generated catch block
      System.err.println("Execution failed.");
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      System.err.println("permission denied.");
      e.printStackTrace();
    }
  }
  protected Status processCommunicateAction(
      final Exchange exchange, final CommunicateAction communicateAction) throws IOException {
    final EmotionKind emotionKind =
        Optional.ofNullable(communicateAction.getEmotionKind()).orElse(EmotionKind.NEUTRAL);
    final Locale lang = Optional.ofNullable(communicateAction.getInLanguage()).orElse(Locale.US);
    log.info("Got speech lang-legacy={}: {}", lang.getLanguage(), communicateAction);
    final String avatarId = Optional.ofNullable(communicateAction.getAvatarId()).orElse("nao1");

    // final File wavFile = File.createTempFile("lumen-speech-synthesis_", ".wav");
    //                        final File oggFile = File.createTempFile("lumen-speech-synthesis_",
    // ".ogg");
    try {
      byte[] wavBytes = null;
      if (INDONESIAN.getLanguage().equals(lang.getLanguage())) {
        // Expressive speech (for now, Indonesian only)
        try {
          PhonemeDoc phonemeDoc;
          if (EmotionKind.NEUTRAL == emotionKind) {
            phonemeDoc = speechProsody.performNeutral(communicateAction.getObject());
          } else {
            try {
              final EmotionProsody emotionProsody =
                  emotionProsodies
                      .getEmotion(emotionKind)
                      .orElseThrow(
                          () ->
                              new SpeechSynthesisException(
                                  "Emotion " + emotionKind + " not supported"));
              phonemeDoc = speechProsody.perform(communicateAction.getObject(), emotionProsody);
            } catch (Exception e) {
              log.error(
                  "Cannot speak with emotion "
                      + emotionKind
                      + ", falling back to NEUTRAL: "
                      + communicateAction.getObject(),
                  e);
              phonemeDoc = speechProsody.performNeutral(communicateAction.getObject());
            }
          }

          try (final ByteArrayInputStream objectIn =
                  new ByteArrayInputStream(phonemeDoc.toString().getBytes(StandardCharsets.UTF_8));
              final ByteArrayOutputStream wavStream = new ByteArrayOutputStream();
              final ByteArrayOutputStream err = new ByteArrayOutputStream()) {
            final CommandLine cmdLine = new CommandLine("mbrola");
            cmdLine.addArgument("-v");
            cmdLine.addArgument(String.valueOf(INDONESIAN_AMPLITUDE / 100f));
            cmdLine.addArgument(new File(mbrolaShareFolder, "id1/id1").toString());
            cmdLine.addArgument("-");
            cmdLine.addArgument("-.wav");
            executor.setStreamHandler(new PumpStreamHandler(wavStream, err, objectIn));
            final int executed;
            try {
              executed = executor.execute(cmdLine);
              wavBytes = wavStream.toByteArray();
            } finally {
              log.info("{}: {}", cmdLine, err.toString());
            }
          }
        } catch (Exception e) {
          log.error(
              "Cannot speak Indonesian using prosody engine, falling back to direct espeak: "
                  + communicateAction.getObject(),
              e);
        }
      }
      if (wavBytes == null) {
        // Neutral speech using direct espeak
        try {
          wavBytes = performEspeak(communicateAction, lang);
        } catch (Exception e) {
          if (!Locale.US.getLanguage().equals(lang.getLanguage())) {
            // Indonesian sometimes fails especially "k-k", e.g. "baik koq".
            // retry using English as last resort, as long as it says something!
            log.error(
                "Cannot speak using "
                    + lang.toLanguageTag()
                    + ", falling back to English (US): "
                    + communicateAction.getObject(),
                e);
            wavBytes = performEspeak(communicateAction, Locale.US);
          } else {
            throw e;
          }
        }
      }

      log.info("espeak/mbrola generated {} bytes WAV", wavBytes.length);
      try (final ByteArrayInputStream wavIn = new ByteArrayInputStream(wavBytes);
          final ByteArrayOutputStream bos = new ByteArrayOutputStream();
          final ByteArrayOutputStream err = new ByteArrayOutputStream()) {
        // flac.exe doesn't support mp3, and that's a problem for now (note: mp3 patent is expiring)
        final CommandLine cmdLine = new CommandLine(ffmpegExecutable);
        cmdLine.addArgument("-i");
        cmdLine.addArgument("-"); // cmdLine.addArgument(wavFile.toString());
        cmdLine.addArgument("-ar");
        cmdLine.addArgument(String.valueOf(SAMPLE_RATE));
        cmdLine.addArgument("-ac");
        cmdLine.addArgument("1");
        cmdLine.addArgument("-f");
        cmdLine.addArgument("ogg");
        // without this you'll get FLAC instead, which browsers do not support
        cmdLine.addArgument("-acodec");
        cmdLine.addArgument("libvorbis");
        //                                cmdLine.addArgument("-y"); // happens, weird!
        //                                cmdLine.addArgument(oggFile.toString());
        cmdLine.addArgument("-");
        executor.setStreamHandler(new PumpStreamHandler(bos, err, wavIn));
        final int executed;
        try {
          executed = executor.execute(cmdLine);
        } finally {
          log.info("{}: {}", cmdLine, err.toString());
        }
        //                                Preconditions.checkState(oggFile.exists(), "Cannot convert
        // %s bytes WAV to OGG",
        //                                        wavBytes.length);

        // Send
        //                                final byte[] audioContent =
        // FileUtils.readFileToByteArray(oggFile);
        final byte[] audioContent = bos.toByteArray();
        final String audioContentType = "audio/ogg";

        final AudioObject audioObject = new AudioObject();
        audioObject.setTranscript(communicateAction.getObject());
        audioObject.setInLanguage(lang);
        audioObject.setMediaLayer(MediaLayer.SPEECH);
        audioObject.setContentType(audioContentType + "; rate=" + SAMPLE_RATE);
        audioObject.setContentUrl(
            "data:" + audioContentType + ";base64," + Base64.encodeBase64String(audioContent));
        audioObject.setContentSize((long) audioContent.length);
        //
        // audioObject.setName(FilenameUtils.getName(oggFile.getName()));
        audioObject.setName("lumen-speech-" + new DateTime() + ".ogg");
        audioObject.setDateCreated(new DateTime());
        audioObject.setDatePublished(audioObject.getDateCreated());
        audioObject.setDateModified(audioObject.getDateCreated());
        audioObject.setUploadDate(audioObject.getDateCreated());
        final String audioOutUri =
            "rabbitmq://dummy/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&skipQueueDeclare=true&routingKey="
                + AvatarChannel.AUDIO_OUT.key(avatarId);
        log.info("Sending {} to {} ...", audioObject, audioOutUri);
        producer.sendBodyAndHeader(
            audioOutUri,
            toJson.getMapper().writeValueAsBytes(audioObject),
            RabbitMQConstants.EXPIRATION,
            String.valueOf(MESSAGE_EXPIRATION.getMillis()));
      }
    } finally {
      //                            oggFile.delete();
      // wavFile.delete();
    }

    // reply
    log.trace("Exchange {} is {}", exchange.getIn().getMessageId(), exchange.getPattern());
    final Status status = new Status();
    exchange.getOut().setBody(status);
    return status;
    //                        final String replyTo = exchange.getIn().getHeader("rabbitmq.REPLY_TO",
    // String.class);
    //                        if (replyTo != null) {
    //                            log.debug("Sending reply to {} ...", replyTo);
    //                            exchange.getOut().setHeader("rabbitmq.ROUTING_KEY", replyTo);
    //                            exchange.getOut().setHeader("rabbitmq.EXCHANGE_NAME", "");
    //                            exchange.getOut().setHeader("recipients",
    //
    // "rabbitmq://dummy/dummy?connectionFactory=#amqpConnFactory&autoDelete=false,log:OUT." +
    // LumenChannel.SPEECH_SYNTHESIS);
    //                        } else {
    //                            exchange.getOut().setHeader("recipients");
    //                        }
  }
 protected byte[] performEspeak(CommunicateAction communicateAction, Locale lang)
     throws IOException {
   byte[] wavBytes;
   try (final ByteArrayInputStream objectIn =
           new ByteArrayInputStream(
               communicateAction.getObject().getBytes(StandardCharsets.UTF_8));
       final ByteArrayOutputStream wavStream = new ByteArrayOutputStream();
       final ByteArrayOutputStream err = new ByteArrayOutputStream()) {
     final CommandLine cmdLine = new CommandLine("espeak");
     cmdLine.addArgument("-b");
     cmdLine.addArgument("1"); // UTF-8
     cmdLine.addArgument("-m"); // SSML markup
     cmdLine.addArgument("-s");
     cmdLine.addArgument("130");
     if (INDONESIAN.getLanguage().equals(lang.getLanguage())) {
       cmdLine.addArgument("-v");
       cmdLine.addArgument(SpeechProsody.MBROLA_ID1_VOICE);
       cmdLine.addArgument("-a");
       cmdLine.addArgument(String.valueOf(INDONESIAN_AMPLITUDE));
     } else if ("ar".equals(lang.getLanguage())) {
       cmdLine.addArgument("-v");
       cmdLine.addArgument(SpeechProsody.MBROLA_AR1_VOICE);
     }
     //                                cmdLine.addArgument("-w");
     //                                cmdLine.addArgument(wavFile.toString());
     cmdLine.addArgument("--stdin");
     cmdLine.addArgument("--stdout");
     // cmdLine.addArgument(communicateAction.getObject());
     executor.setStreamHandler(new PumpStreamHandler(wavStream, err, objectIn));
     final int executed;
     try {
       executed = executor.execute(cmdLine);
       wavBytes = wavStream.toByteArray();
     } finally {
       log.info("{}: {}", cmdLine, err.toString());
     }
   }
   return wavBytes;
 }
  @Override
  public void execute() throws MojoExecutionException, MojoFailureException {

    try {
      File outputDir = getOutputDirectory().getCanonicalFile();
      if (!outputDir.exists()) {
        Files.createDirectories(outputDir.toPath());
      }
    } catch (IOException e) {
      throw new MojoFailureException(e.getMessage(), e);
    }

    CommandLine cl = new CommandLine("java");

    String cp = "";
    for (Object classpathElement : getClassPathElements()) {
      cp = cp + File.pathSeparator + classpathElement;
    }
    cp = cp + File.pathSeparator + getOutputDirectory().getAbsolutePath();

    cl.addArgument("-cp").addArgument(cp);

    cl.addArgument("frege.compiler.Main");
    cl.addArgument("-sp").addArgument(getSourcePath());

    // output dir
    cl.addArgument("-d").addArgument(getOutputDirectory().getAbsolutePath());

    if (hints) {
      cl.addArgument("-hints");
    }
    if (inline) {
      cl.addArgument("-inline");
    }
    if (make) {
      cl.addArgument("-make");
    }
    if (verbose) {
      cl.addArgument("-v");
    }
    if (skipCompile) {
      cl.addArgument("-j");
    }

    // source files
    final Set<File> sourceFiles = getSourceFiles();

    if (sourceFiles.isEmpty()) {
      getLog().info("No files to compile, skipping...");
    } else {

      for (File sourceFile : sourceFiles) {
        cl.addArgument(sourceFile.getAbsolutePath());
      }

      getLog().debug("Command line: " + cl.toString());

      Executor exec = new DefaultExecutor();
      Map<String, String> env = new HashMap<>(System.getenv());
      ExecuteStreamHandler handler = new PumpStreamHandler(System.out, System.err, System.in);
      exec.setStreamHandler(handler);

      int status;
      try {
        status = exec.execute(cl, env);
      } catch (ExecuteException e) {
        status = e.getExitValue();
      } catch (IOException e) {
        status = 1;
      }

      if (status != 0) {
        throw new MojoExecutionException("Frege compilation failed.");
      }
    }
  }
  /* package */ AndroidApp signTestServer(File customSelendroidServer, File outputFileName)
      throws ShellCommandException, AndroidSdkException {
    if (outputFileName == null) {
      throw new IllegalArgumentException("outputFileName parameter is null.");
    }
    File androidKeyStore = androidDebugKeystore();

    if (androidKeyStore.isFile() == false) {
      // create a new keystore
      CommandLine commandline = new CommandLine(JavaSdk.keytool());

      commandline.addArgument("-genkey", false);
      commandline.addArgument("-v", false);
      commandline.addArgument("-keystore", false);
      commandline.addArgument(androidKeyStore.toString(), false);
      commandline.addArgument("-storepass", false);
      commandline.addArgument("android", false);
      commandline.addArgument("-alias", false);
      commandline.addArgument("androiddebugkey", false);
      commandline.addArgument("-keypass", false);
      commandline.addArgument("android", false);
      commandline.addArgument("-dname", false);
      commandline.addArgument("CN=Android Debug,O=Android,C=US", false);
      commandline.addArgument("-storetype", false);
      commandline.addArgument("JKS", false);
      commandline.addArgument("-sigalg", false);
      commandline.addArgument("MD5withRSA", false);
      commandline.addArgument("-keyalg", false);
      commandline.addArgument("RSA", false);
      commandline.addArgument("-validity", false);
      commandline.addArgument("9999", false);

      String output = ShellCommand.exec(commandline, 20000);
      log.info("A new keystore has been created: " + output);
    }

    // Sign the jar
    CommandLine commandline = new CommandLine(JavaSdk.jarsigner());

    commandline.addArgument("-sigalg", false);
    commandline.addArgument("MD5withRSA", false);
    commandline.addArgument("-digestalg", false);
    commandline.addArgument("SHA1", false);
    commandline.addArgument("-signedjar", false);
    commandline.addArgument(outputFileName.getAbsolutePath(), false);
    commandline.addArgument("-storepass", false);
    commandline.addArgument("android", false);
    commandline.addArgument("-keystore", false);
    commandline.addArgument(androidKeyStore.toString(), false);
    commandline.addArgument(customSelendroidServer.getAbsolutePath(), false);
    commandline.addArgument("androiddebugkey", false);
    String output = ShellCommand.exec(commandline, 20000);
    if (log.isLoggable(Level.INFO)) {
      log.info("App signing output: " + output);
    }
    log.info("The app has been signed: " + outputFileName.getAbsolutePath());
    return new DefaultAndroidApp(outputFileName);
  }
  /* package */ File createAndAddCustomizedAndroidManifestToSelendroidServer()
      throws IOException, ShellCommandException, AndroidSdkException {
    String targetPackageName = applicationUnderTest.getBasePackage();
    File tempdir =
        new File(
            FileUtils.getTempDirectoryPath()
                + File.separatorChar
                + targetPackageName
                + System.currentTimeMillis());

    if (!tempdir.exists()) {
      tempdir.mkdirs();
    }

    File customizedManifest = new File(tempdir, "AndroidManifest.xml");
    log.info(
        "Adding target package '"
            + targetPackageName
            + "' to "
            + customizedManifest.getAbsolutePath());

    // add target package
    InputStream inputStream = getResourceAsStream(selendroidApplicationXmlTemplate);
    if (inputStream == null) {
      throw new SelendroidException("AndroidApplication.xml template file was not found.");
    }
    String content = IOUtils.toString(inputStream, Charset.defaultCharset().displayName());

    // find the first occurance of "package" and appending the targetpackagename to begining
    int i = content.toLowerCase().indexOf("package");
    int cnt = 0;
    for (; i < content.length(); i++) {
      if (content.charAt(i) == '\"') {
        cnt++;
      }
      if (cnt == 2) {
        break;
      }
    }
    content = content.substring(0, i) + "." + targetPackageName + content.substring(i);
    log.info("Final Manifest File:\n" + content);
    content = content.replaceAll(SELENDROID_TEST_APP_PACKAGE, targetPackageName);
    // Seems like this needs to be done
    if (content.contains(ICON)) {
      content = content.replaceAll(ICON, "");
    }

    OutputStream outputStream = new FileOutputStream(customizedManifest);
    IOUtils.write(content, outputStream, Charset.defaultCharset().displayName());
    IOUtils.closeQuietly(inputStream);
    IOUtils.closeQuietly(outputStream);

    // adding the xml to an empty apk
    CommandLine createManifestApk = new CommandLine(AndroidSdk.aapt());

    createManifestApk.addArgument("package", false);
    createManifestApk.addArgument("-M", false);
    createManifestApk.addArgument(customizedManifest.getAbsolutePath(), false);
    createManifestApk.addArgument("-I", false);
    createManifestApk.addArgument(AndroidSdk.androidJar(), false);
    createManifestApk.addArgument("-F", false);
    createManifestApk.addArgument(
        tempdir.getAbsolutePath() + File.separatorChar + "manifest.apk", false);
    createManifestApk.addArgument("-f", false);
    log.info(ShellCommand.exec(createManifestApk, 20000L));

    ZipFile manifestApk =
        new ZipFile(new File(tempdir.getAbsolutePath() + File.separatorChar + "manifest.apk"));
    ZipArchiveEntry binaryManifestXml = manifestApk.getEntry("AndroidManifest.xml");

    File finalSelendroidServerFile = new File(tempdir.getAbsolutePath() + "selendroid-server.apk");
    ZipArchiveOutputStream finalSelendroidServer =
        new ZipArchiveOutputStream(finalSelendroidServerFile);
    finalSelendroidServer.putArchiveEntry(binaryManifestXml);
    IOUtils.copy(manifestApk.getInputStream(binaryManifestXml), finalSelendroidServer);

    ZipFile selendroidPrebuildApk = new ZipFile(selendroidServer.getAbsolutePath());
    Enumeration<ZipArchiveEntry> entries = selendroidPrebuildApk.getEntries();
    for (; entries.hasMoreElements(); ) {
      ZipArchiveEntry dd = entries.nextElement();
      finalSelendroidServer.putArchiveEntry(dd);

      IOUtils.copy(selendroidPrebuildApk.getInputStream(dd), finalSelendroidServer);
    }

    finalSelendroidServer.closeArchiveEntry();
    finalSelendroidServer.close();
    manifestApk.close();
    log.info("file: " + finalSelendroidServerFile.getAbsolutePath());
    return finalSelendroidServerFile;
  }