Executes a SPARQL HTTP protocol request for the given command, and returns the response.
@param command The SPARQL protocol command.
@return The HTTP response.
16336
static HttpResponse executeRequest(ProtocolCommand command, String mimeType) {
    HttpClient client = ((ProtocolConnection)command.getConnection()).getHttpClient();
    URL url = ((ProtocolDataSource)command.getConnection().getDataSource()).getUrl();
    HttpUriRequest req;

    try {
      String params = "query=" + encode(command.getCommand());
      String u = url.toString() + "?" + params;
      if (u.length() > QUERY_LIMIT) {
        // POST connection
        try {
          req = new HttpPost(url.toURI());
        } catch (URISyntaxException e) {
          throw new SparqlException("Endpoint <" + url + "> not in an acceptable format", e);
        }
        ((HttpPost) req).setEntity((HttpEntity) new StringEntity(params));
      } else {
        // GET connection
        req = new HttpGet(u);
      }

      if (command.getTimeout() != Command.NO_TIMEOUT) {
        HttpParams reqParams = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(reqParams, (int) (command.getTimeout() * 1000));
        req.setParams(reqParams);
      }
      
      // Add Accept and Content-Type (for POST'ed queries) headers to the request.
      addHeaders(req, mimeType);
      
      // There's a small chance the request could be aborted before it's even executed, we'll have to live with that.
      command.setRequest(req);
      
      //dump(client, req);
      HttpResponse response = client.execute(req);
      StatusLine status = response.getStatusLine();
      int code = status.getStatusCode();
      
      // TODO the client doesn't handle redirects for posts; should we do that here?

      if (code >= SUCCESS_MIN && code <= SUCCESS_MAX) {
        return response;
      } else {
        throw new SparqlException("Unexpected status code in server response: " +
            status.getReasonPhrase() + "(" + code + ")");
      }
    } catch (UnsupportedEncodingException e) {
      throw new SparqlException("Unabled to encode data", e);
    } catch (ClientProtocolException cpe) {
      throw new SparqlException("Error in protocol", cpe);
    } catch (IOException e) {
      throw new SparqlException(e);
    }
  }
168189
public static List<String> cmd(String[] command) throws IOException, InterruptedException {
        return cmd(command, null, null, 300000L, null);
    }
957999
public void process(final T command) {
        boolean traceStarted = false;
        incrementCommandsProcessed();
		DehydratedExecutionContext ctx = null;
		try {
            validateCommand(command);
			CommandResolver<T> resolver = createCommandResolver(command, tracer);
			ctx = resolver.resolveExecutionContext();
            List<ExecutionCommand> executionCommands = resolver.resolveExecutionCommands();
            if (executionCommands.size() > 1) {
                throw new CougarFrameworkException("Resolved >1 command in a non-batch call!");
            }
            ExecutionCommand exec = executionCommands.get(0);
            tracer.start(ctx.getRequestUUID(), exec.getOperationKey());
            traceStarted = true;
			executeCommand(exec, ctx);
		} catch(CougarException ce) {
            executeError(command, ctx, ce, traceStarted);
		} catch (Exception e) {
            executeError(command, ctx, new CougarFrameworkException("Unexpected exception while processing transport command", e), traceStarted);
		}
	}
