Creates a {@code status} tag based on the response status of the given
{@code exchange}.
@param exchange the exchange
@return the status tag derived from the response status
2063
public static Tag status(ServerWebExchange exchange) {
		HttpStatus status = exchange.getResponse().getStatusCode();
		if (status == null) {
			status = HttpStatus.OK;
		}
		return Tag.of("status", String.valueOf(status.value()));
	}
750228
@Benchmark
  @BenchmarkMode(Mode.AverageTime)
  @OutputTimeUnit(TimeUnit.NANOSECONDS)
  public TagContext tagContextCreation(Data data) {
    return TagsBenchmarksUtil.createTagContext(data.tagger.emptyBuilder(), data.numTags);
  }
513301
protected String getRequestBody(HttpServerExchange exchange) throws IOException {
        String body = "";
        if (RequestUtils.isPostPutPatch(exchange)) {
            exchange.startBlocking();
            body = IOUtils.toString(exchange.getInputStream(), Default.ENCODING.toString());
        }

        return body;
    }
1027279
static void processOK(HttpServerExchange exchange) throws IOException {
        exchange.setStatusCode(StatusCodes.OK);
        exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE);
        exchange.endExchange();
    }
908172
public static boolean sendRequestedBlobs(HttpServerExchange exchange) {
        ByteBuffer buffer = null;
        String type = null;
        String etag = null;
        String quotedEtag = null;
        if ("css".equals(exchange.getQueryString())) {
            buffer = Blobs.FILE_CSS_BUFFER.duplicate();
            type = "text/css";
            etag = Blobs.FILE_CSS_ETAG;
            quotedEtag = Blobs.FILE_CSS_ETAG_QUOTED;
        } else if ("js".equals(exchange.getQueryString())) {
            buffer = Blobs.FILE_JS_BUFFER.duplicate();
            type = "application/javascript";
            etag = Blobs.FILE_JS_ETAG;
            quotedEtag = Blobs.FILE_JS_ETAG_QUOTED;
        }

        if (buffer != null) {

            if(!ETagUtils.handleIfNoneMatch(exchange, new ETag(false, etag), false)) {
                exchange.setStatusCode(StatusCodes.NOT_MODIFIED);
                return true;
            }

            exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, String.valueOf(buffer.limit()));
            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, type);
            exchange.getResponseHeaders().put(Headers.ETAG, quotedEtag);
            if (Methods.HEAD.equals(exchange.getRequestMethod())) {
                exchange.endExchange();
                return true;
            }
            exchange.getResponseSender().send(buffer);

            return true;
        }

        return false;
    }
267804
private String getTag(final Annotation[] annotations, final Method method) {
        for (final Annotation annotation : annotations) {
            if (annotation instanceof Audit) {
                final Audit audit = (Audit) annotation;
                return audit.tag();
            }
        }
        return null;
    }
647334
@SuppressWarnings("rawtypes")
    protected Form getForm(HttpServerExchange exchange) throws IOException {
        final Form form = Application.getInstance(Form.class);
        if (RequestUtils.isPostPutPatch(exchange)) {
            final Builder builder = FormParserFactory.builder();
            builder.setDefaultCharset(StandardCharsets.UTF_8.name());
            try (final FormDataParser formDataParser = builder.build().createParser(exchange)) {
                if (formDataParser != null) {
                    exchange.startBlocking();
                    final FormData formData = formDataParser.parseBlocking();
                    for (String data : formData) {
                        Deque<FormValue> deque = formData.get(data);
                        if (deque != null) {
                            FormValue formValue = deque.element();
                            if (formValue != null) {
                                if (formValue.isFileItem() && formValue.getFileItem().getFile() != null) {
                                    form.addFile(Files.newInputStream(formValue.getFileItem().getFile()));
                                } else {
                                    if (data.contains("[]")) {
                                        String key = StringUtils.replace(data, "[]", "");
                                        for (Iterator iterator = deque.iterator(); iterator.hasNext();)  {
                                            form.addValueList(new HttpString(key).toString(), ((FormValue) iterator.next()).getValue());
                                        }
                                    } else {
                                        form.addValue(new HttpString(data).toString(), formValue.getValue());
                                    }
                                }    
                            }
                        }
                    }
                }
            }
            
            form.setSubmitted(true);
        }

        return form;
    }
