/*
(non-Javadoc)

@see
org.duracloud.mill.util.DriverSupport#executeImpl(org.apache.commons.
cli.CommandLine)
506916
@Override
    protected void executeImpl(CommandLine cmd) {
        try {
            List<PropertyDefinition> defintions =
                new PropertyDefinitionListBuilder().addMillDb()
                                                   .build();
            PropertyVerifier verifier = new PropertyVerifier(defintions);
            verifier.verify(System.getProperties());
            ApplicationContext context =
                new AnnotationConfigApplicationContext("org.duracloud.mill.db",
                                                       "org.duracloud.mill.manifest.builder");
            log.info("context initialized");

            boolean dryRun = Boolean.valueOf(cmd.hasOption("d"));
            boolean clean = Boolean.valueOf(cmd.hasOption("C"));
            String host = cmd.getOptionValue("host");
            String port = cmd.getOptionValue("port", "443");
            String username = cmd.getOptionValue("u");
            String password = cmd.getOptionValue("p");
            List<String> spaceList = new LinkedList<>();
            if (cmd.hasOption("s")) {
                String spaces = cmd.getOptionValue("s", "");
                if (!StringUtils.isEmpty(spaces)) {
                    spaceList = Arrays.asList(spaces.split("[,]"));
                }
            }

            List<String> storeList = new LinkedList<>();

            if (cmd.hasOption("t")) {
                String stores = cmd.getOptionValue("t", "");
                if (!StringUtils.isEmpty(stores)) {
                    storeList = Arrays.asList(stores.split("[,]"));
                }
            }

            int threads = 0;
            if (cmd.hasOption("T")) {
                threads = Integer.parseInt(cmd.getOptionValue("T", "10"));
            }

            String account = host.split("[.]")[0];
            ContentStoreManager storeManager = new ContentStoreManagerImpl(host, port);
            storeManager.login(new Credential(username, password));
            Map<String, ContentStore> contentStoreMap = storeManager.getContentStores();
            List<ContentStore> contentStores = new LinkedList<>();
            for (String storeId : contentStoreMap.keySet()) {
                if (storeList.isEmpty() || storeList.contains(storeId)) {
                    ContentStore contentStore = contentStoreMap.get(storeId);
                    contentStores.add(contentStore);
                }
            }

            ManifestBuilder builder = (ManifestBuilder) context.getBean(ManifestBuilder.class);
            builder.init(account, contentStores, spaceList, clean, dryRun, threads);
            builder.execute();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            log.info("exiting...");
        }
    }
281519
public static void executeCommand(String[] args) throws Exception {
        String subCmd = (args.length > 0) ? args[0] : "";
        args = AdminToolUtils.copyArrayCutFirst(args);
        if(subCmd.equals("query-keys")) {
            SubCommandDebugQueryKeys.executeCommand(args);
        } else if(subCmd.equals("route")) {
            SubCommandDebugRoute.executeCommand(args);
        } else {
            printHelp(System.out);
        }
    }
1041321
@Override
    public Object executeWithArgs(ExecutionType executionType, Object[] args) throws CommandActionExecutionException {
        if(ExecutionType.ASYNCHRONOUS == executionType){
            Closure closure = AsyncClosureFactory.getInstance().createClosure(metaHolder, method, object, args);
            return executeClj(closure.getClosureObj(), closure.getClosureMethod());
        }

        return execute(object, method, args);
    }
40049
public void execute() {
    try {
      Command command = new Parser().parse();
      try {
        command.execute(new ContextImpl(), execute);
        close();
      } catch (Exception e) {
        throw new RuntimeException(
            "Error while executing command " + command, e);
      } catch (AssertionError e) {
        throw new RuntimeException(
            "Error while executing command " + command, e);
      }
    } finally {
      try {
        reader.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      writer.close();
      try {
        close();
      } catch (SQLException e) {
        // ignore
      }
    }
  }
364074
@Override
	public Response executeCommand( String app, String commandName ) {

		this.logger.fine("Request: execute command " + commandName + " in the " + app + " application.");
		String lang = lang( this.manager );
		Response response = Response.ok().build();
		try {
			Application application = this.manager.applicationMngr().findApplicationByName( app );
			if( application == null )
				response = handleError( Status.NOT_FOUND, new RestError( REST_INEXISTING, application( app )), lang ).build();
			else
				this.manager.commandsMngr().execute( application, commandName, CommandHistoryItem.ORIGIN_REST_API, null );

		} catch( NoSuchFileException e ) {
			response = RestServicesUtils.handleError(
					Status.NOT_FOUND,
					new RestError( ErrorCode.REST_INEXISTING, e, ErrorDetails.name( commandName )),
					lang ).build();

		} catch( CommandException e ) {
			response = RestServicesUtils.handleError(
					Status.CONFLICT,
					new RestError( ErrorCode.REST_APP_EXEC_ERROR, e, ErrorDetails.name( commandName )),
					lang ).build();

		} catch( Exception e ) {
			response = RestServicesUtils.handleError(
					Status.INTERNAL_SERVER_ERROR,
					new RestError( ErrorCode.REST_UNDETAILED_ERROR, e ),
					lang ).build();
		}

		return response;
	}
416366
private Object execute(Object o, Method m, Object... args) throws CommandActionExecutionException {
        Object result = null;
        try {
            m.setAccessible(true); // suppress Java language access
            if (isCompileWeaving() && metaHolder.getAjcMethod() != null) {
                result = invokeAjcMethod(metaHolder.getAjcMethod(), o, metaHolder, args);
            } else {
                result = m.invoke(o, args);
            }
        } catch (IllegalAccessException e) {
            propagateCause(e);
        } catch (InvocationTargetException e) {
            propagateCause(e);
        }
        return result;
    }
591192
@Override
    public void handle(CommandContext ctx, String commandLine) {
        String[] commands = commandLine.split(" ");
        if (commands.length != 1) {
            ctx.printLine("Invalid command.");
            return;
        }

        ctx.terminateSession();
    }
1324143
public void executeInBackground(AbstractWisdomMojo mojo) throws MojoExecutionException {
        File script = new File(mojo.getWisdomRootDirectory(), "chameleon.sh");
        if (!script.isFile()) {
            throw new MojoExecutionException("The 'chameleon.sh' file does not exist in " + mojo
                    .getWisdomRootDirectory().getAbsolutePath() + " - cannot launch Wisdom");
        }

        // Remove the RUNNING_PID file if exists.
        File pid = new File(mojo.getWisdomRootDirectory(), "RUNNING_PID");
        if (pid.isFile()) {
            mojo.getLog().info("The RUNNING_PID file is present, deleting it");
            FileUtils.deleteQuietly(pid);
        }

        // We create a command line, as we are using th toString method on it.
        CommandLine cmdLine = new CommandLine(script);
        appendSystemPropertiesToCommandLine(mojo, cmdLine);

        try {
            mojo.getLog().info("Launching Wisdom Server using '" + cmdLine.toString() + "'.");
            // As we know which command line we are executing, we can safely execute the command.
            Runtime.getRuntime().exec(cmdLine.toStrings(), null, mojo.getWisdomRootDirectory()); //NOSONAR see comment
        } catch (IOException e) {
            throw new MojoExecutionException("Cannot execute Wisdom", e);
        }
    }
521998
@Override
    public void execute()
            throws MojoExecutionException, MojoFailureException
        {
        boolean fExplicit = this.script != null;
        String  script    = fExplicit
                            ? this.script
                            : execution.getLifecyclePhase();

        String SCRIPT_NOT_FOUND = "Script '" + script + "' is not defined in package.json";

        Package pkg = getPackage();
        if (fExplicit && !pkg.hasScript(script))
            {
            getLog().error(SCRIPT_NOT_FOUND);
            throw new MojoFailureException(SCRIPT_NOT_FOUND);
            }
        else if (pkg.hasScript(script))
            {
            if (!fExplicit && script.endsWith("test") && skipTests)
                {
                getLog().info("Tests are skipped.");
                }
            else
                {
                CommandLine cmdLine = getNpmCommand();
                addCommand(cmdLine);
                cmdLine.addArgument(script);
                addArguments(cmdLine);

                execute(cmdLine);
                }
            }
        else
            {
            getLog().info(SCRIPT_NOT_FOUND);
            }
        }
354058
public void execute ()
        throws MojoExecutionException
    {
        if (mapFile == null) mapFile = new File(base, "compmap.txt");
        if (actionDef == null) actionDef = new File(base, "actions.xml");

        ComponentBundler bundler = new ComponentBundler(mapFile, actionDef) {
            @Override protected boolean keepRawPngs () { return keepRawPngs; }
            @Override protected boolean uncompressed () { return false; }
            @Override protected void logInfo (String message) { getLog().info(message); }
            @Override protected void logWarn (String message) { getLog().warn(message); }
        };

        if (bundleDirectories == null) {
            bundleDirectories = findBundleDirs();
        }
        for (BundleDirectory bdir : bundleDirectories) {
            getLog().info("Processing " + bdir);
            File root = new File(base, bdir.root);

            // create the scanner
            DirectoryScanner scanner = new DirectoryScanner();
            scanner.setBasedir(new File(root, bdir.path));
            scanner.setIncludes(includes.toArray(new String[0]));
            scanner.setExcludes(excludes.toArray(new String[0]));
            scanner.scan();

            File targetDir = new File(targetBase, bdir.root);
            File target = new File(new File(targetDir, bdir.path), "components.jar");
            List<Tuple<File,List<String>>> sourceDirs = Lists.newArrayList();
            sourceDirs.add(Tuple.newTuple(scanner.getBasedir(),
                                          Arrays.asList(scanner.getIncludedFiles())));
            bundler.execute(root.getPath(), target, sourceDirs);
        }
    }
434380
public static void main(final String[] args) {

    try {

      final Configuration commandLineConf = parseCommandLine(args);
      final Injector injector = Tang.Factory.getTang().newInjector(commandLineConf);

      final boolean isLocal = injector.getNamedInstance(Local.class);
      final int numEvaluators = injector.getNamedInstance(NumEvaluators.class);
      final int numTasks = injector.getNamedInstance(NumTasks.class);
      final int delay = injector.getNamedInstance(Delay.class);
      final int jobNum = injector.getNamedInstance(JobId.class);

      final String jobId = String.format("pool.e_%d.a_%d.d_%d.%d",
          numEvaluators, numTasks, delay, jobNum < 0 ? System.currentTimeMillis() : jobNum);

      // Timeout: delay + 6 extra seconds per Task per Evaluator + 2 minutes to allocate each Evaluator:
      final int timeout = numTasks * (delay + 6) * 1000 / numEvaluators + numEvaluators * 120000;

      final Configuration runtimeConfig = getClientConfiguration(commandLineConf, isLocal);
      LOG.log(Level.INFO, "TIME: Start Client {0} with timeout {1} sec. Configuration:\n--\n{2}--",
          new Object[] {jobId, timeout / 1000, Configurations.toString(runtimeConfig, true)});

      final Configuration driverConfig = DriverConfiguration.CONF
          .set(DriverConfiguration.GLOBAL_LIBRARIES, EnvironmentUtils.getClassLocation(JobDriver.class))
          .set(DriverConfiguration.DRIVER_IDENTIFIER, jobId)
          .set(DriverConfiguration.ON_DRIVER_STARTED, JobDriver.StartHandler.class)
          .set(DriverConfiguration.ON_DRIVER_STOP, JobDriver.StopHandler.class)
          .set(DriverConfiguration.ON_EVALUATOR_ALLOCATED, JobDriver.AllocatedEvaluatorHandler.class)
          .set(DriverConfiguration.ON_CONTEXT_ACTIVE, JobDriver.ActiveContextHandler.class)
          .set(DriverConfiguration.ON_TASK_RUNNING, JobDriver.RunningTaskHandler.class)
          .set(DriverConfiguration.ON_TASK_COMPLETED, JobDriver.CompletedTaskHandler.class)
          .set(DriverConfiguration.ON_EVALUATOR_COMPLETED, JobDriver.CompletedEvaluatorHandler.class)
          .build();

      final Configuration submittedConfiguration = Tang.Factory.getTang()
          .newConfigurationBuilder(driverConfig, commandLineConf).build();

      DriverLauncher.getLauncher(runtimeConfig).run(submittedConfiguration, timeout);

      LOG.log(Level.INFO, "TIME: Stop Client {0}", jobId);

    } catch (final BindException | InjectionException | IOException ex) {
      LOG.log(Level.SEVERE, "Job configuration error", ex);
    }
  }
101706
@Override
    protected void executeImpl(CommandLine cmd) {

        String taskQueueNames = cmd.getOptionValue(TASK_QUEUES_OPTION);
        if (taskQueueNames != null) {
            setSystemProperty(ConfigConstants.QUEUE_TASK_ORDERED, taskQueueNames);
        }

        List<PropertyDefinition> defintions =
            new PropertyDefinitionListBuilder().addAws()
                                               .addMillDb()
                                               .addMcDb()
                                               .addDeadLetterQueue()
                                               .addAuditQueue()
                                               .addBitIntegrityQueue()
                                               .addBitIntegrityErrorQueue()
                                               .addBitIntegrityReportQueue()
                                               .addNotifications()
                                               .addWorkDir()
                                               .addTaskQueueOrder()
                                               .addDuplicationPolicyBucketSuffix()
                                               .addDuplicationPolicyRefreshFrequency()
                                               .addDuplicationHighPriorityQueue()
                                               .addLocalDuplicationDir()
                                               .addMaxWorkers()
                                               .build();
        PropertyVerifier verifier = new PropertyVerifier(defintions);
        verifier.verify(System.getProperties());

        TaskProducerConfigurationManager config = new WorkmanConfigurationManager();

        String workDirPath = config.getWorkDirectoryPath();

        if (workDirPath == null || workDirPath.trim() == "") {
            // this should never happen since workDirPath is required,
            // but I'll leave this in here as a sanity check.
            workDirPath = System.getProperty("java.io.tmpdir") + File.separator + "workman-work";
        }

        initializeWorkDir(workDirPath);

        String localDuplicationPolicyDirPath = config.getDuplicationPolicyDir();

        if (localDuplicationPolicyDirPath != null && !new File(localDuplicationPolicyDirPath).exists()) {
            System.err.print("The local duplication policy directory "
                             + "path you specified, "
                             + localDuplicationPolicyDirPath + " does not exist: ");
            die();
        }

        ApplicationContext context = new AnnotationConfigApplicationContext("org.duracloud.mill");
    }
1228645
@SuppressWarnings("unchecked")
        public static void executeCommand(String[] args) throws IOException {

            OptionParser parser = getParser();

            // declare parameters
            List<String> metaKeys = null;
            String url = null;
            List<Integer> nodeIds = null;
            Boolean allNodes = true;
            List<String> storeNames = null;

            // parse command-line input
            args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_GET_RO);
            OptionSet options = parser.parse(args);
            if(options.has(AdminParserUtils.OPT_HELP)) {
                printHelp(System.out);
                return;
            }

            // check required options and/or conflicting options
            AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET_RO);
            AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);
            AdminParserUtils.checkOptional(options,
                                           AdminParserUtils.OPT_NODE,
                                           AdminParserUtils.OPT_ALL_NODES);
            AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_STORE);

            // load parameters
            metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET_RO);
            url = (String) options.valueOf(AdminParserUtils.OPT_URL);
            if(options.has(AdminParserUtils.OPT_NODE)) {
                nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);
                allNodes = false;
            }
            storeNames = (List<String>) options.valuesOf(AdminParserUtils.OPT_STORE);

            // execute command
            AdminClient adminClient = AdminToolUtils.getAdminClient(url);

            if(allNodes) {
                nodeIds = AdminToolUtils.getAllNodeIds(adminClient);
            }

            if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {
                metaKeys = Lists.newArrayList();
                metaKeys.add(KEY_MAX_VERSION);
                metaKeys.add(KEY_CURRENT_VERSION);
                metaKeys.add(KEY_STORAGE_FORMAT);
            }

            doMetaGetRO(adminClient, nodeIds, storeNames, metaKeys);
        }
622412
public <R> R executeAndQuery(ContextCommand<ROOT, R> cmd) {
        return Politician.beatAroundTheBush(() -> this.prevayler.execute(new InternalTransaction<>(cmd)));
    }
10040
@Override
    public final void execute() throws TaskExecutionFailedException {
        long startTime = System.currentTimeMillis();

        try {
            executeImpl();
            log.info(createMessage("success", System.currentTimeMillis() - startTime));
        } catch (TaskExecutionFailedException ex) {
            log.error(createMessage("failure", System.currentTimeMillis() - startTime));
            throw ex;
        }
    }
1295701
public static void runShellCommand(String[] cmd,
                                     StringBuilder outputLines,
                                     StringBuilder errorLines)
    throws IOException {
    Process p = Runtime.getRuntime().exec(cmd);
    if (outputLines != null) {
      BufferedReader in =
        new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        outputLines.append(line);
      }
    }
    if (errorLines != null) {
      BufferedReader err =
        new BufferedReader(new InputStreamReader(p.getErrorStream()));
      String line;
      while ((line = err.readLine()) != null) {
        errorLines.append(line);
      }
    }
  }
406463
@Override
    protected void executeImpl() throws TaskExecutionFailedException {

        try {
            String account = task.getAccount();
            String storeId = task.getStoreId();
            String spaceId = task.getSpaceId();
            String contentId = task.getContentId();
            String action = task.getAction();
            Map<String, String> props = task.getContentProperties();
            String acls = task.getSpaceACLs();
            Date timestamp = new Date(Long.valueOf(task.getDateTime()));

            auditLogStore.write(account,
                                storeId,
                                spaceId,
                                contentId,
                                task.getContentChecksum(),
                                task.getContentMimetype(),
                                task.getContentSize(),
                                task.getUserId(),
                                action,
                                props != null ? AuditLogStoreUtil.serialize(props) : null,
                                acls,
                                task.getSourceSpaceId(),
                                task.getSourceContentId(),
                                timestamp);

            log.debug("audit task successfully processed: {}", task);
        } catch (TransactionSystemException e) {
            log.error("failed to write item  ( account={} storeId={} spaceId={} contentId={} timestamp={} ) " +
                      "to the database due to a transactional error. Likely cause: duplicate entry. Details: {}. " +
                      "Ignoring...",
                      task.getAccount(),
                      task.getStoreId(),
                      task.getSpaceId(),
                      task.getContentId(),
                      new Date(Long.valueOf(task.getDateTime())),
                      e.getMessage());
        } catch (Exception e) {
            String message = "Failed to execute " + task + ": " + e.getMessage();
            log.debug(message, e);
            throw new TaskExecutionFailedException(message, e);
        }
    }