Builds response and sets it as out message on given Camel exchange.
@param message
@param exchange
@return
343308
private void buildOutMessage(Exchange exchange, Message message) {
        org.apache.camel.Message reply = exchange.getOut();
        for (Map.Entry<String, Object> header : message.getHeaders().entrySet()) {
            if (!header.getKey().startsWith(MessageHeaders.PREFIX)) {
                reply.setHeader(header.getKey(), header.getValue());
            }
        }

        if (message.getHeader(CitrusCamelMessageHeaders.EXCHANGE_EXCEPTION) != null) {
            String exceptionClass = message.getHeader(CitrusCamelMessageHeaders.EXCHANGE_EXCEPTION).toString();
            String exceptionMsg = null;

            if (message.getHeader(CitrusCamelMessageHeaders.EXCHANGE_EXCEPTION_MESSAGE) != null) {
                exceptionMsg = message.getHeader(CitrusCamelMessageHeaders.EXCHANGE_EXCEPTION_MESSAGE).toString();
            }

            try {
                Class<?> exception = Class.forName(exceptionClass);
                if (exceptionMsg != null) {
                    exchange.setException((Throwable) exception.getConstructor(String.class).newInstance(exceptionMsg));
                } else {
                    exchange.setException((Throwable) exception.newInstance());
                }
            } catch (RuntimeException e) {
                log.warn("Unable to create proper exception instance for exchange!", e);
            } catch (Exception e) {
                log.warn("Unable to create proper exception instance for exchange!", e);
            }
        }

        reply.setBody(message.getPayload());
    }
974780
public static String messageAsText(final Message message, final boolean includeHeaders) {
		try {
			StrBuilder sb = new StrBuilder(300);

			if (includeHeaders) {
				@SuppressWarnings("unchecked")
				Enumeration<Header> headers = message.getAllHeaders();
				while (headers.hasMoreElements()) {
					Header header = headers.nextElement();
					sb.append(header.getName()).append('=').appendln(header.getValue());
				}

				sb.appendln("");
			}

			Object content = message.getContent();
			if (content instanceof String) {
				String body = (String) content;
				sb.appendln(body);
				sb.appendln("");
			} else if (content instanceof Multipart) {
				parseMultipart(sb, (Multipart) content);
			}
			return sb.toString();
		} catch (MessagingException ex) {
			throw new MailException("Error getting mail content.", ex);
		} catch (IOException ex) {
			throw new MailException("Error getting mail content.", ex);
		}
	}
1305579
public Response executeMessage(Message message, Builder<?> builder) {
    return executeMessage(message, builder,
                          OperaIntervals.RESPONSE_TIMEOUT.getMs());
  }
1042988
def publish(self, message, routing_key=None):
        
        if routing_key is None:
            routing_key = self.routing_key
        return self.client.publish_to_exchange(self.name, message=message, routing_key=routing_key)
301403
@Override
	public MailSendResult send(MailMessage message) {

		Assert.notNull(message, "Missing mail message!");

		Properties props = new Properties();
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.host", smtpHost);
		props.put("mail.smtp.port", smtpPort);

		Session session = getSession(props, smtpUsername, smtpPassword);

		try {
			// build mime message
			Message msg = message.getMessage(session);

			Enumeration enumer = msg.getAllHeaders();
			while (enumer.hasMoreElements()) {
				Header header = (Header) enumer.nextElement();
				log.info(header.getName() + ": " + header.getValue());
			}

			log.info("Getting transport...");

			Transport transport = session.getTransport("smtp");
			log.info("Connecting to SMTP server: " + smtpHost + ":" + smtpPort);

			transport.connect();
			transport.sendMessage(msg, msg.getAllRecipients());

			log.info("Closing transport...");
			transport.close();
		}
		catch (Exception e) {

			log.error(e.getMessage(), e);
			return MailSendResult.fail();
		}

		return MailSendResult.ok();

	}
460583
@Override
    public void handleRequest(final HttpServerExchange exchange) throws Exception {
        if(exchange.isInIoThread()) {
            exchange.dispatch(this);
            return;
        }
        SecurityContext context = exchange.getSecurityContext();
        if (context.authenticate()) {
            if(!exchange.isComplete()) {
               next.handleRequest(exchange);
            }
        } else {
            if(exchange.getStatusCode() >= StatusCodes.BAD_REQUEST && !exchange.isComplete()) {
                ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
                src.getOriginalResponse().sendError(exchange.getStatusCode());
            } else {
                exchange.endExchange();
            }
        }
    }
153769
@Override
    public void handleRequest(final HttpServerExchange exchange) throws Exception {

        // handle request header
        Map<String, Object> requestHeaderMap = (Map<String, Object>)config.get(REQUEST);
        if(requestHeaderMap != null) {
            List<String> requestHeaderRemove = (List<String>)requestHeaderMap.get(REMOVE);
            if(requestHeaderRemove != null) {
                requestHeaderRemove.forEach(s -> exchange.getRequestHeaders().remove(s));
            }
            Map<String, String> requestHeaderUpdate = (Map<String, String>)requestHeaderMap.get(UPDATE);
            if(requestHeaderUpdate != null) {
                requestHeaderUpdate.forEach((k, v) -> exchange.getRequestHeaders().put(new HttpString(k), v));
            }
        }

        // handle response header
        Map<String, Object> responseHeaderMap = (Map<String, Object>)config.get(RESPONSE);
        if(responseHeaderMap != null) {
            List<String> responseHeaderRemove = (List<String>)responseHeaderMap.get(REMOVE);
            if(responseHeaderRemove != null) {
                responseHeaderRemove.forEach(s -> exchange.getResponseHeaders().remove(s));
            }
            Map<String, String> responseHeaderUpdate = (Map<String, String>)responseHeaderMap.get(UPDATE);
            if(responseHeaderUpdate != null) {
                responseHeaderUpdate.forEach((k, v) -> exchange.getResponseHeaders().put(new HttpString(k), v));
            }
        }
        Handler.next(exchange, next);
    }