583606
@Override
    public void process(Exchange exchange) throws Exception {
        if (log.isTraceEnabled()) {
            log.trace(exchange.toString());
        }

        GPIOAction messageAction = exchange.getIn().getHeader(Pi4jConstants.CAMEL_RBPI_PIN_ACTION, action,
                GPIOAction.class);

        if (messageAction == null) {
            log.trace("No action pick up body");
            this.output(exchange, exchange.getIn().getBody());
        } else {
            log.trace("action= {} ", action);
            switch (messageAction) {

            case TOGGLE:
                if (pin.getMode() == PinMode.DIGITAL_OUTPUT) {
                    ((GpioPinDigitalOutput) pin).toggle();
                }
                break;

            case LOW:
                if (pin.getMode() == PinMode.DIGITAL_OUTPUT) {
                    ((GpioPinDigitalOutput) pin).low();
                }
                break;

            case HIGH:
                if (pin.getMode() == PinMode.DIGITAL_OUTPUT) {
                    ((GpioPinDigitalOutput) pin).high();
                }
                break;

            case BLINK:
                if (pin.getMode() == PinMode.DIGITAL_OUTPUT) {

                    pool.submit(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(getEndpoint().getDelay());
                                ((GpioPinDigitalOutput) pin).toggle();
                                Thread.sleep(getEndpoint().getDuration());
                                ((GpioPinDigitalOutput) pin).toggle();
                            } catch (InterruptedException e) {
                                log.error("Thread interruption into BLINK sequence", e);
                            }
                        }
                    });
                }

                break;

            default:
                log.error("Any action set found");
                break;
            }
        }
    }
170002
protected function createExchange($exchangeClass, $channel, array $exchangeOptions)
    {
        /** @var \AMQPExchange $exchange */
        $exchange = new $exchangeClass($channel);
        $exchange->setName($exchangeOptions['name']);

        // If the type is not specified, the exchange must exist
        if (isset($exchangeOptions['type'])) {
            $exchange->setType($exchangeOptions['type']);
            $exchange->setArguments($exchangeOptions['arguments']);
            $exchange->setFlags(
                ($exchangeOptions['passive'] ? AMQP_PASSIVE : AMQP_NOPARAM) |
                ($exchangeOptions['durable'] ? AMQP_DURABLE : AMQP_NOPARAM) |
                ($exchangeOptions['auto_delete'] ? AMQP_AUTODELETE : AMQP_NOPARAM)
            );
            $exchange->declareExchange();
        }

        return $exchange;
    }
610884
@SuppressWarnings("unchecked")
    protected Flash getFlashCookie(HttpServerExchange exchange) {
        Flash flash = Flash.create();
        
        final String cookieValue = getCookieValue(exchange, this.config.getFlashCookieName());
        if (StringUtils.isNotBlank(cookieValue)) {
            try {
                String decryptedValue = Application.getInstance(Crypto.class).decrypt(cookieValue, this.config.getFlashCookieEncryptionKey());
                JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                    .setVerificationKey(new HmacKey(this.config.getFlashCookieSignKey().getBytes(StandardCharsets.UTF_8)))
                    .setJwsAlgorithmConstraints(new AlgorithmConstraints(ConstraintType.WHITELIST, AlgorithmIdentifiers.HMAC_SHA512))
                    .build();
                
                JwtClaims jwtClaims = jwtConsumer.processToClaims(decryptedValue);
                LocalDateTime expires = LocalDateTime.parse(jwtClaims.getClaimValue(ClaimKey.EXPIRES.toString(), String.class), DateUtils.formatter);
                
                if (expires.isAfter(LocalDateTime.now())) {
                    if (jwtClaims.hasClaim(ClaimKey.FORM.toString())) {
                        this.form = CodecUtils.deserializeFromBase64(jwtClaims.getClaimValue(ClaimKey.FORM.toString(), String.class));
                    } 
                    
                    flash = Flash.create()
                            .withContent(MangooUtils.copyMap(jwtClaims.getClaimValue(ClaimKey.DATA.toString(), Map.class))).setDiscard(true);
                }
            } catch (MalformedClaimException | InvalidJwtException  e) {
                LOG.error("Failed to parse flash cookie", e);
                flash.invalidate();
            } 
        }
        
        return flash;
    }
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());
    }
