Send a xcmd Overture Response

@param overtureCmd
The overture command which this is a response to
@param hdr
The header
@param body
The body
@throws IOException
10329
private void xcmdOvertureResponse(DBGPXCmdOvertureCommandType overtureCmd,
			StringBuilder hdr, StringBuilder body) throws IOException
	{
		StringBuilder sb = new StringBuilder();

		sb.append("<xcmd_overture_response command=\"");
		sb.append(command);
		sb.append("\"");

		sb.append(" overtureCmd=\"");
		sb.append(overtureCmd);
		sb.append("\"");

		if (hdr != null)
		{
			sb.append(" ");
			sb.append(hdr);
		}

		sb.append(" transaction_id=\"");
		sb.append(transaction);
		sb.append("\"");

		if (body != null)
		{
			sb.append(">");
			sb.append(body);
			sb.append("</xcmd_overture_response>\n");
		} else
		{
			sb.append("/>\n");
		}

		write(sb);
	}
606437
public void setHocr(boolean hocr) {
        this.renderedFormat = hocr ? RenderedFormat.HOCR : RenderedFormat.TEXT;
        prop.setProperty("tessedit_create_hocr", hocr ? "1" : "0");
    }
858681
private void sendResponse(HttpServletResponse servletResponse, RESTResponse restResponse) throws IOException {
        servletResponse.setStatus(restResponse.getCode().getCode());
        
        Map<String, String> responseHeaders = restResponse.getHeaders();
        if (responseHeaders != null) {
            for (Map.Entry<String, String> mapEntry : responseHeaders.entrySet()) {
                if (mapEntry.getKey().equalsIgnoreCase(HttpDefs.CONTENT_TYPE)) {
                    servletResponse.setContentType(mapEntry.getValue());
                } else {
                    servletResponse.setHeader(mapEntry.getKey(), mapEntry.getValue());
                }
            }
        }
        
        byte[] bodyBytes = restResponse.getBodyBytes();
        int bodyLen = bodyBytes == null ? 0 : bodyBytes.length;
        servletResponse.setContentLength(bodyLen);
        
        if (bodyLen > 0 && servletResponse.getContentType() == null) {
            servletResponse.setContentType("text/plain");
        }
        
        if (bodyLen > 0) {
            servletResponse.getOutputStream().write(restResponse.getBodyBytes());
        }
    }
466254
def send_frame(self, cmd, headers=None, body=''):
        
        if headers is None:
            headers = {}
        frame = utils.Frame(cmd, headers, body)

        if cmd == CMD_BEGIN:
            trans = headers[HDR_TRANSACTION]
            if trans in self.transactions:
                self.notify('error', {}, 'Transaction %s already started' % trans)
            else:
                self.transactions[trans] = []
        elif cmd == CMD_COMMIT:
            trans = headers[HDR_TRANSACTION]
            if trans not in self.transactions:
                self.notify('error', {}, 'Transaction %s not started' % trans)
            else:
                for f in self.transactions[trans]:
                    self.transport.transmit(f)
                del self.transactions[trans]
        elif cmd == CMD_ABORT:
            trans = headers['transaction']
            del self.transactions[trans]
        else:
            if 'transaction' in headers:
                trans = headers['transaction']
                if trans not in self.transactions:
                    self.transport.notify('error', {}, 'Transaction %s not started' % trans)
                    return
                else:
                    self.transactions[trans].append(frame)
            else:
                self.transport.transmit(frame)
1252430
public byte[] sendHeader(OutputStream os, int commandId, int commandStatus,
            int sequenceNumber) throws IOException {
        synchronized (os) {
            return pduSender.sendHeader(os, commandId, commandStatus,
                    sequenceNumber);
        }
    }
