Sends a multipart response. Each body part represents a versioned value
of the given key.

@throws IOException
@throws MessagingException
547703
@Override
    public void sendResponse(StoreStats performanceStats,
                             boolean isFromLocalZone,
                             long startTimeInMs) throws Exception {

        /*
         * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.
         * However when writing to the outputStream we only send the multiPart object and not the entire
         * mimeMessage. This is intentional.
         *
         * In the earlier version of this code we used to create a multiPart object and just send that multiPart
         * across the wire.
         *
         * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates
         * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated
         * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the
         * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()
         * on the body part. It's this updateHeaders call that transfers the content type from the
         * DataHandler to the part's MIME Content-Type header.
         *
         * To make sure that the Content-Type headers are being updated (without changing too much code), we decided
         * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.
         * This is to make sure multiPart's headers are updated accurately.
         */

        MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
        MimeMultipart multiPart = new MimeMultipart();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        String base64Key = RestUtils.encodeVoldemortKey(key.get());
        String contentLocationKey = "/" + this.storeName + "/" + base64Key;

        for(Versioned<byte[]> versionedValue: versionedValues) {

            byte[] responseValue = versionedValue.getValue();

            VectorClock vectorClock = (VectorClock) versionedValue.getVersion();
            String eTag = RestUtils.getSerializedVectorClock(vectorClock);
            numVectorClockEntries += vectorClock.getVersionMap().size();

            // Create the individual body part for each versioned value of the
            // requested key
            MimeBodyPart body = new MimeBodyPart();
            try {
                // Add the right headers
                body.addHeader(CONTENT_TYPE, "application/octet-stream");
                body.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
                body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);
                body.setContent(responseValue, "application/octet-stream");
                body.addHeader(RestMessageHeaders.CONTENT_LENGTH,
                               Integer.toString(responseValue.length));

                multiPart.addBodyPart(body);
            } catch(MessagingException me) {
                logger.error("Exception while constructing body part", me);
                outputStream.close();
                throw me;
            }

        }
        message.setContent(multiPart);
        message.saveChanges();
        try {
            multiPart.writeTo(outputStream);
        } catch(Exception e) {
            logger.error("Exception while writing multipart to output stream", e);
            outputStream.close();
            throw e;
        }
        ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();
        responseContent.writeBytes(outputStream.toByteArray());

        // Create the Response object
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

        // Set the right headers
        response.setHeader(CONTENT_TYPE, "multipart/binary");
        response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
        response.setHeader(CONTENT_LOCATION, contentLocationKey);

        // Copy the data into the payload
        response.setContent(responseContent);
        response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());

        // Write the response to the Netty Channel
        if(logger.isDebugEnabled()) {
            String keyStr = RestUtils.getKeyHexString(this.key);
            debugLog("GET",
                     this.storeName,
                     keyStr,
                     startTimeInMs,
                     System.currentTimeMillis(),
                     numVectorClockEntries);
        }
        this.messageEvent.getChannel().write(response);

        if(performanceStats != null && isFromLocalZone) {
            recordStats(performanceStats, startTimeInMs, Tracked.GET);
        }

        outputStream.close();

    }
759573
@Override
    public Response send(String CorpNum, MgtKeyType KeyType, String MgtKey,
                         String Memo) throws PopbillException {
        return send(CorpNum, KeyType, MgtKey, Memo, null);
    }
1028612
@Override
    protected void haveResponse ( byte[] buffer, int start, int len ) throws SMBProtocolDecodingException {
        if ( isRetainPayload() ) {
            byte[] payload = new byte[len];
            System.arraycopy(buffer, start, payload, 0, len);
            setRawPayload(payload);
        }

        if ( !verifySignature(buffer, start, len) ) {
            throw new SMBProtocolDecodingException("Signature verification failed for " + getClass().getName());
        }

        setAsyncHandled(false);
        received();
    }
