Handle an SMTP transaction, i.e. all activity between initial connect and QUIT command.

@param out output stream
@param input input stream
@return List of SmtpMessage
776516
private List<SmtpMessage> handleTransaction(PrintWriter out, BufferedReader input) throws IOException {
		// Initialize the state machine
		SmtpState smtpState = SmtpState.CONNECT;
		SmtpRequest smtpRequest = new SmtpRequest(SmtpActionType.CONNECT, "", smtpState);

		// Execute the connection request
		SmtpResponse smtpResponse = smtpRequest.execute();

		// Send initial response
		sendResponse(out, smtpResponse);
		smtpState = smtpResponse.getNextState();

		List<SmtpMessage> msgList = new ArrayList<>();
		SmtpMessage msg = new SmtpMessage();

		while (smtpState != SmtpState.CONNECT) {
			String line = input.readLine();

			if (line == null) {
				break;
			}

			// Create request from client input and current state
			SmtpRequest request = SmtpRequest.createRequest(line, smtpState);
			// Execute request and create response object
			SmtpResponse response = request.execute();
			// Move to next internal state
			smtpState = response.getNextState();
			// Send response to client
			sendResponse(out, response);

			// Store input in message
			String params = request.getParams();
			msg.store(response, params);

			// If message reception is complete save it
			if (smtpState == SmtpState.QUIT) {
				msgList.add(msg);
				msg = new SmtpMessage();
			}
		}

		return msgList;
	}
