io.undertow.server.HttpServerExchange Java Examples

The following examples show how to use io.undertow.server.HttpServerExchange. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Oauth2ServiceServiceIdEndpointPostHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    List<Map<String, Object>> body = (List)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    String serviceId = exchange.getQueryParameters().get("serviceId").getFirst();
    if(logger.isDebugEnabled()) logger.debug("post serviceEndpoints for serviceId " + serviceId);

    // ensure that the serviceId exists
    IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services");
    if(services.get(serviceId) == null) {
        setExchangeStatus(exchange, SERVICE_NOT_FOUND, serviceId);
        processAudit(exchange);
        return;
    }

    IMap<String, List<ServiceEndpoint>> serviceEndpoints = CacheStartupHookProvider.hz.getMap("serviceEndpoints");
    List<ServiceEndpoint> list = new ArrayList<>();
    for(Map<String, Object> m: body) {
        list.add(Config.getInstance().getMapper().convertValue(m, ServiceEndpoint.class));
    }
    serviceEndpoints.set(serviceId, list);
    processAudit(exchange);
}
 
Example #2
Source File: ProxyHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void failed(final HttpServerExchange exchange) {
    final long time = System.currentTimeMillis();
    if (tries++ < maxRetryAttempts) {
        if (timeout > 0 && time > timeout) {
            cancel(exchange);
        } else {
            target = proxyClient.findTarget(exchange);
            if (target != null) {
                final long remaining = timeout > 0 ? timeout - time : -1;
                proxyClient.getConnection(target, exchange, this, remaining, TimeUnit.MILLISECONDS);
            } else {
                couldNotResolveBackend(exchange); // The context was registered when we started, so return 503
            }
        }
    } else {
        couldNotResolveBackend(exchange);
    }
}
 
Example #3
Source File: NameVirtualHostHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final String hostHeader = exchange.getRequestHeader(HttpHeaderNames.HOST);
    if (hostHeader != null) {
        String host;
        if (hostHeader.contains(":")) { //header can be in host:port format
            host = hostHeader.substring(0, hostHeader.lastIndexOf(":"));
        } else {
            host = hostHeader;
        }
        //most hosts will be lowercase, so we do the host
        HttpHandler handler = hosts.get(host);
        if (handler != null) {
            handler.handleRequest(exchange);
            return;
        }
        //do a cache insensitive match
        handler = hosts.get(host.toLowerCase(Locale.ENGLISH));
        if (handler != null) {
            handler.handleRequest(exchange);
            return;
        }
    }
    defaultHandler.handleRequest(exchange);
}
 
Example #4
Source File: SimpleErrorPageHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean handleDefaultResponse(final HttpServerExchange exchange) {
    if (!exchange.isResponseChannelAvailable()) {
        return false;
    }
    Set<Integer> codes = responseCodes;
    if (codes == null ? exchange.getStatusCode() >= StatusCodes.BAD_REQUEST : codes.contains(Integer.valueOf(exchange.getStatusCode()))) {
        final String errorPage = "<html><head><title>Error</title></head><body>" + exchange.getStatusCode() + " - " + StatusCodes.getReason(exchange.getStatusCode()) + "</body></html>";
        exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, "" + errorPage.length());
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
        Sender sender = exchange.getResponseSender();
        sender.send(errorPage);
        return true;
    }
    return false;
}
 
Example #5
Source File: ChangeSessionId.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static String changeSessionId(HttpServerExchange exchange, boolean create) {
    final ServletRequestContext sc = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    ServletContextImpl currentServletContext = sc.getCurrentServletContext();
    HttpSessionImpl session = currentServletContext.getSession(exchange, create);
    if (session == null) {
        return null;
    }
    Session underlyingSession;
    if(System.getSecurityManager() == null) {
        underlyingSession = session.getSession();
    } else {
        underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
    }


    return underlyingSession.changeSessionId(exchange, currentServletContext.getSessionConfig());
}
 
Example #6
Source File: PathParameterDeserializerTest.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
/**
* undertow consider path parts following ';' as path parameters and tries to parse them too.
* the below code simulates the parsing results in light-4j handler chains.	
*/
@Test
public void test_matrix_primitive() {
	Schema schema = new PojoSchema();
	schema.setType("string");
	
	Parameter parameter = new PoJoParameter(PARAM_NAME,
			ParameterType.PATH.name().toLowerCase(),
			PathParameterStyle.MATRIX.name().toLowerCase(),
			true,
			schema);
	
	HttpServerExchange exchange = new HttpServerExchange(null);
	
	exchange.addPathParam(PARAM_NAME, "5");
	exchange.addPathParam(PARAM_NAME, "");
	
	checkString(exchange, parameter, "5");
}
 
