Create new instance of command executor.

@param commandPacketType command packet type for PostgreSQL
@param commandPacket command packet for PostgreSQL
@param backendConnection backend connection
@return command executor
777590
public static CommandExecutor newInstance(final PostgreSQLCommandPacketType commandPacketType, final PostgreSQLCommandPacket commandPacket, final BackendConnection backendConnection) {
        log.debug("Execute packet type: {}, value: {}", commandPacketType, commandPacket);
        switch (commandPacketType) {
            case QUERY:
                return new PostgreSQLComQueryExecutor((PostgreSQLComQueryPacket) commandPacket, backendConnection);
            case PARSE:
                return new PostgreSQLComParseExecutor((PostgreSQLComParsePacket) commandPacket, backendConnection);
            case BIND:
                return new PostgreSQLComBindExecutor((PostgreSQLComBindPacket) commandPacket, backendConnection);
            case DESCRIBE:
                return new PostgreSQLComDescribeExecutor();
            case EXECUTE:
                return new PostgreSQLComExecuteExecutor();
            case SYNC:
                return new PostgreSQLComSyncExecutor();
            case TERMINATE:
                return new PostgreSQLComTerminationExecutor();
            default:
                return new PostgreSQLUnsupportedCommandExecutor();
        }
    }
335968
public final static PipeConnectionEvent build(AbstractPipe source, EventType type, IProvider provider, Map<String, Object> paramMap) {
        return new PipeConnectionEvent(source, type, provider, paramMap);
    }
109920
@NotNull
    protected <A, R> Optional<R> restExceptionBarrier(
            Command<A, R> command,
            Mode mode,
            @Nullable A param
    ) {
        try {
            return executor.execute(command, mode, param);
        } catch (Exception | AssertionError e) {
            if (e instanceof ServiceException) {
                throw (ServiceException)e;
//            if (e instanceof WebApplicationException) {
//                throw (WebApplicationException)e;
            } else {
                //should never arrive here. nothing we can do.
                String msg = "Unexpected late exception translation for: "+e.getMessage();
                logger.error(msg);
                throw InternalServerErrorServiceExceptions.internalServerError(msg);
            }
        }
    }
1263929
public final Command createStatsCachedumpCommand(InetSocketAddress server, CountDownLatch latch,
      int slabId, int limit) {
    return new TextStatsCachedumpCommand(server, latch, slabId, limit);
  }
331513
public CompletableFuture<CommandResponse> command(CommandRequest request) {
    CompletableFuture<CommandResponse> future = new CompletableFuture<>();
    if (context.isCurrentContext()) {
      sendRequest(request, protocol::command, future);
    } else {
      context.execute(() -> sendRequest(request, protocol::command, future));
    }
    return future;
  }
384219
public static MySQLCommandPacketType getCommandPacketType(final MySQLPacketPayload payload) {
        Preconditions.checkArgument(0 == payload.readInt1(), "Sequence ID of MySQL command packet must be `0`.");
        return MySQLCommandPacketType.valueOf(payload.readInt1());
    }
1146063
public <R> R executeTransactionalCommand(final TransactionalCommand<R> command, final TransactionStyle style)
            throws MithraBusinessException
    {
        String commandName = command.getClass().getName();
        MithraTransaction tx = this.getCurrentTransaction();
        if (tx != null)
        {
            try
            {
                return command.executeTransaction(tx);
            }
            catch(RuntimeException e)
            {
                throw e;
            }
            catch (Throwable throwable)
            {
                getLogger().error(commandName+" rolled back tx, will not retry.", throwable);
                tx.expectRollbackWithCause(throwable);
                throw new MithraBusinessException(commandName+" transaction failed", throwable);
            }
        }
        R result = null;
        int retryCount = style.getRetries() + 1;
        do
        {
            try
            {
                tx = this.startOrContinueTransaction(style);
                tx.setTransactionName("Transactional Command: "+commandName);
                result = command.executeTransaction(tx);

                tx.commit();
                retryCount = 0;
            }
            catch (Throwable throwable)
            {
                retryCount = MithraTransaction.handleTransactionException(tx, throwable, retryCount, style);
            }
        }
        while(retryCount > 0);
        return result;
    }