107719
private void sendDummyTakeMastershipResponse(long sourceHsid, long requestId, int partitionId, byte[] signatureBytes) {
        // msg type(1) + partition:int(4) + length:int(4) + signaturesBytes.length
        // requestId(8)
        int msgLen = 1 + 4 + 4 + signatureBytes.length + 8;
        ByteBuffer buf = ByteBuffer.allocate(msgLen);
        buf.put(ExportManager.TAKE_MASTERSHIP_RESPONSE);
        buf.putInt(partitionId);
        buf.putInt(signatureBytes.length);
        buf.put(signatureBytes);
        buf.putLong(requestId);
        BinaryPayloadMessage bpm = new BinaryPayloadMessage(new byte[0], buf.array());
        m_mbox.send(sourceHsid, bpm);
        if (exportLog.isDebugEnabled()) {
            exportLog.debug("Partition " + partitionId + " mailbox hsid (" +
                    CoreUtils.hsIdToString(m_mbox.getHSId()) +
                    ") send dummy TAKE_MASTERSHIP_RESPONSE message(" +
                    requestId + ") to " + CoreUtils.hsIdToString(sourceHsid));
        }
    }
554047
protected function sendmailSend($header, $body)
    {
        // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
        if (!empty($this->Sender) and self::isShellSafe($this->Sender)) {
            if ('qmail' == $this->Mailer) {
                $sendmailFmt = '%s -f%s';
            } else {
                $sendmailFmt = '%s -oi -f%s -t';
            }
        } else {
            if ('qmail' == $this->Mailer) {
                $sendmailFmt = '%s';
            } else {
                $sendmailFmt = '%s -oi -t';
            }
        }

        $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);

        if ($this->SingleTo) {
            foreach ($this->SingleToArray as $toAddr) {
                $mail = @popen($sendmail, 'w');
                if (!$mail) {
                    throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
                }
                fwrite($mail, 'To: ' . $toAddr . "\n");
                fwrite($mail, $header);
                fwrite($mail, $body);
                $result = pclose($mail);
                $this->doCallback(
                    ($result == 0),
                    [$toAddr],
                    $this->cc,
                    $this->bcc,
                    $this->Subject,
                    $body,
                    $this->From,
                    []
                );
                if (0 !== $result) {
                    throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
                }
            }
        } else {
            $mail = @popen($sendmail, 'w');
            if (!$mail) {
                throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
            }
            fwrite($mail, $header);
            fwrite($mail, $body);
            $result = pclose($mail);
            $this->doCallback(
                ($result == 0),
                $this->to,
                $this->cc,
                $this->bcc,
                $this->Subject,
                $body,
                $this->From,
                []
            );
            if (0 !== $result) {
                throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
            }
        }

        return true;
    }
416238
public Message putHeader(short id, Header hdr) {
        if(id < 0)
            throw new IllegalArgumentException("An ID of " + id + " is invalid");
        if(hdr != null)
            hdr.setProtId(id);
        synchronized(this) {
            Header[] resized_array=Headers.putHeader(this.headers, id, hdr, true);
            if(resized_array != null)
                this.headers=resized_array;
        }
        return this;
    }
1339698
public void sendData(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        res.setContentType("text/xml");
        PrintWriter out = res.getWriter();
        this.printXML(req, out);
        out.flush();
    }