1210712
public void sendData(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException
    {
        String dataType = GIF_TYPE;
        res.setContentType(GIF_TYPE.equalsIgnoreCase(dataType) ? "image/gif" : "image/jpeg");
        OutputStream out = res.getOutputStream();
        String strParamField = this.getProperty("field");   // Display record
        ImageIcon imageIcon = null;
        Image image = null;
        int scaledW = 0;
        int scaledH = 0;
        if (strParamField != null)
        {
            Record record = ((DataAccessScreen)this.getScreenField()).getMainRecord();
            if (record != null)
            {
                BaseField field = record.getField(strParamField);
                if (field != null) if (!field.isNull())
                {
                    if (field instanceof ImageField)
                    {
                        if (field.getData() instanceof ImageIcon)
                            imageIcon = (ImageIcon)field.getData();
                        else if (field.getData() instanceof PortableImage)
                        {
                            image = (Image)((PortableImage)field.getData()).getImage();
                            scaledW = ((PortableImage)field.getData()).getImageWidth();
                            scaledH = ((PortableImage)field.getData()).getImageHeight();
                        }
                    }
                }                
            }
        }
        if ((imageIcon == null) && (image == null))
            imageIcon = new ImageIcon("images/icons/Noimage.gif", "Next button");

        if (imageIcon != null)
        {
            scaledW = imageIcon.getIconWidth();
            scaledH = imageIcon.getIconHeight();
            image = imageIcon.getImage();
        }

        BufferedImage outImage = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_RGB);
        // Paint image.
        Graphics2D g2d = outImage.createGraphics();
        g2d.drawImage(image, null, null);
        g2d.dispose();

        ImageIO.write(outImage, dataType, out);
/** This is the code (that works fine) when using the jai image encoder
        // This is the code to use with com.sun encoder:
        // JPEG-encode the image and write to file.
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

        encoder.encode(outImage);
/*
/** This is the code (that works fine) when using the JAI toolkit
        ParameterBlock pb = new ParameterBlock();
        pb.add(image.getImage());
        
        // Create the AWTImage operation.
        PlanarImage im = (PlanarImage)JAI.create("awtImage", pb); // Store the image in the JPEG format.
        JPEGEncodeParam encodeParam = new JPEGEncodeParam();
        float fQuality = 1.0f;
        String strDestination = "test.gif";
        encodeParam.setQuality(fQuality);   // Medium quality
        JAI.create("encode", im, out, "JPEG", encodeParam);
*/
    }
739959
@Override
	public void receiveResponse(Tree message) {

		// Verify protocol version
		if (checkVersion) {
			String ver = message.get("ver", "unknown");
			if (!PROTOCOL_VERSION.equals(ver)) {
				logger.warn("Invalid protocol version (" + ver + ")!");
				return;
			}
		}

		// Get response's unique ID
		String id = message.get("id", (String) null);
		if (id == null || id.isEmpty()) {
			logger.warn("Missing \"id\" property!", message);
			return;
		}

		// Incoming (response) stream handling
		IncomingStream responseStream;
		responseStreamReadLock.lock();
		try {
			responseStream = responseStreams.get(id);
		} finally {
			responseStreamReadLock.unlock();
		}
		if (responseStream != null) {
			boolean remove = false;
			try {
				if (responseStream.receive(message)) {
					remove = true;
				}
			} catch (Throwable error) {
				remove = true;

				// Write error to log file
				if (writeErrorsToLog) {
					logger.error("Unexpected error occurred while streaming!", error);
				}
			}
			if (remove) {
				responseStreamWriteLock.lock();
				try {
					responseStreams.remove(id);
				} finally {
					responseStreamWriteLock.unlock();
				}
			}
			return;
		}
		if (message.get("stream", false)) {
			responseStreamWriteLock.lock();
			try {
				responseStream = responseStreams.get(id);
				if (responseStream == null) {
					responseStream = new IncomingStream(nodeID, scheduler, streamTimeout);
					responseStreams.put(id, responseStream);
				}
			} finally {
				responseStreamWriteLock.unlock();
			}
			if (responseStream.receive(message)) {
				responseStreamWriteLock.lock();
				try {
					responseStreams.remove(id);
				} finally {
					responseStreamWriteLock.unlock();
				}
			}
			message.putObject("data", responseStream.getPacketStream());
		}

		// Get stored promise
		PendingPromise pending = promises.remove(id);
		if (pending == null) {
			logger.warn("Unknown (maybe timeouted) response received!", message);
			return;
		}
		try {

			// Get response status (successed or not?)
			boolean success = message.get("success", true);
			if (success) {

				// Ok -> resolve
				pending.promise.complete(message.get("data"));

			} else {

				// Failed -> reject
				Tree error = message.get("error");
				MoleculerError moleculerError;
				if (error == null) {
					moleculerError = new MoleculerError("Remote invocation failed!", null, "MoleculerError",
							pending.nodeID, false, 500, "UNKNOWN_ERROR", message);
				} else {
					moleculerError = MoleculerErrorUtils.create(error);
				}

				pending.promise.complete(moleculerError);
				logger.error(moleculerError.getMessage(), moleculerError);

				return;
			}
		} catch (Throwable cause) {
			logger.error("Unable to pass on incoming response!", cause);
		}
	}