781505
function UnknownPacket(cmd, data) {
  if (!(this instanceof UnknownPacket))
    return new UnknownPacket(cmd, data);

  Packet.call(this);

  this.cmd = cmd;
  this.data = data;
}
964006
private void invokeCommand(CommandRequest request, CompletableFuture<byte[]> future) {
    invoke(new CommandAttempt(sequencer.nextRequest(), request, future));
  }
1119775
public static ProcessOutput executeProcess(ConfigurationHolder configurationHolder,String command)
    {
        //get process executer class name
        String className=configurationHolder.getConfigurationValue(ProcessExecutor.PROCESS_EXECUTER_CLASS_NAME_PROPERTY_KEY);
        if(className==null)
        {
            className=DefaultProcessExecutor.class.getName();
        }
        
        //get process executer from cache
        ProcessExecutor processExecutor=ProcessExecutorHelper.PROCESS_EXECUTERS.get(className);
        if(processExecutor==null)
        {
            //create new process executer (no need to synchronize as it won't impact anything if we create more
            //than 1 process executer of same type)
            processExecutor=(ProcessExecutor)ReflectionHelper.createInstance(className);
            
            //put in cache
            ProcessExecutorHelper.PROCESS_EXECUTERS.put(className,processExecutor);
        }

        ProcessOutput processOutput=null;
        try
        {
            //execute process
            processOutput=processExecutor.executeProcess(configurationHolder,command);
        }
        catch(RuntimeException exception)
        {
            throw exception;
        }
        catch(Exception exception)
        {
            throw new FaxException("Error while invoking process, command: "+command,exception);
        }
        
        return processOutput;
    }
408916
@Override
    protected void doHandle(CommandContext ctx) throws CommandLineException {
        final ModelControllerClient client = ctx.getModelControllerClient();
        if(client == null) {
            throw new CommandLineException("Connection is not available.");
        }

        if (embeddedServerRef != null && embeddedServerRef.get() != null) {
            doHandleEmbedded(ctx, client);
            return;
        }

        if (!(client instanceof AwaiterModelControllerClient)) {
            throw new CommandLineException("Unsupported ModelControllerClient implementation " + client.getClass().getName());
        }
        final AwaiterModelControllerClient cliClient = (AwaiterModelControllerClient) client;

        final ModelNode op = this.buildRequestWithoutHeaders(ctx);
        try {
            final ModelNode response = cliClient.execute(op, true);
            if(!Util.isSuccess(response)) {
                throw new CommandLineException(Util.getFailureDescription(response));
            }
        } catch(IOException e) {
            // if it's not connected it's assumed the reload is in process
            if (cliClient.isConnected()) {
                StreamUtils.safeClose(client);
                throw new CommandLineException("Failed to execute :reload", e);
            }
        }

        ensureServerRebootComplete(ctx, client);
    }
1016016
@Override
    public void createControlAdapter()
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "createControlAdapter");

        DestinationHandler dh = null;
        try
        {
            ReferenceStream rs = getReferenceStream();
            if (rs instanceof MessageReferenceStream)
            {
                ItemStream is = rs.getItemStream();
                if (is instanceof PubSubMessageItemStream)
                {
                    dh = ((PubSubMessageItemStream) is).getDestinationHandler();
                    controlAdapter = new QueuedMessage(this, dh, rs);
                }
            }
        } catch (Exception e)
        {
            // FFDC
            FFDCFilter.processException(
                                        e,
                                        "com.ibm.ws.sib.processor.impl.store.items.MessageItemReference.createControlAdapter",
                                        "1:1266:1.147",
                                        this);

            SibTr.exception(tc, e);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "createControlAdapter");
    }