284770
public void sendResponse(HttpResponse resp, boolean close) throws IOException {
		StringBuilder header = new StringBuilder();
		header.append("HTTP/1.1").append(' ').append(resp.getStatus().getCode()).append(' ').append(resp.getStatus());
		header.append('\r').append('\n');
		// Set the content type header if it's not already set
		if (!resp.getHeaders().containsKey(HttpHeader.CONTENT_TYPE)) {
			resp.addHeader(HttpHeader.CONTENT_TYPE, "text/html; charset=utf-8");
		}
		// Set the content length header if it's not already set
		if (!resp.getHeaders().containsKey(HttpHeader.CONTENT_LENGTH)) {
			resp.addHeader(HttpHeader.CONTENT_LENGTH, resp.getResponseLength());
		}
		// Copy in the headers
		for (Entry<String, List<Object>> entry : resp.getHeaders().entrySet()) {
			String headerName = HttpUtil.capitalizeHeader(entry.getKey());
			for (Object o : entry.getValue()) {
				header.append(headerName);
				header.append(':').append(' ');
				header.append(o);
				header.append('\r').append('\n');
			}
		}
		header.append('\r').append('\n');
		// Write the header
		output.write(header.toString().getBytes("UTF-8"));

		// Ignore the body for headers and no content
		if (request != null && request.getMethod() == HttpMethod.HEAD || resp.getStatus() == HttpStatus.NO_CONTENT) {
			if (resp.getResponse() instanceof InputStream) {
				((InputStream) resp.getResponse()).close();
			}
		} else {
			// Responses can be InputStreams or Strings
			if (resp.getResponse() instanceof InputStream) {
				// InputStreams will block the session thread (No big deal) and send
				// data without loading it into memory
				InputStream res = resp.getResponse();
				try {
					long remaining = resp.getResponseLength();
					// Write the body
					byte[] buffer = new byte[1024];
					while (remaining > 0) {
						int read = res.read(buffer, 0, remaining > buffer.length ? buffer.length : (int) remaining);
						if (read == -1) {
							break;
						}

						output.write(buffer, 0, read);

						remaining -= read;
					}
				} finally {
					res.close();
				}
			} else if (resp.getResponse() instanceof String) {
				String responseString = resp.getResponse();
				output.write(responseString.getBytes("UTF-8"));
			} else if (resp.getResponse() instanceof byte[]) {
				output.write((byte[]) resp.getResponse());
			}
		}
		// Close it if required.
		if (close) {
			socket.close();
		}
	}

	/**
	 * Send an HttpStatus
	 *
	 * @param status The status to send
	 * @throws IOException If an error occurred while sending
	 */
	public void sendError(HttpStatus status) throws IOException {
		sendResponse(new HttpResponse(status, status.toString()));
	}

	/**
	 * Send an HttpStatus with the specified error message
	 *
	 * @param status The status to send
	 * @param message The error message to send
	 * @throws IOException If an error occurred while sending
	 */
	public void sendError(HttpStatus status, String message) throws IOException {
		sendResponse(new HttpResponse(status, status.toString() + ':' + message));
	}

	/**
	 * Get the remote address from this session
	 *
	 * @return The remote address
	 */
	public InetSocketAddress getRemoteAddress() {
		return (InetSocketAddress) socket.getRemoteSocketAddress();
	}
}
364962
@Override
    synchronized public void sendResponse(ReplyHeader h, Record r, String tag) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // Make space for length
            BinaryOutputArchive bos = BinaryOutputArchive.getArchive(baos);
            try {
                baos.write(fourBytes);
                bos.writeRecord(h, "header");
                if (r != null) {
                    bos.writeRecord(r, tag);
                }
                baos.close();
            } catch (IOException e) {
                LOG.error("Error serializing response");
            }
            byte b[] = baos.toByteArray();
            ByteBuffer bb = ByteBuffer.wrap(b);
            bb.putInt(b.length - 4).rewind();
            sendBuffer(bb);
            if (h.getXid() > 0) {
                synchronized(this){
                    outstandingRequests--;
                }
                // check throttling
                synchronized (this.factory) {
                    if (zk.getInProcess() < factory.outstandingLimit
                            || outstandingRequests < 1) {
                        sk.selector().wakeup();
                        enableRecv();
                    }
                }
            }
         } catch(Exception e) {
            LOG.warn("Unexpected exception. Destruction averted.", e);
         }
    }
23941
public void write(Command cmd)
        throws IOException, IllegalArgumentException {
        //we delete the initial reply when the first command is sent
        if (cmd == null) {
            throw new IllegalArgumentException("null argument: cmd");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Control channel sending: " + cmd);
        }
        writeStr(cmd.toString());
    }
735100
public function sendResponse(ResponseInterface $response) : void
    {
        if (!headers_sent()) {
            $this->sendStatusLine($response);
            $this->sendHeaders($response);
        }
        $this->eventDispatcher->dispatch(new EventAfterAppReponseHeadersSending($response));
        $this->sendBody($response);
    }
1157250
private void sendCommandToAll(ReplicableCommand command, long requestId, DeliverOrder deliverOrder, boolean rsvp) {
      Message message = new Message();
      marshallRequest(message, command, requestId);
      setMessageFlags(message, deliverOrder, rsvp, true);

      if (deliverOrder == DeliverOrder.TOTAL) {
         message.dest(new AnycastAddress());
      }

      send(message);
   }