1224034
public void sendAll(String apiKey, String queue, Collection<?> messages) {
        checkNotNull(queue, "queue");
        checkNotNull(messages, "messages");
        if (messages.isEmpty()) {
            return;
        }
        try {
            URI uri = _queueService.clone()
                    .segment(queue, "sendbatch")
                    .build();
            _client.resource(uri)
                    .type(MediaType.APPLICATION_JSON_TYPE)
                    .header(ApiKeyRequest.AUTHENTICATION_HEADER, apiKey)
                    .post(messages);
        } catch (EmoClientException e) {
            throw convertException(e);
        }
    }
190012
public void sendData(Object req, Object res)
        throws Exception, IOException
    {
        this.sendData((HttpServletRequest)req, (HttpServletResponse)res);
    }
848164
static void sendResponse(final ManagementRequestContext<ExecuteRequestContext> context, final byte responseType, final ModelNode response) throws IOException {

        // WFLY-3090 Protect the communication channel from getting closed due to administrative
        // cancellation of the management op by using a separate thread to send
        final CountDownLatch latch = new CountDownLatch(1);
        final IOExceptionHolder exceptionHolder = new IOExceptionHolder();
        boolean accepted = context.executeAsync(new AsyncTask<TransactionalProtocolOperationHandler.ExecuteRequestContext>() {

            @Override
            public void execute(final ManagementRequestContext<ExecuteRequestContext> context) throws Exception {
                FlushableDataOutput output = null;
                try {
                    MGMT_OP_LOGGER.tracef("Transmitting response for %d", context.getOperationId());
                    final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());
                    output = context.writeMessage(header);
                    // response type
                    output.writeByte(responseType);
                    // operation result
                    response.writeExternal(output);
                    // response end
                    output.writeByte(ManagementProtocol.RESPONSE_END);
                    output.close();
                } catch (IOException toCache) {
                    exceptionHolder.exception = toCache;
                } finally {
                    StreamUtils.safeClose(output);
                    latch.countDown();
                }
            }
        }, false);
        if (accepted) {
            try {
                latch.await();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            if (exceptionHolder.exception != null) {
                throw exceptionHolder.exception;
            }
        }
    }
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());
        }
    }
1222804
@Override
    public void sendResponseHeaders() throws IOException, MessageSentException {

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "sendResponseHeaders(sync)");
        }
        if (!headersParsed()) {
            // request message must have the headers parsed prior to sending
            // any data out (this is a completely invalid state in the channel
            // above)
            IOException ioe = new IOException("Request not read yet");
            FFDCFilter.processException(ioe,
                                        CLASS_NAME + ".sendResponseHeaders", "594");
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Attempt to send response without a request msg");
            }
            throw ioe;
        }

        if (headersSent()) {
            throw new MessageSentException("Message already sent");
        }

        sendHeaders(getResponseImpl());
        if (getResponseImpl().isTemporaryStatusCode()) {
            // allow multiple temporary responses to be sent out
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Temp response sent, resetting send flags.");
            }
            resetWrite();
        }
    }