226875
public static String createAssignmentMessage(final String tagName,
            final AssignmentResult<? extends NamedEntity> result, final VaadinMessageSource i18n) {
        final StringBuilder formMsg = new StringBuilder();
        final int assignedCount = result.getAssigned();
        final int alreadyAssignedCount = result.getAlreadyAssigned();
        final int unassignedCount = result.getUnassigned();
        if (assignedCount == 1) {
            formMsg.append(i18n.getMessage("message.target.assigned.one", result.getAssignedEntity().get(0).getName(),
                    tagName)).append("<br>");
        } else if (assignedCount > 1) {
            formMsg.append(i18n.getMessage("message.target.assigned.many", assignedCount, tagName)).append("<br>");

            if (alreadyAssignedCount > 0) {
                final String alreadyAssigned = i18n.getMessage("message.target.alreadyAssigned", alreadyAssignedCount);
                formMsg.append(alreadyAssigned).append("<br>");
            }
        }
        if (unassignedCount == 1) {
            formMsg.append(i18n.getMessage("message.target.unassigned.one",
                    result.getUnassignedEntity().get(0).getName(), tagName)).append("<br>");
        } else if (unassignedCount > 1) {
            formMsg.append(i18n.getMessage("message.target.unassigned.many", unassignedCount, tagName)).append("<br>");
        }
        return formMsg.toString();
    }
594908
@Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        if ( exchange.getRequestMethod() != Methods.POST ) {
            exchange.setResponseCode(404);
            exchange.endExchange();
            return;
        }
        String rpath = exchange.getRelativePath();

        StreamSourceChannel requestChannel = exchange.getRequestChannel();
        String first = exchange.getRequestHeaders().getFirst(Headers.CONTENT_LENGTH);
        int len = Integer.parseInt(first);

        // read post data.
        ByteBuffer buf = ByteBuffer.allocate(len);
        requestChannel.getReadSetter().set( streamSourceChannel -> {
                try {
                    streamSourceChannel.read(buf);
                } catch (IOException e) {
                    Log.Warn(this,e);
                }
                if ( buf.remaining() == 0 ) {
                    try {
                        requestChannel.shutdownReads();
                    } catch (IOException e) {
                        Log.Warn(this,e);
                    }
                    facade.execute( () -> requestReceived( exchange, buf.array(), rpath ) );
                }
            }
        );
        requestChannel.resumeReads();
    }
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();
            }
        }
    }