144948
private void executePutOperation(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ClassNotFoundException {
        if (request.getContentLength() > 0) {
            ObjectInputStream input = new ObjectInputStream(new BufferedInputStream(request.getInputStream()));
            CommandPayload payload = (CommandPayload) input.readObject();
            Command operation = payload.getCommand();
            Manager manager = (Manager) request.getAttribute(ARQUILLIAN_MANAGER_ATTRIBUTE);
            // execute remote Event
            try {
                manager.fire(new ActivateManager(manager));
                manager.inject(operation);
                operation.perform();
                manager.fire(new PassivateManager(manager));
            } catch (Throwable e) {
                payload.setThrowable(e);
            }
            response.setStatus(HttpServletResponse.SC_OK);
            ObjectOutputStream output = new ObjectOutputStream(response.getOutputStream());
            output.writeObject(payload);
            output.flush();
            output.close();
        } else {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    }
611880
private void exec(File command,
                      String pathInfo,
                      HttpServletRequest req,
                      HttpServletResponse res)
        throws IOException
    {
        String path=command.toString();
        File dir=command.getParentFile();
        if(log.isDebugEnabled())log.debug("CGI: execing: "+path);

	EnvList env = new EnvList(_env);

	// these ones are from "The WWW Common Gateway Interface Version 1.1"
	// look at : http://Web.Golux.Com/coar/cgi/draft-coar-cgi-v11-03-clean.html#6.1.1
	env.set("AUTH_TYPE", req.getAuthType());
	env.set("CONTENT_LENGTH", Integer.toString(req.getContentLength()));
	env.set("CONTENT_TYPE", req.getContentType());
	env.set("GATEWAY_INTERFACE", "CGI/1.1");
	env.set("PATH_INFO", pathInfo);
	env.set("PATH_TRANSLATED", req.getPathTranslated());
	env.set("QUERY_STRING", req.getQueryString());
	env.set("REMOTE_ADDR", req.getRemoteAddr());
	env.set("REMOTE_HOST", req.getRemoteHost());
	// The identity information reported about the connection by a
	// RFC 1413 [11] request to the remote agent, if
	// available. Servers MAY choose not to support this feature, or
	// not to request the data for efficiency reasons.
	// "REMOTE_IDENT" => "NYI"
	env.set("REMOTE_USER", req.getRemoteUser());
	env.set("REQUEST_METHOD", req.getMethod());
    String scriptName = req.getRequestURI().substring(0,req.getRequestURI().length() - pathInfo.length());
	env.set("SCRIPT_NAME",scriptName);
    env.set("SCRIPT_FILENAME",getServletContext().getRealPath(scriptName));
    env.set("SERVER_NAME", req.getServerName());
	env.set("SERVER_PORT", Integer.toString(req.getServerPort()));
	env.set("SERVER_PROTOCOL", req.getProtocol());
        env.set("SERVER_SOFTWARE", getServletContext().getServerInfo());
	Enumeration enm = req.getHeaderNames();
	while (enm.hasMoreElements())
	{
	    String name = (String) enm.nextElement();
	    String value = req.getHeader(name);
	    env.set("HTTP_" + name.toUpperCase().replace( '-', '_' ), value);
	}

	// these extra ones were from printenv on www.dev.nomura.co.uk
	env.set("HTTPS", (req.isSecure()?"ON":"OFF"));
	// "DOCUMENT_ROOT" => root + "/docs",
	// "SERVER_URL" => "NYI - http://us0245",
	// "TZ" => System.getProperty("user.timezone"),

        // are we meant to decode args here ? or does the script get them
        // via PATH_INFO ?  if we are, they should be decoded and passed
        // into exec here...

        String execCmd=path;
        if (execCmd.indexOf(" ")>=0)
            execCmd="\""+execCmd+"\"";
        if (_cmdPrefix!=null)
            execCmd=_cmdPrefix+" "+execCmd;

        Process p=dir==null
            ?Runtime.getRuntime().exec(execCmd, env.getEnvArray())
            :Runtime.getRuntime().exec(execCmd, env.getEnvArray(),dir);

        // hook processes input to browser's output (async)
        final InputStream inFromReq=req.getInputStream();
        final OutputStream outToCgi=p.getOutputStream();
        final int inputLength = req.getContentLength();

        new Thread(new Runnable()
            {
                public void run()
                {
                    try{
                        if (inputLength>0)
                            IO.copy(inFromReq,outToCgi,inputLength);
                        outToCgi.close();
                    }
                    catch(IOException e){LogSupport.ignore(log,e);}
                }
            }).start();


        // hook processes output to browser's input (sync)
        // if browser closes stream, we should detect it and kill process...
        try
        {
            // read any headers off the top of our input stream
            LineInput li = new LineInput(p.getInputStream());
            HttpFields fields=new HttpFields();
            fields.read(li);

            String ContentStatus = "Status";
            String redirect = fields.get(HttpFields.__Location);
            String status   = fields.get(ContentStatus);

            if (status!=null)
            {
                log.debug("Found a Status header - setting status on response");
                fields.remove(ContentStatus);

                // NOTE: we ignore any reason phrase, otherwise we
                // would need to use res.sendError() selectively.
                int i = status.indexOf(' ');
                if (i>0)
                    status = status.substring(0,i);

                res.setStatus(Integer.parseInt(status));
            }

            // copy remaining headers into response...
	    for (Iterator i=fields.iterator(); i.hasNext();)
            {
                HttpFields.Entry e=(HttpFields.Entry)i.next();
                res.addHeader(e.getKey(),e.getValue());
            }

            if (status==null && redirect != null)
            {
                // The CGI has set Location and is counting on us to do the redirect.
                // See http://CGI-Spec.Golux.Com/draft-coar-cgi-v11-03-clean.html#7.2.1.2
                if (!redirect.startsWith("http:/")&&!redirect.startsWith("https:/"))
                    res.sendRedirect(redirect);
                else
                    res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            }

            // copy remains of input onto output...
            IO.copy(li, res.getOutputStream());

	    p.waitFor();
	    int exitValue = p.exitValue();
	    if(log.isDebugEnabled())log.debug("CGI: p.exitValue(): " + exitValue);
	    if (0 != exitValue)
	    {
		log.warn("Non-zero exit status ("+exitValue+
			     ") from CGI program: "+path);
		if (!res.isCommitted())
		    res.sendError(500, "Failed to exec CGI");
	    }
        }
        catch (IOException e)
        {
            // browser has probably closed its input stream - we
            // terminate and clean up...
            log.debug("CGI: Client closed connection!");
        }
	catch (InterruptedException ie)
        {
            log.debug("CGI: interrupted!");
        }
	finally
	{
            p.destroy();
	}

	if(log.isDebugEnabled())log.debug("CGI: Finished exec: " + p);
    }
307016
public static KubernetesMessage response(String command, KubernetesClientException error) {
        return response(command, error.getMessage());
    }
820248
public static PowerShellResponse executeSingleCommand(String command) {
        PowerShellResponse response = null;

        try (PowerShell session = PowerShell.openSession()) {
            response = session.executeCommand(command);
        } catch (PowerShellNotAvailableException ex) {
            logger.log(Level.SEVERE, "PowerShell not available", ex);
        }

        return response;
    }
247748
static void handleCommand(
      String command, HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("application/json");
    boolean isPost = "POST".equals(request.getMethod());
    JSONObject retValue = null;
    try {
      if (command.equals(LIST_JOBS_PATH) && !isPost) {
        retValue = handleListJobs(request);
      } else if (command.equals(CLEANUP_JOB_PATH) && isPost) {
        retValue = handleCleanupJob(request.getParameter("mapreduce_id"));
      } else if (command.equals(ABORT_JOB_PATH) && isPost) {
        retValue = handleAbortJob(request.getParameter("mapreduce_id"));
      } else if (command.equals(GET_JOB_DETAIL_PATH) && !isPost) {
        retValue = handleGetJobDetail(request.getParameter("mapreduce_id"));
      }
    } catch (Exception t) {
      log.log(Level.SEVERE, "Got exception while running command", t);
      try {
        retValue = new JSONObject();
        retValue.put("error_class", t.getClass().getName());
        retValue.put("error_message",
            "Full stack trace is available in the server logs. Message: "
                + t.getMessage());
      } catch (JSONException e) {
        throw new RuntimeException("Couldn't create error JSON object", e);
      }
    }
    try {
      if (retValue == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
      } else {
        retValue.write(response.getWriter());
        response.getWriter().flush();
      }
    } catch (JSONException | IOException e) {
      throw new RuntimeException("Couldn't write command response", e);
    }
  }
762286
public List<ModelServiceInstance> queryService(List<StringCommand> commands){

        ProtocolHeader header = new ProtocolHeader();
        header.setType(ProtocolType.QueryService);

        List<QueryCommand> cs = new ArrayList<QueryCommand>();
        for(StringCommand c : commands){
            cs.add(c.getStringCommand());
        }

        QueryServiceProtocol p = new QueryServiceProtocol(cs);
        QueryServiceResponse resp ;
        resp = (QueryServiceResponse) connection.submitRequest(header, p,  null);
        return resp.getInstances();
    }
334591
public PowerShellResponse executeCommand(String command) {
        String commandOutput = "";
        boolean isError = false;
        boolean timeout = false;

        checkState();

        PowerShellCommandProcessor commandProcessor = new PowerShellCommandProcessor("standard", p.getInputStream(),
                this.waitPause, this.scriptMode);
        Future<String> result = threadpool.submit(commandProcessor);

        // Launch command
        commandWriter.println(command);

        try {
            if (!result.isDone()) {
                try {
                    commandOutput = result.get(maxWait, TimeUnit.MILLISECONDS);
                } catch (TimeoutException timeoutEx) {
                    timeout = true;
                    isError = true;
                    //Interrupt command after timeout
                    result.cancel(true);
                }
            }
        } catch (InterruptedException | ExecutionException ex) {
            logger.log(Level.SEVERE,
                    "Unexpected error when processing PowerShell command", ex);
            isError = true;
        } finally {
            // issue #2. Close and cancel processors/threads - Thanks to r4lly
            // for helping me here
            commandProcessor.close();
        }

        return new PowerShellResponse(isError, commandOutput, timeout);
    }
1194124
@Override
    public synchronized String executeCommand(String command) throws SshException {
        if (!isConnected()) {
            throw new IllegalStateException("Not connected!");
        }

        Channel channel = null;
        try {
            logger.debug("Opening channel");
            channel = connectSession.openChannel(CMD_EXEC);
            ((ChannelExec)channel).setCommand(command);

            ByteArrayOutputStream errOut = new ByteArrayOutputStream();
            channel.setExtOutputStream(errOut);

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
            logger.debug("connecting channel.");
            channel.connect();

            // Seems like Gerrit does not like when you disconnect directly after the command has been sent.
            // For instance, we have seen effects of mails not being sent out. This is the reason for
            // receiving all the incoming data.
            String incomingLine = null;
            StringBuilder commandOutput = new StringBuilder();
            while ((incomingLine = bufferedReader.readLine()) != null) {
                commandOutput.append(incomingLine);
                commandOutput.append('\n');
                logger.trace("Incoming line: {}", incomingLine);
            }
            logger.trace("Closing reader.");
            bufferedReader.close();

            // Exit code is only available if channel is closed, so wait a bit for it.
            // Channel.disconnect(), however, must not have been called yet.
            // See http://stackoverflow.com/questions/3154940/jsch-error-return-codes-not-consistent.
            waitForChannelClosure(channel, CLOSURE_WAIT_TIMEOUT);
            int exitCode = channel.getExitStatus();
            if (exitCode > 0) {
               String error = errOut.toString();
               if (error != null && error.trim().length() > 0) {
                   throw new SshException(error.trim() + " (" + String.valueOf(exitCode) + ")");
               } else {
                   throw new SshException(String.valueOf(exitCode));
               }
            }

            return commandOutput.toString();
        } catch (SshException ex) {
            throw ex;
        } catch (JSchException ex) {
            throw new SshException(ex);
        } catch (IOException ex) {
            throw new SshException(ex);
        } finally {
            if (channel != null) {
                logger.trace("disconnecting channel.");
                channel.disconnect();
            }
        }
    }
609946
public static KubernetesMessage response(String command, KubernetesResource<?> result) {
        KubernetesResponse response = new KubernetesResponse();
        response.setCommand(command);
        response.setResult(result);

        return new KubernetesMessage(response);
    }
777388
public static void exec_command(String command) throws IOException {
        launchProcess(command, new HashMap<String, String>(), false);
    }
975273
@Override
    public String sendCommand2(String command) throws IOException {
        String str = null;
        SshConnection ssh = null;
        try {
            ssh = SshConnectionFactory.getConnection(config.getGerritHostName(),
                    config.getGerritSshPort(), config.getGerritProxy(), config.getGerritAuthentication());
            str = ssh.executeCommand(command);
        } catch (Exception ex) {
            throw new IOException("Error during sending command", ex);
        } finally {
            if (ssh != null) {
                ssh.disconnect();
            }
        }
        return str;
    }
1308457
@Override
    public <R> R executeAndQuery(Command<ROOT, R> cmd) {
        return this.executeAndQuery((ContextCommand<ROOT, R>) cmd);
    }
93649
protected Serializable executeCommand(String command, Serializable[] arguments) throws Throwable
   {
      Socket socket = null;
      try
      {
         socket = new Socket(host, port);

         ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
         
         oos.writeUTF(command);
         
         if (arguments != null)
         {
            oos.writeInt(arguments.length);
            for (Serializable argument : arguments)
            {
               oos.writeObject(argument);
            }
         }
         else
         {
            oos.writeInt(0);
         }
         
         oos.flush();

         ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
         
         return (Serializable)ois.readObject();
      }
      catch (EOFException ee)
      {
         // Nothing
      }
      finally
      {
         try
         {
            if (socket != null)
               socket.close();
         }
         catch (IOException ignore)
         {
            // Ignore
         }
      }

      return null;
   }
1282691
def _simple_command(self, command, arg=None, **kwargs):
    """"""
    self._protocol.send_command(command, arg)
    return self._protocol.handle_simple_responses(**kwargs)