920937
def execute(input=@input)
      completions = Array(call_action(input)).map {|e| e.to_s }
      completions = call_search(@search, input, completions) if @search
      if @completion_prefix
        # Everything up to last break char stays on the line.
        # Must ensure only chars after break are prefixed
        @completion_prefix = @completion_prefix[/([^#{Readline::DefaultBreakCharacters}]+)$/,1] || ''
        completions = completions.map {|e| @completion_prefix + e }
      end
      completions
    end
165025
public static String qsub(String input) {
        final CommandLine cmdLine = new CommandLine(COMMAND_QSUB);
        cmdLine.addArgument(input);

        final OutputStream out = new ByteArrayOutputStream();
        final OutputStream err = new ByteArrayOutputStream();

        DefaultExecuteResultHandler resultHandler;
        try {
            resultHandler = execute(cmdLine, null, out, err);
            resultHandler.waitFor(DEFAULT_TIMEOUT);
        } catch (ExecuteException e) {
            throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
        } catch (IOException e) {
            throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
        } catch (InterruptedException e) {
            throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
        }

        final int exitValue = resultHandler.getExitValue();
        LOGGER.info("qsub exit value: " + exitValue);
        LOGGER.fine("qsub output: " + out.toString());

        if (exitValue != 0)
            throw new PBSException("Failed to submit job script " + input + ". Error output: " + err.toString());

        String jobId = out.toString();
        return jobId.trim();
    }
471203
public static void deliverMail (String[] recipients, String sender,
                                    String subject, MimeMessage message)
        throws IOException
    {
        checkCreateSession();
        try {
            message.setFrom(new InternetAddress(sender));
            for (String recipient : recipients) {
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            }
            if (subject != null) {
                message.setSubject(subject);
            }
            message.saveChanges();
            Address[] recips = message.getAllRecipients();
            if (recips == null || recips.length == 0) {
                log.info("Not sending mail to zero recipients",
                    "subject", subject, "message", message);
                return;
            }
            Transport t = _defaultSession.getTransport(recips[0]);
            try {
                t.addTransportListener(_listener);
                t.connect();
                t.sendMessage(message, recips);

            } finally {
                t.close();
            }

        } catch (Exception e) {
            String errmsg = "Failure sending mail [from=" + sender +
                ", to=" + StringUtil.toString(recipients) +
                ", subject=" + subject + "]";
            IOException ioe = new IOException(errmsg);
            ioe.initCause(e);
            throw ioe;
        }
    }
965967
protected void sendInput()
    {
        Thread thread = new Thread()
        {
            public void run()
            {
                try
                {
                    stdin.write(input.getBytes("UTF-8"));
                    stdin.flush();
                    stdin.close();
                }
                catch (Exception e)
                {
                    exceptionCaught(e);
                }
            }
        };

        try
        {
            thread.start();
            thread.join();
        }
        catch (Exception e)
        {
            exceptionCaught(e);
        }
    }
254756
public static long copyAndCloseOutput(InputStream input, OutputStream output) throws IOException {
		try (OutputStream outputStream = output) {
			return copy(input, outputStream);
		}
	}
143167
public <Message extends PMessage<Message, Field>, Field extends PField>
    void formatTo(OutputStream out, Message message) {
        IndentedPrintWriter builder = new IndentedPrintWriter(out, indent, newline);
        if (message == null) {
            builder.append(null);
        } else {
            builder.append(message.descriptor().getQualifiedName())
                   .append(space);
            appendMessage(builder, message);
        }
        builder.flush();
    }
1016377
@Override
  public void deliver(WriteStream os, OutHttp2 outHttp)
    throws IOException
  {
    outHttp.writeFlow(_streamId, _credit);
  }
452039
@Override
    InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {
        assert args.length <= 3;                // includes null

        // first check that we are still attached
        int door;
        synchronized (this) {
            if (fd == -1) {
                throw new IOException("Detached from target VM");
            }
            door = fd;
        }

        // enqueue the command via a door call
        int s = enqueue(door, cmd, args);
        assert s >= 0;                          // valid file descriptor

        // The door call returns a file descriptor (one end of a socket pair).
        // Create an input stream around it.
        SocketInputStream sis = new SocketInputStream(s);

        // Read the command completion status
        int completionStatus;
        try {
            completionStatus = readInt(sis);
        } catch (IOException ioe) {
            sis.close();
            throw ioe;
        }

        // If non-0 it means an error but we need to special-case the
        // "load" command to ensure that the right exception is thrown.
        if (completionStatus != 0) {
            sis.close();
            if (cmd.equals("load")) {
                throw new AgentLoadException("Failed to load agent library");
            } else {
                throw new IOException("Command failed in target VM");
            }
        }

        // Return the input stream so that the command output can be read
        return sis;
    }
1136626
public static List<String> readLines(InputStream input) throws IOException {
        final InputStreamReader reader = new InputStreamReader(input);
        return readLines(reader);
    }
297571
private TransactionOutput createOutput(Address sendTo, long value) {
      ScriptOutput script;
      if (sendTo.isMultisig(_network)) {
         script = new ScriptOutputMultisig(sendTo.getTypeSpecificBytes());
      } else {
         script = new ScriptOutputStandard(sendTo.getTypeSpecificBytes());
      }
      TransactionOutput output = new TransactionOutput(value, script);
      return output;
   }
922245
@Override
  public void deliver(WriteStream os, OutHttp2 outHttp)
    throws IOException
  {
    outHttp.writeReset(_streamId, _errorCode);
  }
456936
public void doProcess(InputStream in, PrintWriter out, Map<String, Object> properties)
        throws RemoteException
    {
        String strCommand = this.getProperty(REMOTE_COMMAND, properties);
        try {
            if (CLOSE.equals(strCommand))
            {
                ((RemoteDatabase)m_remoteObject).close();
            }
            else if (GET_DB_PROPERTIES.equals(strCommand))
            {
                Map<String,Object> propIn = ((RemoteDatabase)m_remoteObject).getDBProperties();
                this.setReturnObject(out, propIn);
            }
            else if (SET_DB_PROPERTIES.equals(strCommand))
            {
                Map<String,Object> propIn = this.getNextPropertiesParam(in, PROPERTIES, properties);
                if (propIn != null)
                    properties.putAll(propIn);
                ((RemoteDatabase)m_remoteObject).setDBProperties(properties);
            }
            else if (COMMIT.equals(strCommand))
            {
                ((RemoteDatabase)m_remoteObject).commit();
            }
            else if (ROLLBACK.equals(strCommand))
            {
                ((RemoteDatabase)m_remoteObject).rollback();
            }
            else
                super.doProcess(in, out, properties);
        } catch (DBException ex)    {
            this.setReturnObject(out, ex);
        } catch (Exception ex)    {
            this.setReturnObject(out, ex);
        }
    }
392055
public OkRequest<T> send(final InputStream input) throws IOException {

        openOutput();

        copy(input, mOutput);

        return this;
    }
1228213
@Override
    protected void outputPass() {
        if(!prototype.isOutputSupported())
            return;

        // take a snapshot of the current container state.
        final LinkedList<Object> toOutput = new LinkedList<Object>(instances.keySet());

        final Executor executorService = getOutputExecutorService();
        final Semaphore taskLock = (executorService != null) ? new Semaphore(outputConcurrency) : null;

        // This keeps track of the number of concurrently running
        // output tasks so that this method can wait until they're
        // all done to return.
        //
        // It's also used as a condition variable signaling on its
        // own state changes.
        final AtomicLong numExecutingOutputs = new AtomicLong(0);

        final MutRef<WorkingQueueHolder> mref = new MutRef<>();

        // keep going until all of the outputs have been invoked
        while(toOutput.size() > 0 && isRunning.get()) {
            for(final Iterator<Object> iter = toOutput.iterator(); iter.hasNext();) {
                final Object key = iter.next();

                final InstanceWrapper wrapper = instances.get(key);

                if(wrapper != null) { // if the MP still exists
                    final WorkingQueueHolder mailbox = setIfAbsent(wrapper.mailbox, () -> mref.set(new WorkingQueueHolder(true)));
                    if(mailbox == null) { // this means I got it.
                        // it was created locked so no one else will be able to drop messages in the mailbox.
                        final Semaphore taskSepaphore = taskLock;

                        // This task will release the wrapper's lock.
                        final Runnable task = new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    if(isRunning.get())
                                        invokeOperation(wrapper.instance, Operation.output, null);
                                } finally {
                                    wrapper.mailbox.set(null); // releases this back to the world

                                    // this signals that we're done.
                                    synchronized(numExecutingOutputs) {
                                        numExecutingOutputs.decrementAndGet();
                                        numExecutingOutputs.notifyAll();
                                    }
                                    if(taskSepaphore != null)
                                        taskSepaphore.release();
                                }
                            }
                        };

                        synchronized(numExecutingOutputs) {
                            numExecutingOutputs.incrementAndGet();
                        }

                        if(executorService != null) {
                            try {
                                taskSepaphore.acquire();
                                executorService.execute(task);
                            } catch(final RejectedExecutionException e) {
                                wrapper.mailbox.set(null); // we never got into the run so we need to release the lock
                                // this may happen because of a race condition between the
                                taskSepaphore.release();
                            } catch(final InterruptedException e) {
                                // this can happen while blocked in the semaphore.acquire.
                                // if we're no longer running we should just get out
                                // of here.
                                //
                                // Not releasing the taskSepaphore assumes the acquire never executed.
                                // if (since) the acquire never executed we also need to release the
                                // wrapper lock or that Mp will never be usable again.
                                wrapper.mailbox.set(null); // we never got into the run so we need to release the lock
                            }
                        } else
                            task.run();

                        iter.remove();

                    } // didn't get the lock
                } else { // end if mp exists. Otherwise the mp is already gone.
                    iter.remove();
                    LOGGER.warn("There was an attempt to output a non-existent Mp for key " + SafeString.objectDescription(key));
                }
            } // loop over every mp
        } // end while there are still Mps that haven't had output invoked.

        // =======================================================
        // now make sure all of the running tasks have completed
        synchronized(numExecutingOutputs) {
            while(numExecutingOutputs.get() > 0) {
                try {
                    numExecutingOutputs.wait();
                } catch(final InterruptedException e) {
                    // if we were interupted for a shutdown then just stop
                    // waiting for all of the threads to finish
                    if(!isRunning.get())
                        break;
                    // otherwise continue checking.
                }
            }
        }
        // =======================================================
    }