292831
def command(command)
    
      if ! @authed
        raise NetworkException.new("You must authenticate the connection successfully before sending commands.")
      end

      @packet = Packet::Source.new
      @packet.command(command)

      @socket.print @packet.to_s
      rpacket = build_response_packet

      if rpacket.command_type != Packet::Source::RESPONSE_NORM
        raise NetworkException.new("error sending command: #{rpacket.command_type}")
      end

      if @return_packets
        return rpacket
      else
        return rpacket.string1
      end
    end
1215124
private void createStream(final CreateStreamCommand command, final ChannelPromise promise)
          throws Exception {
    if (lifecycleManager.getShutdownThrowable() != null) {
      command.stream().setNonExistent();
      // The connection is going away (it is really the GOAWAY case),
      // just terminate the stream now.
      command.stream().transportReportStatus(
          lifecycleManager.getShutdownStatus(), RpcProgress.REFUSED, true, new Metadata());
      promise.setFailure(lifecycleManager.getShutdownThrowable());
      return;
    }

    // Get the stream ID for the new stream.
    final int streamId;
    try {
      streamId = incrementAndGetNextStreamId();
    } catch (StatusException e) {
      command.stream().setNonExistent();
      // Stream IDs have been exhausted for this connection. Fail the promise immediately.
      promise.setFailure(e);

      // Initiate a graceful shutdown if we haven't already.
      if (!connection().goAwaySent()) {
        logger.fine("Stream IDs have been exhausted for this connection. "
                + "Initiating graceful shutdown of the connection.");
        lifecycleManager.notifyShutdown(e.getStatus());
        close(ctx(), ctx().newPromise());
      }
      return;
    }

    final NettyClientStream.TransportState stream = command.stream();
    final Http2Headers headers = command.headers();
    stream.setId(streamId);

    // Create an intermediate promise so that we can intercept the failure reported back to the
    // application.
    ChannelPromise tempPromise = ctx().newPromise();
    encoder().writeHeaders(ctx(), streamId, headers, 0, command.isGet(), tempPromise)
            .addListener(new ChannelFutureListener() {
              @Override
              public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                  // The http2Stream will be null in case a stream buffered in the encoder
                  // was canceled via RST_STREAM.
                  Http2Stream http2Stream = connection().stream(streamId);
                  if (http2Stream != null) {
                    stream.getStatsTraceContext().clientOutboundHeaders();
                    http2Stream.setProperty(streamKey, stream);

                    // This delays the in-use state until the I/O completes, which technically may
                    // be later than we would like.
                    if (command.shouldBeCountedForInUse()) {
                      inUseState.updateObjectInUse(http2Stream, true);
                    }

                    // Attach the client stream to the HTTP/2 stream object as user data.
                    stream.setHttp2Stream(http2Stream);
                  }
                  // Otherwise, the stream has been cancelled and Netty is sending a
                  // RST_STREAM frame which causes it to purge pending writes from the
                  // flow-controller and delete the http2Stream. The stream listener has already
                  // been notified of cancellation so there is nothing to do.

                  // Just forward on the success status to the original promise.
                  promise.setSuccess();
                } else {
                  final Throwable cause = future.cause();
                  if (cause instanceof StreamBufferingEncoder.Http2GoAwayException) {
                    StreamBufferingEncoder.Http2GoAwayException e =
                        (StreamBufferingEncoder.Http2GoAwayException) cause;
                    lifecycleManager.notifyShutdown(statusFromGoAway(e.errorCode(), e.debugData()));
                    promise.setFailure(lifecycleManager.getShutdownThrowable());
                  } else {
                    promise.setFailure(cause);
                  }
                }
              }
            });
  }