1209750
public Observable<Boolean> handleMessage(final ChatMessage message) {

        String sender = message.getSentBy();

        Observable<Boolean> replaceMessages = persistenceController.updateStoreWithNewMessage(message, noConversationListener);

        if (!TextUtils.isEmpty(sender) && !sender.equals(getProfileId())) {

            final Set<String> ids = new HashSet<>();
            ids.add(message.getMessageId());

            return Observable.zip(replaceMessages, markDelivered(message.getConversationId(), ids), (saved, result) -> saved && result.isSuccessful());

        } else {

            return replaceMessages;
        }
    }
377419
private ResponseEncapsulation recvMessage() throws IOException {
    GeneratedMessage msg = null;
    byte[] headers = new byte[8];
    recv(headers, headers.length);

    if (headers[0] != 'L' || headers[1] != '1') {
      throw new IOException("Wrong launcher protocol header");
    }

    ByteBuffer buf = ByteBuffer.allocate(4);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.put(headers, 4, 4);
    buf.flip();

    int size = buf.getInt();

    logger.finest("RECV: type=" + ((int) headers[3]) + ", command="
                  + ((int) headers[2]) + ", size=" + size);

    byte[] data = new byte[size];
    recv(data, size);

    boolean success = (headers[3] == (byte) 1);
    MessageType type = MessageType.get(headers[2]);

    if (type == null) {
      throw new IOException("Unable to determine message type");
    }

    if ((headers[3] != (byte) 1) && (headers[3] != (byte) 2)) {
      throw new IOException("Unable to determine success or error");
    }

    switch (type) {
      case MSG_HELLO: {
        LauncherHandshakeResponse.Builder response = LauncherHandshakeResponse.newBuilder();
        buildMessage(response, data);
        msg = response.build();
        break;
      }

      case MSG_START:
      case MSG_STATUS:
      case MSG_STOP: {
        LauncherStatusResponse.Builder response = LauncherStatusResponse.newBuilder();
        buildMessage(response, data);
        msg = response.build();
        break;
      }

      case MSG_SCREENSHOT: {
        LauncherScreenshotResponse.Builder response = LauncherScreenshotResponse.newBuilder();
        buildMessage(response, data);
        msg = response.build();
        break;
      }

    }

    return new ResponseEncapsulation(success, msg);
  }
704053
public <Message extends PMessage<Message, Field>, Field extends PField>
    String format(Message message) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        formatTo(out, message);
        return new String(out.toByteArray(), StandardCharsets.UTF_8);
    }
226887
protected String createSoapFaultResponse(String message)
            throws SOAPException, TransformerException {
        return createSoapFaultResponse(SOAPConstants.SOAP_1_1_PROTOCOL, null, message);
    }
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);
		}
	}
764731
public function publishMessage($message, $exchange, $routing_key = '', $flags = AMQP_NOPARAM, $attributes = [])
    {
        if (!isset($this->_exchanges[$exchange])) {
            throw new InvalidKeyException(['publish message to `:1` exchange with `:2` routing_key failed: exchange is NOT exists', $exchange, $routing_key]);
        }

        try {
            $this->_exchanges[$exchange]->publish($message, $routing_key, $flags, $attributes);
        } catch (\Exception $e) {
            throw new AmqpException(['publish message to `:1` exchange with `:2` routing_key failed: `:3`', $exchange, $routing_key, $e->getMessage()]);
        }

        return $this;
    }
1304208
@Broadcast(writeEntity = false)
    @POST
    public Response broadcast(Message message) {
        if (injectedService == null) {
            throw new WebApplicationException(500);
        }
        return new Response(message.author, message.message);
    }
897519
public function publishMessage($exchangeName, $routingKey, $message)
    {
        $informations = $this->query('POST', sprintf(
            '/api/exchanges/%s/%s/publish',
            $this->credentials['vhost'],
            $exchangeName
        ), array(
            'properties'       => array(),
            'routing_key'      => $routingKey,
            'payload'          => $message,
            'payload_encoding' => 'string',
        ));

        $decodedInformations = json_decode($informations, true);

        if (isset($decodedInformations['routed']) && true === $decodedInformations['routed']) {
            return;
        }

        throw new \RuntimeException('Unable to send that message into rabbit.');
    }
451354
protected Response createNotFound(String message) {
    ErrorResponse entity = new ErrorResponse();
    entity.setMessage(message);
    return Response
      .status(Response.Status.NOT_FOUND)
      .entity(entity)
      .build();
  }
354886
public Status validateResponse(final HttpServerExchange exchange, final SwaggerOperation swaggerOperation) {
        requireNonNull(exchange, "An exchange is required");
        requireNonNull(swaggerOperation, "A swagger operation is required");

        io.swagger.models.Response swaggerResponse = swaggerOperation.getOperation().getResponses().get(Integer.toString(exchange.getStatusCode()));
        if (swaggerResponse == null) {
            swaggerResponse = swaggerOperation.getOperation().getResponses().get("default"); // try the default response
        }

        if (swaggerResponse == null) {
            return new Status("ERR11015", exchange.getStatusCode(), swaggerOperation.getPathString().original());
        }

        if (swaggerResponse.getSchema() == null) {
            return null;
        }
        String body = exchange.getOutputStream().toString();

        if (body == null || body.length() == 0) {
            return new Status("ERR11016", swaggerOperation.getMethod(), swaggerOperation.getPathString().original());
        }
        return schemaValidator.validate(body, swaggerResponse.getSchema());
    }