902612
@Override public Call<Void> accept(List<Span> input) {
    if (input.isEmpty()) return Call.create(null);

    Set<InsertSpan.Input> spans = new LinkedHashSet<>();
    Set<InsertServiceRemoteService.Input> serviceRemoteServices = new LinkedHashSet<>();
    Set<InsertServiceSpan.Input> serviceSpans = new LinkedHashSet<>();
    Set<InsertTraceByServiceRemoteService.Input> traceByServiceRemoteServices =
      new LinkedHashSet<>();
    Set<InsertTraceByServiceSpan.Input> traceByServiceSpans = new LinkedHashSet<>();
    Set<Map.Entry<String, String>> autocompleteTags = new LinkedHashSet<>();

    for (Span s : input) {
      // indexing occurs by timestamp, so derive one if not present.
      long ts_micro = s.timestampAsLong();
      if (ts_micro == 0L) ts_micro = guessTimestamp(s);

      // fallback to current time on the ts_uuid for span data, so we know when it was inserted
      UUID ts_uuid =
        new UUID(
          UUIDs.startOf(ts_micro != 0L ? (ts_micro / 1000L) : System.currentTimeMillis())
            .getMostSignificantBits(),
          UUIDs.random().getLeastSignificantBits());

      spans.add(insertSpan.newInput(s, ts_uuid));

      if (!searchEnabled) continue;

      // Empty values allow for api queries with blank service or span name
      String service = s.localServiceName() != null ? s.localServiceName() : "";
      String span =
        null != s.name() ? s.name() : ""; // Empty value allows for api queries without span name

      if (null == s.localServiceName()) continue; // don't index further w/o a service name

      // service span and remote service indexes is refreshed regardless of timestamp
      String remoteService = s.remoteServiceName();
      if (insertServiceRemoteService != null && remoteService != null) {
        serviceRemoteServices.add(insertServiceRemoteService.newInput(service, remoteService));
      }
      serviceSpans.add(insertServiceSpan.newInput(service, span));

      if (ts_micro == 0L) continue; // search is only valid with a timestamp, don't index w/o it!
      int bucket = durationIndexBucket(ts_micro); // duration index is milliseconds not microseconds
      long duration = s.durationAsLong() / 1000L;
      traceByServiceSpans.add(
        insertTraceByServiceSpan.newInput(service, span, bucket, ts_uuid, s.traceId(), duration));
      if (span.isEmpty()) continue;

      if (insertServiceRemoteService != null && remoteService != null) {
        traceByServiceRemoteServices.add(
          insertTraceByServiceRemoteService.newInput(service, remoteService, bucket, ts_uuid,
            s.traceId()));
      }
      traceByServiceSpans.add( // Allows lookup without the span name
        insertTraceByServiceSpan.newInput(service, "", bucket, ts_uuid, s.traceId(), duration));

      if (insertAutocompleteValue != null) {
        for (Map.Entry<String, String> entry : s.tags().entrySet()) {
          if (autocompleteKeys.contains(entry.getKey())) autocompleteTags.add(entry);
        }
      }
    }
    List<Call<Void>> calls = new ArrayList<>();
    for (InsertSpan.Input span : spans) {
      calls.add(insertSpan.create(span));
    }
    for (InsertServiceSpan.Input serviceSpan : serviceSpans) {
      insertServiceSpan.maybeAdd(serviceSpan, calls);
    }
    for (InsertServiceRemoteService.Input serviceRemoteService : serviceRemoteServices) {
      insertServiceRemoteService.maybeAdd(serviceRemoteService, calls);
    }
    for (InsertTraceByServiceSpan.Input serviceSpan : traceByServiceSpans) {
      calls.add(insertTraceByServiceSpan.create(serviceSpan));
    }
    for (InsertTraceByServiceRemoteService.Input serviceRemoteService : traceByServiceRemoteServices) {
      calls.add(insertTraceByServiceRemoteService.create(serviceRemoteService));
    }
    for (Map.Entry<String, String> autocompleteTag : autocompleteTags) {
      insertAutocompleteValue.maybeAdd(autocompleteTag, calls);
    }
    return calls.isEmpty() ? Call.create(null) : AggregateCall.newVoidCall(calls);
  }