1363475
@Override
    public void setResponseHeader(String key, String value) {
        this.response.setResponseHeader(key, value);
    }
1075090
protected HttpResponse sendImpl() throws IOException {
    HttpURLConnection con = (HttpURLConnection) uri.toURL().openConnection();
    con.setConnectTimeout(connectTimeout);
    con.setReadTimeout(readTimeout);
    con.setRequestMethod(method);
    for (Map.Entry<String, String> h : reqHeaders.entrySet()) {
      con.setRequestProperty(h.getKey(), h.getValue());
    }
    configureHTTPS(con);

    boolean canRetry = true;
    try {
      con.setDoInput(true);

      // HttpURLConnection will change method to POST if there is a body associated
      // with a GET request. Only try to write entity if it is not empty.
      entry.withRequestContentLength(entity.length).mark("start");
      if (entity.length > 0) {
        con.setDoOutput(true);
        try (OutputStream out = con.getOutputStream()) {
          out.write(entity);
        }
      }

      int status = con.getResponseCode();
      canRetry = (status >= 500 || status == 429);
      entry.mark("complete").withStatusCode(status);

      // A null key is used to return the status line, remove it before sending to
      // the log entry or creating the response object
      Map<String, List<String>> headers = new LinkedHashMap<>(con.getHeaderFields());
      headers.remove(null);
      for (Map.Entry<String, List<String>> h : headers.entrySet()) {
        for (String v : h.getValue()) {
          entry.withResponseHeader(h.getKey(), v);
        }
      }

      try (InputStream in = (status >= 400) ? con.getErrorStream() : con.getInputStream()) {
        byte[] data = readAll(in);
        entry.withResponseContentLength(data.length);
        return new HttpResponse(status, headers, data);
      }
    } catch (IOException e) {
      entry.mark("complete").withException(e);
      throw e;
    } finally {
      entry.withCanRetry(canRetry);
      HttpLogEntry.logClientRequest(entry);
    }
  }
610821
private void reply(final String response, final boolean error,
            final String errorMessage, final String stackTrace,
            final String statusCode, final int statusCodeInt,
            Map<String, List<String>> responseHeaders) {

        if (!sentReply) {
            // must update sentReply first to avoid duplicated msg.
            sentReply = true;

            final ResponseOnSingeRequest res = new ResponseOnSingeRequest(
                    response, error, errorMessage, stackTrace, statusCode,
                    statusCodeInt, PcDateUtils.getNowDateTimeStrStandard(),
                    responseHeaders);
            if (!getContext().system().deadLetters().equals(sender)) {
                sender.tell(res, getSelf());
            }
            if (getContext() != null) {
                getContext().stop(getSelf());
            }
        }

    }
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));
        }
    }
368054
private void writeResponse(final HttpServletResponse response, final String data) throws IOException {
    final byte[] outputBody = data.getBytes(StandardCharsets.UTF_8);
    response.getOutputStream().write(outputBody);
  }
640047
static void sendResponse(final ManagementRequestContext<RegistrationContext> context, final byte responseType, final ModelNode response) throws IOException {
        final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());
        final FlushableDataOutput output = context.writeMessage(header);
        try {
            sendResponse(output, responseType, response);
        } finally {
            StreamUtils.safeClose(output);
        }
    }
1018805
public ListVersionsHandler parseListVersionsResponse(InputStream inputStream, final boolean shouldSDKDecodeResponse)
            throws IOException {
        ListVersionsHandler handler = new ListVersionsHandler(shouldSDKDecodeResponse);
        parseXmlInputStream(handler, sanitizeXmlDocument(handler, inputStream));
        return handler;
    }