406940
private CommandOutput<?, ?> executePreparedSql(List<Command> cmds) {
    String query = null;
    List<String> queryParameters = null;
    int fetchSize = 0;

    for (Command cmd : cmds) {
      if (cmd instanceof JdbcCommand) {
        JdbcCommandType type = (JdbcCommandType) cmd.getCommandType();
        switch (type) {
          case QUERY:
            query = cmd.getParams().get(0);
            break;
          case QUERYPARAMS:
            queryParameters = cmd.getParams();
            break;
          case FETCHSIZE:
            fetchSize = Integer.parseInt(cmd.getParams().get(0));
            break;
          default:
            this.log.error("Command " + type.toString() + " not recognized");
            break;
        }
      }
    }

    this.log.info("Executing query:" + query);
    ResultSet resultSet = null;
    try {
      this.jdbcSource = createJdbcSource();
      if (this.dataConnection == null) {
        this.dataConnection = this.jdbcSource.getConnection();
      }

      PreparedStatement statement =
          this.dataConnection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);

      int parameterPosition = 1;
      if (queryParameters != null && queryParameters.size() > 0) {
        for (String parameter : queryParameters) {
          statement.setString(parameterPosition, parameter);
          parameterPosition++;
        }
      }
      if (fetchSize != 0) {
        statement.setFetchSize(fetchSize);
      }
      final boolean status = statement.execute();
      if (status == false) {
        this.log.error("Failed to execute sql:" + query);
      }
      resultSet = statement.getResultSet();

    } catch (Exception e) {
      this.log.error("Failed to execute sql:" + query + " ;error-" + e.getMessage(), e);
    }

    CommandOutput<JdbcCommand, ResultSet> output = new JdbcCommandOutput();
    output.put((JdbcCommand) cmds.get(0), resultSet);
    return output;
  }
1078703
public static MOAObject fromCommandLine(Class requiredType, String commandline) {
  	MOAObject     result;
  	String[]			tmpOptions;
  	String				classname;
  	
  	try {
  		tmpOptions    = Utils.splitOptions(commandline);
  		classname     = tmpOptions[0];
  		tmpOptions[0] = "";
  		try {
  			result = (MOAObject) Class.forName(classname).newInstance();
  		}
  		catch (Exception e) {
  			// try to prepend package name
  			result = (MOAObject) Class.forName(requiredType.getPackage().getName() + "." + classname).newInstance();
  		}
  		if (result instanceof AbstractOptionHandler) {
  			((AbstractOptionHandler) result).getOptions().setViaCLIString(Utils.joinOptions(tmpOptions));
  			((AbstractOptionHandler) result).prepareForUse();
  		}
  	}
  	catch (Exception e) {
  		e.printStackTrace();
  		result = null;
  	}
  	
  	return result;
  }
1110151
private CommandOutput<?, ?> executeSql(List<Command> cmds) {
    String query = null;
    int fetchSize = 0;

    for (Command cmd : cmds) {
      if (cmd instanceof JdbcCommand) {
        JdbcCommandType type = (JdbcCommandType) cmd.getCommandType();
        switch (type) {
          case QUERY:
            query = cmd.getParams().get(0);
            break;
          case FETCHSIZE:
            fetchSize = Integer.parseInt(cmd.getParams().get(0));
            break;
          default:
            this.log.error("Command " + type.toString() + " not recognized");
            break;
        }
      }
    }

    this.log.info("Executing query:" + query);
    ResultSet resultSet = null;
    try {
      this.jdbcSource = createJdbcSource();
      if (this.dataConnection == null) {
        this.dataConnection = this.jdbcSource.getConnection();
      }
      Statement statement = this.dataConnection.createStatement();

      if (fetchSize != 0 && this.getExpectedRecordCount() > 2000) {
        statement.setFetchSize(fetchSize);
      }
      final boolean status = statement.execute(query);
      if (status == false) {
        this.log.error("Failed to execute sql:" + query);
      }
      resultSet = statement.getResultSet();
    } catch (Exception e) {
      this.log.error("Failed to execute sql:" + query + " ;error-" + e.getMessage(), e);
    }

    CommandOutput<JdbcCommand, ResultSet> output = new JdbcCommandOutput();
    output.put((JdbcCommand) cmds.get(0), resultSet);
    return output;
  }