517309
public void doProcess(InputStream in, PrintWriter out, Map<String, Object> properties)
        throws RemoteException
    {
        String strCommand = this.getProperty(REMOTE_COMMAND, properties);
        try {
            if (FREE_REMOTE_SESSION.equals(strCommand))
            {
                ((BaseSession)m_remoteObject).freeRemoteSession();
                this.free();    // Free this (peer's) resources.
            }
            else if (MAKE_REMOTE_SESSION.equals(strCommand))
            {
                String strSessionClassName = this.getNextStringParam(in, NAME, properties);
                RemoteBaseSession remoteSession = ((RemoteBaseSession)m_remoteObject).makeRemoteSession(strSessionClassName);
                this.setReturnSessionOrObject(out, remoteSession);
            }
            else if (DO_REMOTE_ACTION.equals(strCommand))
            {
                String strAction = this.getNextStringParam(in, NAME, properties);
                Map<String,Object> propIn = this.getNextPropertiesParam(in, PROPERTIES, properties);
                if (propIn != null)
                    properties.putAll(propIn);
                Object objReturn = ((RemoteBaseSession)m_remoteObject).doRemoteAction(strAction, properties);
                this.setReturnSessionOrObject(out, objReturn);  // Could be a session.
            }
            else
                super.doProcess(in, out, properties);
        } catch (Exception ex)    {
            // ex.printStackTrace();    // Don't print this error, since I am returning it to my ajax caller.
            this.setReturnObject(out, ex);
        }
    }