629720
public final void send (final ProtocolDataUnit protocolDataUnit) throws InternetSCSIException {

        try {
            senderReceiver.sendOverWire(protocolDataUnit);
        } catch (IOException e) {
            throw new InternetSCSIException(e);
        } catch (InterruptedException e) {
            throw new InternetSCSIException(e);
        }
    }
318721
public void send(TCResponseRequest event) throws TCAPSendException {

        if (this.previewMode)
            return;

        if (!this.isStructured()) {
            throw new TCAPSendException("Unstructured dialogs do not use Response");
        }

        try {
            dialogLock.lock();
            TCResponseMessageImpl tcbm = null;

            if (state == TRPseudoState.InitialReceived) {
                // TC-END request primitive issued in response to a TC-BEGIN
                // indication primitive
                this.idleTimerActionTaken = true;
                stopIdleTimer();
                tcbm = (TCResponseMessageImpl) TcapFactory.createTCResponseMessage();
                tcbm.setDestinationTransactionId(this.remoteTransactionId);
                // local address may change, lets check it;
                if (event.getOriginatingAddress() != null && !event.getOriginatingAddress().equals(this.localAddress)) {
                    this.localAddress = event.getOriginatingAddress();
                }

                if (event.getApplicationContextName() != null || event.getConfidentiality() != null
                        || event.getSecurityContext() != null || event.getUserInformation() != null) {
                    // set dialog portion
                    DialogPortion dp = TcapFactory.createDialogPortion();
                    dp.setProtocolVersion(TcapFactory.createProtocolVersionFull());
                    dp.setApplicationContext(event.getApplicationContextName());
                    dp.setUserInformation(event.getUserInformation());
                    dp.setSecurityContext(event.getSecurityContext());
                    dp.setConfidentiality(event.getConfidentiality());

                    tcbm.setDialogPortion(dp);
                }
                if (this.scheduledComponentList.size() > 0) {
                    Component[] componentsToSend = new Component[this.scheduledComponentList.size()];
                    this.prepareComponents(componentsToSend);
                    tcbm.setComponent(componentsToSend);
                }

            } else if (state == TRPseudoState.Active) {
                restartIdleTimer();
                tcbm = (TCResponseMessageImpl) TcapFactory.createTCResponseMessage();

                tcbm.setDestinationTransactionId(this.remoteTransactionId);
                if (this.scheduledComponentList.size() > 0) {
                    Component[] componentsToSend = new Component[this.scheduledComponentList.size()];
                    this.prepareComponents(componentsToSend);
                    tcbm.setComponent(componentsToSend);
                }

            } else {
                throw new TCAPSendException(String.format("State is not %s or %s: it is %s", TRPseudoState.Active,
                        TRPseudoState.InitialReceived, this.state));
            }

            AsnOutputStream aos = new AsnOutputStream();
            try {
                tcbm.encode(aos);
                if (this.provider.getStack().getStatisticsEnabled()) {
                    this.provider.getStack().getCounterProviderImpl().updateTcResponseSentCount(this);
                }
                this.provider.send(aos.toByteArray(), event.getReturnMessageOnError(), this.remoteAddress, this.localAddress,
                        this.seqControl, this.getNetworkId(), this.localSsn);

                this.scheduledComponentList.clear();
            } catch (Exception e) {
                // FIXME: remove freshly added invokes to free invoke ID??
                if (logger.isEnabledFor(Level.ERROR)) {
                    logger.error("Failed to send message: ", e);
                }
                throw new TCAPSendException("Failed to send TC-Response message: " + e.getMessage(), e);
            } finally {
                // FIXME: is this proper place - should we not release in case
                // of error ?
                release();
            }
        } finally {
            dialogLock.unlock();
        }
    }
618808
protected synchronized void do_send(final OtpOutputStream header)
            throws IOException {
        try {
            if (traceLevel >= ctrlThreshold) {
                try {
                    final OtpErlangObject h = header.getOtpInputStream(5)
                            .read_any();
                    System.out.println("-> " + headerType(h) + " " + h);
                } catch (final OtpErlangDecodeException e) {
                    System.out.println("   " + "can't decode output buffer: "
                            + e);
                }
            }
            header.writeToAndFlush(socket.getOutputStream());
        } catch (final IOException e) {
            close();
            throw e;
        }
    }