879336
private void processConfig(final HttpServerExchange exchange, final RequestData requestData) {

        // Get the node builder
        List<String> hosts = null;
        List<String> contexts = null;
        final Balancer.BalancerBuilder balancer = Balancer.builder();
        final NodeConfig.NodeBuilder node = NodeConfig.builder(modCluster);
        final Iterator<HttpString> i = requestData.iterator();
        while (i.hasNext()) {
            final HttpString name = i.next();
            final String value = requestData.getFirst(name);

            UndertowLogger.ROOT_LOGGER.mcmpKeyValue(name, value);
            if (!checkString(value)) {
                processError(TYPESYNTAX, SBADFLD + name + SBADFLD1, exchange);
                return;
            }

            if (BALANCER.equals(name)) {
                node.setBalancer(value);
                balancer.setName(value);
            } else if (MAXATTEMPTS.equals(name)) {
                balancer.setMaxRetries(Integer.parseInt(value));
            } else if (STICKYSESSION.equals(name)) {
                if ("No".equalsIgnoreCase(value)) {
                    balancer.setStickySession(false);
                }
            } else if (STICKYSESSIONCOOKIE.equals(name)) {
                balancer.setStickySessionCookie(value);
            } else if (STICKYSESSIONPATH.equals(name)) {
                balancer.setStickySessionPath(value);
            } else if (STICKYSESSIONREMOVE.equals(name)) {
                if ("Yes".equalsIgnoreCase(value)) {
                    balancer.setStickySessionRemove(true);
                }
            } else if (STICKYSESSIONFORCE.equals(name)) {
                if ("no".equalsIgnoreCase(value)) {
                    balancer.setStickySessionForce(false);
                }
            } else if (JVMROUTE.equals(name)) {
                node.setJvmRoute(value);
            } else if (DOMAIN.equals(name)) {
                node.setDomain(value);
            } else if (HOST.equals(name)) {
                node.setHostname(value);
            } else if (PORT.equals(name)) {
                node.setPort(Integer.parseInt(value));
            } else if (TYPE.equals(name)) {
                node.setType(value);
            } else if (REVERSED.equals(name)) {
                continue; // ignore
            } else if (FLUSH_PACKET.equals(name)) {
                if ("on".equalsIgnoreCase(value)) {
                    node.setFlushPackets(true);
                } else if ("auto".equalsIgnoreCase(value)) {
                    node.setFlushPackets(true);
                }
            } else if (FLUSH_WAIT.equals(name)) {
                node.setFlushwait(Integer.parseInt(value));
            } else if (MCMPConstants.PING.equals(name)) {
                node.setPing(Integer.parseInt(value));
            } else if (SMAX.equals(name)) {
                node.setSmax(Integer.parseInt(value));
            } else if (TTL.equals(name)) {
                node.setTtl(TimeUnit.SECONDS.toMillis(Long.parseLong(value)));
            } else if (TIMEOUT.equals(name)) {
                node.setTimeout(Integer.parseInt(value));
            } else if (CONTEXT.equals(name)) {
                final String[] context = value.split(",");
                contexts = Arrays.asList(context);
            } else if (ALIAS.equals(name)) {
                final String[] alias = value.split(",");
                hosts = Arrays.asList(alias);
            } else if(WAITWORKER.equals(name)) {
                node.setWaitWorker(Integer.parseInt(value));
            } else {
                processError(TYPESYNTAX, SBADFLD + name + SBADFLD1, exchange);
                return;
            }
        }

        final NodeConfig config;
        try {
            // Build the config
            config = node.build();
            if (container.addNode(config, balancer, exchange.getIoThread(), exchange.getConnection().getByteBufferPool())) {
                // Apparently this is hard to do in the C part, so maybe we should just remove this
                if (contexts != null && hosts != null) {
                    for (final String context : contexts) {
                        container.enableContext(context, config.getJvmRoute(), hosts);
                    }
                }
                processOK(exchange);
            } else {
                processError(MCMPErrorCode.NODE_STILL_EXISTS, exchange);
            }
        } catch (Exception e) {
            processError(MCMPErrorCode.CANT_UPDATE_NODE, exchange);
        }
    }
286338
private IdTagInfo_.Status convertAuthenticationStatus(IdentifyingToken.AuthenticationStatus status) {
        IdTagInfo_.Status result;
        switch (status) {
            case ACCEPTED:
                result = IdTagInfo_.Status.ACCEPTED;
                break;
            case EXPIRED:
                result = IdTagInfo_.Status.EXPIRED;
                break;
            case DELETED:
                result = IdTagInfo_.Status.EXPIRED;
                break;
            case CONCURRENT_TX:
                result = IdTagInfo_.Status.CONCURRENT_TX;
                break;
            case BLOCKED:
                result = IdTagInfo_.Status.BLOCKED;
                break;
            default:
                result = IdTagInfo_.Status.INVALID;
                break;
        }
        return result;
    }
477274
public static Tag outcome(ClientResponse response) {
		try {
			if (response != null) {
				HttpStatus status = response.statusCode();
				if (status.is1xxInformational()) {
					return OUTCOME_INFORMATIONAL;
				}
				if (status.is2xxSuccessful()) {
					return OUTCOME_SUCCESS;
				}
				if (status.is3xxRedirection()) {
					return OUTCOME_REDIRECTION;
				}
				if (status.is4xxClientError()) {
					return OUTCOME_CLIENT_ERROR;
				}
				if (status.is5xxServerError()) {
					return OUTCOME_SERVER_ERROR;
				}
			}
			return OUTCOME_UNKNOWN;
		}
		catch (IllegalArgumentException exc) {
			return OUTCOME_UNKNOWN;
		}
	}