Example #7
Source File: MultiPartParserDefinition.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private MultiPartUploadHandler(final HttpServerExchange exchange, final String boundary, final long maxIndividualFileSize, final String defaultEncoding) {
    this.exchange = exchange;
    this.maxIndividualFileSize = maxIndividualFileSize;
    this.defaultEncoding = defaultEncoding;
    this.data = new FormData(exchange.getConnection().getUndertowOptions().get(UndertowOptions.MAX_PARAMETERS, 1000));
    String charset = defaultEncoding;
    String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
    if (contentType != null) {
        String value = Headers.extractQuotedValueFromHeader(contentType, "charset");
        if (value != null) {
            charset = value;
        }
    }
   this.parser = MultipartParser.beginParse(exchange.getConnection().getByteBufferPool(), this, boundary.getBytes(StandardCharsets.US_ASCII), charset);

}
 
Example #8
Source File: SignEd25519Handler.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) {
    JsonObject body = parseJsonObject(exchange);

    _MatrixID mxid = MatrixID.asAcceptable(GsonUtil.getStringOrThrow(body, "mxid"));
    String token = GsonUtil.getStringOrThrow(body, "token");
    String privKey = GsonUtil.getStringOrThrow(body, "private_key");

    IThreePidInviteReply reply = invMgr.getInvite(token, privKey);
    _MatrixID sender = reply.getInvite().getSender();

    JsonObject res = new JsonObject();
    res.addProperty("token", token);
    res.addProperty("sender", sender.getId());
    res.addProperty("mxid", mxid.getId());
    res.add("signatures", signMgr.signMessageGson(cfg.getServer().getName(), MatrixJson.encodeCanonical(res)));

    log.info("Signed data for invite using token {}", token);
    respondJson(exchange, res);
}
 
Example #9
Source File: Oauth2UserGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    Deque<String> userIdDeque = exchange.getQueryParameters().get("userId");
    String userId = userIdDeque == null? "%" : userIdDeque.getFirst() + "%";
    int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1;
    Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize");
    int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst());

    LikePredicate likePredicate = new LikePredicate("userId", userId);

    PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new UserComparator(), pageSize);
    pagingPredicate.setPage(page);
    Collection<User> values = users.values(pagingPredicate);

    for (User value : values) {
        value.setPassword(null);
    }
    exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values));
    processAudit(exchange);
}
 
Example #10
Source File: Oauth2ClientGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    Deque<String> clientNameDeque = exchange.getQueryParameters().get("clientName");
    String clientName = clientNameDeque == null? "%" : clientNameDeque.getFirst() + "%";
    int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1;
    Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize");
    int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst());

    LikePredicate likePredicate = new LikePredicate("clientName", clientName);

    PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new ClientComparator(), pageSize);
    pagingPredicate.setPage(page);
    Collection<Client> values = clients.values(pagingPredicate);

    List results = new ArrayList();
    for (Client value : values) {
        Client c = Client.copyClient(value);
        c.setClientSecret(null);
        results.add(c);
    }
    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(results));
    processAudit(exchange);
}
 
Example #11
Source File: OpenApiHandler.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
public static Map<String, ?> getHeaderParameters(final HttpServerExchange exchange, final boolean deserializedValueOnly){
	Map<String, Object> deserializedHeaderParamters = exchange.getAttachment(DESERIALIZED_HEADER_PARAMETERS);
	
	if (!deserializedValueOnly) {
		HeaderMap headers = exchange.getRequestHeaders();
		
		if (null==headers) {
			return Collections.emptyMap();
		}
		
		Map<String, HeaderValues> headerMap = new HashMap<>();
		
		for (HttpString headerName: headers.getHeaderNames()) {
			headerMap.put(headerName.toString(), headers.get(headerName));
		}
		
		return mergeMaps(deserializedHeaderParamters, headerMap);
	}
	
	return nonNullMap(deserializedHeaderParamters);
}
 
Example #12
Source File: CorsUtilTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * Test of defaultOrigin method, of class CorsUtil.
 */
@Test
public void testDefaultOrigin() {
    HeaderMap headerMap = new HeaderMap();
    headerMap.add(HOST, "localhost:80");
    HttpServerExchange exchange = new HttpServerExchange(null, headerMap, new HeaderMap(), 10);
    exchange.setRequestScheme("http");
    assertThat(CorsUtil.defaultOrigin(exchange), is("http://localhost"));
    headerMap.clear();
    headerMap.add(HOST, "www.example.com:8080");
    assertThat(CorsUtil.defaultOrigin(exchange), is("http://www.example.com:8080"));
    headerMap.clear();
    headerMap.add(HOST, "www.example.com:443");
    exchange.setRequestScheme("https");
    assertThat(CorsUtil.defaultOrigin(exchange), is("https://www.example.com"));
    headerMap.clear();
    exchange.setRequestScheme("http");
    headerMap.add(HOST, "[::1]:80");
    assertThat(CorsUtil.defaultOrigin(exchange), is("http://[::1]"));
}
 
Example #13
Source File: ExchangeAttributes.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static String  resolve(final HttpServerExchange exchange, final ExchangeAttribute[] attributes) {
    final StringBuilder result = new StringBuilder();
    for (int i = 0; i < attributes.length; ++i) {
        final String str = attributes[i].readAttribute(exchange);
        if (str != null) {
            result.append(str);
        }
    }
    return result.toString();
}
 
Example #14
Source File: PingHandler.java    From galeb with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    boolean hasNoUpdate = exchange.getQueryParameters().containsKey("noupdate");
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
    exchange.getResponseHeaders().put(Headers.SERVER, "GALEB");
    String statusBody = getStatusBody(hasNoUpdate);
    exchange.setStatusCode(StatusCodes.OK);
    exchange.getResponseSender().send(statusBody);
    if (!hasNoUpdate) {
        updaterService.sched();
    }
    exchange.endExchange();
}
 
Example #15
Source File: RequestUtilsTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetRequestParametersConcurrent() {
    MatcherAssert.assertThat(t -> {
        // given
        String one = UUID.randomUUID().toString();
        String two = UUID.randomUUID().toString();
        Deque<String> paramsOne = new LinkedList<>();
        paramsOne.push(one);
        Deque<String> paramsTwo = new LinkedList<>();
        paramsTwo.push(two);

        Map<String, Deque<String>> queryParameters = new HashMap<>();
        Map<String, Deque<String>> pathParameters = new HashMap<>();
        queryParameters.put("first", paramsOne);
        pathParameters.put("second", paramsTwo);

        HttpServerExchange mockedExchange = Mockito.mock(HttpServerExchange.class);

        // when
        when(mockedExchange.getQueryParameters()).thenReturn(queryParameters);
        when(mockedExchange.getPathParameters()).thenReturn(pathParameters);
        Map<String, String> requestParameters = RequestUtils.getRequestParameters(mockedExchange);


        return requestParameters != null && requestParameters.get("first").equals(one) && requestParameters.get("second").equals(two);
    }, new RunsInThreads<>(new AtomicInteger(), TestExtension.THREADS));
}
 
Example #16
Source File: DomainApiHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private ModelNode convertPostRequest(HttpServerExchange exchange, boolean encode) throws IOException {
    InputStream in = new ChannelInputStream(exchange.getRequestChannel());
    try {
        return encode ? ModelNode.fromBase64(in) : ModelNode.fromJSONStream(in);
    } finally {
        IoUtils.safeClose(in);
    }
}
 
Example #17
Source File: ChunkedRequestTrailersTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setup() {
    final BlockingHandler blockingHandler = new BlockingHandler();
    existing = DefaultServer.getUndertowOptions();
    DefaultServer.setUndertowOptions(UndertowOptionMap.create(UndertowOptions.ALWAYS_SET_DATE, false));
    DefaultServer.setRootHandler(blockingHandler);
    blockingHandler.setRootHandler(new HttpHandler() {
        @Override
        public void handleRequest(final HttpServerExchange exchange) {
            try {
                final OutputStream outputStream = exchange.getOutputStream();
                final InputStream inputStream = exchange.getInputStream();
                String m = HttpClientUtils.readResponse(inputStream);
                Assert.assertEquals("abcdefghi", m);

                HttpHeaders headers = exchange.getAttachment(HttpAttachments.REQUEST_TRAILERS);
                for (Map.Entry<String, String> header : headers) {
                    for (String val : headers.getAll(header.getKey())) {
                        outputStream.write(header.getKey().getBytes(StandardCharsets.UTF_8));
                        outputStream.write(": ".getBytes());
                        outputStream.write(val.getBytes());
                        outputStream.write("\r\n".getBytes());
                    }
                }

                inputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    });
}
 
Example #18
Source File: HandleRequestInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    Object ret) {
    if (isExceptionHandler(objInst)) {
        HttpServerExchange exchange = (HttpServerExchange) allArguments[0];

        if (Config.Plugin.Light4J.TRACE_HANDLER_CHAIN && !exchange.isInIoThread()) {
            ContextManager.stopSpan();
        }
    } else if (Config.Plugin.Light4J.TRACE_HANDLER_CHAIN && (isMiddlewareHandler(objInst) || isBusinessHandler(objInst))) {
        ContextManager.stopSpan();
    }
    return ret;
}
 
Example #19
Source File: UndertowHttpHandler.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
private String clientIP(HttpServerExchange exchange) {
    String xForwardedFor = exchange.getRequestHeaders().getFirst(Headers.X_FORWARDED_FOR_STRING);

    if (Strings.isNullOrEmpty(xForwardedFor)) {
        return exchange.getSourceAddress().getAddress().getHostAddress();
    }
    int index = xForwardedFor.indexOf(',');
    if (index > 0)
        return xForwardedFor.substring(0, index);
    return xForwardedFor;
}
 
Example #20
Source File: VersionPath.java    From PYX-Reloaded with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) {
    exchange.startBlocking();
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "application/json");
    exchange.getResponseSender().send(json);
}
 
Example #21
Source File: ServerInfoGetHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
public Map<String, Object> getHost(HttpServerExchange exchange) {
    Map<String, Object> hostMap = new LinkedHashMap<>();
    String ip = "unknown";
    String hostname = "unknown";
    InetAddress inetAddress = Util.getInetAddress();
    ip = inetAddress.getHostAddress();
    hostname = inetAddress.getHostName();
    hostMap.put("ip", ip);
    hostMap.put("hostname", hostname);
    hostMap.put("dns", exchange.getSourceAddress().getHostName());
    return hostMap;
}
 
Example #22
Source File: TaskIDE.java    From greycat with Apache License 2.0 5 votes vote down vote up
public static void attach(final WSServer server, final Graph graph) {
    server.addHandler("taskide", new ResourceHandler(new ClassPathResourceManager(TaskIDE.class.getClassLoader(), "taskide")).addWelcomeFiles("index.html").setDirectoryListingEnabled(false));
    server.addHandler("actionregistry", new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange httpServerExchange) throws Exception {
            Buffer builder = new HeapBuffer();
            builder.writeString("[");
            ActionRegistry registry = graph.actionRegistry();
            ActionDeclaration[] declarations = registry.declarations();
            for (int i = 0; i < declarations.length; i++) {
                ActionDeclaration declaration = declarations[i];
                if (i != 0) {
                    builder.writeString(",");
                }
                builder.writeString("{\"name\":");
                TaskHelper.serializeString(declaration.name(), builder, false);
                builder.writeString(",\"description\":");
                TaskHelper.serializeString(declaration.description(), builder, false);
                byte[] params = declaration.params();
                if (params != null) {
                    builder.writeString(",\"params\":[");
                    for (int j = 0; j < params.length; j++) {
                        if (j != 0) {
                            builder.writeString(",");
                        }
                        TaskHelper.serializeString(Type.typeName(params[j]), builder, false);
                    }
                    builder.writeString("]");
                }
                builder.writeString("}");
            }
            builder.writeString("]");
            httpServerExchange.getResponseHeaders().add(new HttpString("Access-Control-Allow-Origin"), "*");
            httpServerExchange.setStatusCode(StatusCodes.OK);
            httpServerExchange.getResponseSender().send(builder.toString());
        }
    });

}
 
Example #23
Source File: ServletContextImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void updateSessionAccessTime(final HttpServerExchange exchange) {
    HttpSessionImpl httpSession = getSession(exchange, false);
    if (httpSession != null) {
        Session underlyingSession;
        if (System.getSecurityManager() == null) {
            underlyingSession = httpSession.getSession();
        } else {
            underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(httpSession));
        }
        underlyingSession.requestDone(exchange);
    }
}
 
Example #24
Source File: HTTPErrorHandler.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
private Response defaultErrorResponse(Throwable e, HttpServerExchange exchange, ActionLog actionLog) {
    HTTPStatus status = httpStatus(e);

    HeaderMap headers = exchange.getRequestHeaders();
    String accept = headers.getFirst(Headers.ACCEPT);

    if (accept != null && accept.contains(ContentType.APPLICATION_JSON.mediaType)) {
        String userAgent = headers.getFirst(Headers.USER_AGENT);
        return Response.bean(errorResponse(e, userAgent, actionLog.id)).status(status);
    } else {
        return Response.text(errorHTML(e, actionLog.id)).status(status).contentType(ContentType.TEXT_HTML);
    }
}
 
Example #25
Source File: ServletConfidentialityConstraintHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean confidentialityRequired(HttpServerExchange exchange) {
    TransportGuaranteeType transportGuarantee = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getTransportGuarenteeType();

    // TODO - We may be able to add more flexibility here especially with authentication mechanisms such as Digest for
    // INTEGRAL - for now just use SSL.
    return (TransportGuaranteeType.CONFIDENTIAL == transportGuarantee || TransportGuaranteeType.INTEGRAL == transportGuarantee);
}
 
Example #26
Source File: ByteRangeHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void beforeCommit(HttpServerExchange exchange) {
    if(!exchange.getResponseHeaders().contains(Headers.ACCEPT_RANGES)) {
        if (exchange.getResponseHeaders().contains(Headers.CONTENT_LENGTH)) {
            exchange.getResponseHeaders().put(Headers.ACCEPT_RANGES, "bytes");
        } else {
            exchange.getResponseHeaders().put(Headers.ACCEPT_RANGES, "none");
        }
    }
}
 
Example #27
Source File: ServletRequestedSessionIdValidAttribute.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    ServletRequestContext context = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if (context != null) {
        ServletRequest req = context.getServletRequest();
        if (req instanceof HttpServletRequest) {
            return Boolean.toString(((HttpServletRequest) req).isRequestedSessionIdValid());
        }
    }
    return null;
}
 
Example #28
Source File: HttpContinueAcceptingHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if(HttpContinue.requiresContinueResponse(exchange)) {
        if(accept.resolve(exchange)) {
            exchange.send1ContinueIfRequired();
            next.handleRequest(exchange);
        } else {
            HttpContinue.rejectExchange(exchange);
        }
    } else {
        next.handleRequest(exchange);
    }
}
 
Example #29
Source File: FormDataParserTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void blockingParser() throws Exception {
    final BlockingHandler blocking = new BlockingHandler();

    blocking.setRootHandler(new HttpHandler() {

        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            final FormParserFactory parserFactory = FormParserFactory.builder().build();
            final FormDataParser parser = parserFactory.createParser(exchange);
            try {
                FormData data = parser.parseBlocking();
                Iterator<String> it = data.iterator();
                while (it.hasNext()) {
                    String fd = it.next();
                    for (FormData.FormValue val : data.get(fd)) {
                        exchange.addResponseHeader("res", fd + ":" + val.getValue());
                    }
                }
            } catch (IOException e) {
                exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
            }
        }
    });
    DefaultServer.setRootHandler(blocking);
    testCase();
}
 
Example #30
Source File: DivolteEvent.java    From divolte-collector with Apache License 2.0 5 votes vote down vote up
static DivolteEvent createBrowserEvent(
        final HttpServerExchange originatingExchange,
        final boolean corruptEvent,
        final DivolteIdentifier partyCookie,
        final DivolteIdentifier sessionCookie,
        final String eventId,
        final Instant requestStartTime,
        final Instant clientUtcOffset,
        final boolean newPartyId,
        final boolean firstInSession,
        final Optional<String> eventType,
        final Supplier<Optional<JsonNode>> eventParametersProducer,
        final BrowserEventData browserEvent) {
    return new DivolteEvent(
            originatingExchange,
            corruptEvent,
            partyCookie,
            sessionCookie,
            eventId,
            BrowserSource.EVENT_SOURCE_NAME,
            requestStartTime,
            clientUtcOffset,
            newPartyId,
            firstInSession,
            eventType,
            eventParametersProducer,
            Optional.of(browserEvent),
            Optional.empty()
            );
}