Java Code Examples for io.undertow.util.Methods

The following examples show how to use io.undertow.util.Methods. These examples are extracted from open source projects. 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 Project: SikuliX1   Author: RaiMan   File: SikulixServer.java    License: MIT License 6 votes vote down vote up
public ScriptsCommand(TasksCommand tasks) {
  this.taskId = new AtomicInteger();
  this.tasks = tasks;
  this.run.addExceptionHandler(Throwable.class, getExceptionHttpHandler());
  getRouting()
      .add(Methods.GET, "/scripts", 
          getScripts)
      .add(Methods.GET, "/scripts/*",
          Predicates.regex(RelativePathAttribute.INSTANCE, "^/scripts/[^/].*/run$"),
          run)
      .add(Methods.POST, "/scripts/*",
          Predicates.regex(RelativePathAttribute.INSTANCE, "^/scripts/[^/].*/run$"),
          run)
      .add(Methods.POST, "/scripts/*",
          Predicates.regex(RelativePathAttribute.INSTANCE, "^/scripts/[^/].*/task$"),
          task)
      .add(Methods.GET, "/scripts/*",
          Predicates.regex(RelativePathAttribute.INSTANCE, "^/scripts/[^/].*/tasks(/.*)*$"),
          delegate)
      .add(Methods.PUT, "/scripts/*",
          Predicates.regex(RelativePathAttribute.INSTANCE, "^/scripts/[^/].*/tasks(/.*)*$"),
          delegate)
      .add(Methods.GET, "/scripts/*", 
          Predicates.regex(RelativePathAttribute.INSTANCE, "^/scripts/([^/].*)?[^/]$"),
          getScript);
}
 
Example #2
Source Project: proteus   Author: noboomu   File: AssetsService.java    License: Apache License 2.0 6 votes vote down vote up
public RoutingHandler get()
{
    RoutingHandler router = new RoutingHandler();
    final String assetsPath = serviceConfig.getString("path");
    final String assetsDirectoryName = serviceConfig.getString("dir");
    final Integer assetsCacheTime = serviceConfig.getInt("cache.time");
    final FileResourceManager fileResourceManager = new FileResourceManager(Paths.get(assetsDirectoryName).toFile());

    router.add(Methods.GET,
            assetsPath + "/*",
            io.undertow.Handlers.rewrite("regex('" + assetsPath + "/(.*)')",
                    "/$1",
                    getClass().getClassLoader(),
                    new ResourceHandler(fileResourceManager).setCachable(TruePredicate.instance()).setCacheTime(assetsCacheTime)));

    this.registeredEndpoints.add(EndpointInfo.builder()
            .withConsumes("*/*")
            .withProduces("*/*")
            .withPathTemplate(assetsPath)
            .withControllerName(this.getClass().getSimpleName())
            .withMethod(Methods.GET)
            .build());

    return router;
}
 
Example #3
Source Project: lams   Author: lamsfoundation   File: HttpServletRequestImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public Enumeration<String> getParameterNames() {
    if (queryParameters == null) {
        queryParameters = exchange.getQueryParameters();
    }
    final Set<String> parameterNames = new HashSet<>(queryParameters.keySet());
    if (exchange.getRequestMethod().equals(Methods.POST)) {
        final FormData parsedFormData = parseFormData();
        if (parsedFormData != null) {
            Iterator<String> it = parsedFormData.iterator();
            while (it.hasNext()) {
                String name = it.next();
                for(FormData.FormValue param : parsedFormData.get(name)) {
                    if(!param.isFile()) {
                        parameterNames.add(name);
                        break;
                    }
                }
            }
        }
    }
    return new IteratorEnumeration<>(parameterNames.iterator());
}
 
Example #4
Source Project: wildfly-camel   Author: wildfly-extras   File: CamelUndertowHostService.java    License: Apache License 2.0 6 votes vote down vote up
boolean remove(String method, String path) {
    MethodPathKey key = new MethodPathKey(method, path);
    boolean result;
    synchronized (paths) {
        MethodPathValue value = paths.get(key);
        if (value != null) {
            value.removeRef();
            if (value.refCount <= 0) {
                paths.remove(key);
            }
        }
        result = paths.isEmpty();
    }
    delegate.remove(Methods.fromString(method), path);
    return result;
}
 
Example #5
Source Project: lams   Author: lamsfoundation   File: ResourceHandler.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (exchange.getRequestMethod().equals(Methods.GET) ||
            exchange.getRequestMethod().equals(Methods.POST)) {
        serveResource(exchange, true);
    } else if (exchange.getRequestMethod().equals(Methods.HEAD)) {
        serveResource(exchange, false);
    } else {
        if (KNOWN_METHODS.contains(exchange.getRequestMethod())) {
            exchange.setStatusCode(StatusCodes.METHOD_NOT_ALLOWED);
            exchange.getResponseHeaders().add(Headers.ALLOW,
                    String.join(", ", Methods.GET_STRING, Methods.HEAD_STRING, Methods.POST_STRING));
        } else {
            exchange.setStatusCode(StatusCodes.NOT_IMPLEMENTED);
        }
        exchange.endExchange();
    }
}
 
Example #6
Source Project: lams   Author: lamsfoundation   File: AllowedContentEncodings.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public StreamSinkConduit wrap(final ConduitFactory<StreamSinkConduit> factory, final HttpServerExchange exchange) {
    if (exchange.getResponseHeaders().contains(Headers.CONTENT_ENCODING)) {
        //already encoded
        return factory.create();
    }
    //if this is a zero length response we don't want to encode
    if (exchange.getResponseContentLength() != 0
            && exchange.getStatusCode() != StatusCodes.NO_CONTENT
            && exchange.getStatusCode() != StatusCodes.NOT_MODIFIED) {
        EncodingMapping encoding = getEncoding();
        if (encoding != null) {
            exchange.getResponseHeaders().put(Headers.CONTENT_ENCODING, encoding.getName());
            if (exchange.getRequestMethod().equals(Methods.HEAD)) {
                //we don't create an actual encoder for HEAD requests, but we set the header
                return factory.create();
            } else {
                return encoding.getEncoding().getResponseWrapper().wrap(factory, exchange);
            }
        }
    }
    return factory.create();
}
 
Example #7
Source Project: lams   Author: lamsfoundation   File: ChannelUpgradeHandler.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final List<String> upgradeStrings = exchange.getRequestHeaders().get(Headers.UPGRADE);
    if (upgradeStrings != null && exchange.getRequestMethod().equals(Methods.GET)) {
        for (String string : upgradeStrings) {
            final List<Holder> holders = handlers.get(string);
            if (holders != null) {
                for (Holder holder : holders) {
                    final HttpUpgradeListener listener = holder.listener;
                    if (holder.handshake != null) {
                        if (!holder.handshake.handleUpgrade(exchange)) {
                            //handshake did not match, try again
                            continue;
                        }
                    }

                    exchange.upgradeChannel(string,listener);
                    exchange.endExchange();
                    return;
                }
            }
        }
    }
    nonUpgradeHandler.handleRequest(exchange);
}
 
Example #8
Source Project: mangooio   Author: svenkubiak   File: AuthorizationControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testReadAuthorized() {
    //given
    TestBrowser instance = TestBrowser.open();
    TestResponse response = instance.to("/authorize/alice")
            .withHTTPMethod(Methods.GET.toString())
            .withDisabledRedirects()
            .execute();
    
    //given
    instance.to("/read")
        .withHTTPMethod(Methods.GET.toString())
        .execute();
    
    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContent(), equalTo("can read"));
}
 
Example #9
Source Project: light-rest-4j   Author: networknt   File: ResponseValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    if(server == null) {
        logger.info("starting server");
        TestValidateResponseHandler testValidateResponseHandler = new TestValidateResponseHandler();
        HttpHandler handler = Handlers.routing()
                .add(Methods.GET, "/v1/todoItems", testValidateResponseHandler);
        ValidatorHandler validatorHandler = new ValidatorHandler();
        validatorHandler.setNext(handler);
        handler = validatorHandler;

        BodyHandler bodyHandler = new BodyHandler();
        bodyHandler.setNext(handler);
        handler = bodyHandler;

        OpenApiHandler openApiHandler = new OpenApiHandler();
        openApiHandler.setNext(handler);
        handler = openApiHandler;

        server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(handler)
                .build();
        server.start();
    }
}
 
Example #10
Source Project: light-4j   Author: networknt   File: HandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void mixedPathsAndSource() {
    Handler.config.setPaths(Arrays.asList(
        mkPathChain(null, "/my-api/first", "post", "third"),
        mkPathChain(MockEndpointSource.class.getName(), null, null, "secondBeforeFirst", "third"),
        mkPathChain(null, "/my-api/second", "put", "third")
    ));
    Handler.init();

    Map<HttpString, PathTemplateMatcher<String>> methodToMatcher = Handler.methodToMatcherMap;

    PathTemplateMatcher<String> getMatcher = methodToMatcher.get(Methods.GET);
    PathTemplateMatcher.PathMatchResult<String> getFirst = getMatcher.match("/my-api/first");
    Assert.assertNotNull(getFirst);
    PathTemplateMatcher.PathMatchResult<String> getSecond = getMatcher.match("/my-api/second");
    Assert.assertNotNull(getSecond);
    PathTemplateMatcher.PathMatchResult<String> getThird = getMatcher.match("/my-api/third");
    Assert.assertNull(getThird);
}
 
Example #11
Source Project: mangooio   Author: svenkubiak   File: I18nControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWithI18nCookie() {
    //given
    TestBrowser browser = TestBrowser.open();
    TestResponse response = browser.withHTTPMethod(Methods.GET.toString()).to("/localize").execute();
    
    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getCookie(Default.I18N_COOKIE_NAME.toString()), not(nullValue()));
    
    //given
    response = browser.to("/translation").execute();
    
    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContent(), equalTo("welcome"));
}
 
Example #12
Source Project: spring-analysis-note   Author: Vip-Augus   File: UndertowXhrTransport.java    License: MIT License 5 votes vote down vote up
private void executeReceiveRequest(final TransportRequest transportRequest,
		final URI url, final HttpHeaders headers, final XhrClientSockJsSession session,
		final SettableListenableFuture<WebSocketSession> connectFuture) {

	if (logger.isTraceEnabled()) {
		logger.trace("Starting XHR receive request for " + url);
	}

	ClientCallback<ClientConnection> clientCallback = new ClientCallback<ClientConnection>() {
		@Override
		public void completed(ClientConnection connection) {
			ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(url.getPath());
			HttpString headerName = HttpString.tryFromString(HttpHeaders.HOST);
			request.getRequestHeaders().add(headerName, url.getHost());
			addHttpHeaders(request, headers);
			HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
			connection.sendRequest(request, createReceiveCallback(transportRequest,
					url, httpHeaders, session, connectFuture));
		}

		@Override
		public void failed(IOException ex) {
			throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
		}
	};

	this.httpClient.connect(clientCallback, url, this.worker, this.bufferPool, this.optionMap);
}
 
Example #13
Source Project: java-technology-stack   Author: codeEngraver   File: UndertowXhrTransport.java    License: MIT License 5 votes vote down vote up
private void executeReceiveRequest(final TransportRequest transportRequest,
		final URI url, final HttpHeaders headers, final XhrClientSockJsSession session,
		final SettableListenableFuture<WebSocketSession> connectFuture) {

	if (logger.isTraceEnabled()) {
		logger.trace("Starting XHR receive request for " + url);
	}

	ClientCallback<ClientConnection> clientCallback = new ClientCallback<ClientConnection>() {
		@Override
		public void completed(ClientConnection connection) {
			ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(url.getPath());
			HttpString headerName = HttpString.tryFromString(HttpHeaders.HOST);
			request.getRequestHeaders().add(headerName, url.getHost());
			addHttpHeaders(request, headers);
			HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
			connection.sendRequest(request, createReceiveCallback(transportRequest,
					url, httpHeaders, session, connectFuture));
		}

		@Override
		public void failed(IOException ex) {
			throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
		}
	};

	this.httpClient.connect(clientCallback, url, this.worker, this.bufferPool, this.optionMap);
}
 
Example #14
Source Project: mangooio   Author: svenkubiak   File: AdminControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testToolsAuthorized() {
    //given
    TestResponse response = login().to("/@admin/tools")
            .withHTTPMethod(Methods.GET.toString())
            .execute();
    
    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContentType(), equalTo(TEXT_HTML));
    assertThat(response.getContent(), containsString(TOOLS));
}
 
Example #15
Source Project: aion   Author: aionnetwork   File: AionUndertowRpcHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) {
    boolean isPost = Methods.POST.equals(exchange.getRequestMethod());
    boolean isOptions = Methods.OPTIONS.equals(exchange.getRequestMethod());

    // only support POST & OPTIONS requests
    if (!isPost && !isOptions) {
        exchange.setStatusCode(StatusCodes.METHOD_NOT_ALLOWED);
        exchange.setPersistent(false); // don't need to keep-alive connection in case of error.
        exchange.endExchange();
        return;
    }

    // respond to cors-preflight request
    if (corsEnabled && isOptions) {
        addCorsHeaders(exchange);
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
        exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, "0");
        exchange.getResponseSender().send("");
        return;
    }

    /** respond to rpc call; {@link io.Undertow.BlockingReceiverImpl#receiveFullString} */
    exchange.getRequestReceiver()
            .receiveFullString(
                    (_exchange, body) -> {
                        if (corsEnabled) addCorsHeaders(_exchange);
                        _exchange
                                .getResponseHeaders()
                                .put(Headers.CONTENT_TYPE, "application/json");
                        _exchange.getResponseSender().send(rpcProcessor.process(body));
                    });
}
 
Example #16
Source Project: mangooio   Author: svenkubiak   File: RequestUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIsPost() {
    // given
    HttpServerExchange mockedExchange = Mockito.mock(HttpServerExchange.class);

    // when
    when(mockedExchange.getRequestMethod()).thenReturn(Methods.POST);
    boolean postPutPatch = RequestUtils.isPostPutPatch(mockedExchange);

    // then
    assertThat(postPutPatch, equalTo(true));
}
 
Example #17
Source Project: mangooio   Author: svenkubiak   File: AdminControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testToolsTwoFactorAuthorized() {
    //given
    TestResponse response = login().to("/@admin/tools")
            .withHTTPMethod(Methods.GET.toString())
            .execute();
    
    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContentType(), equalTo(TEXT_HTML));
    assertThat(response.getContent(), containsString("Two Factor Authentication"));
}
 
Example #18
Source Project: SikuliX1   Author: RaiMan   File: SikulixServer.java    License: MIT License 5 votes vote down vote up
public GroupsCommand(ScriptsCommand scripts) {
  this.scripts = scripts;
  getRouting()
      .add(Methods.GET, "/groups", getGroups)
      .add(Methods.GET, "/groups/{name}", getSubTree)
      .add(Methods.GET, "/groups/{name}/*", delegate)
      .add(Methods.POST, "/groups/{name}/*", delegate)
      .add(Methods.PUT, "/groups/{name}/*", delegate);
}
 
Example #19
Source Project: divolte-collector   Author: divolte   File: JsonSource.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public PathHandler attachToPathHandler(final PathHandler pathHandler) {
    final HttpHandler onlyJsonHandler = new JsonContentHandler(handler);
    final HttpHandler onlyPostHandler = new AllowedMethodsHandler(onlyJsonHandler, Methods.POST);
    final PathHandler newPathHandler = pathHandler.addExactPath(eventPath, onlyPostHandler);
    logger.info("Registered source[{}] event handler: {}", sourceName, eventPath);
    return newPathHandler;
}
 
Example #20
Source Project: mangooio   Author: svenkubiak   File: RequestUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIsNonPostPutPatch() {
    // given
    HttpServerExchange mockedExchange = Mockito.mock(HttpServerExchange.class);

    // when
    when(mockedExchange.getRequestMethod()).thenReturn(Methods.GET);
    boolean postPutPatch = RequestUtils.isPostPutPatch(mockedExchange);

    // then
    assertThat(postPutPatch, equalTo(false));
}
 
Example #21
Source Project: thorntail   Author: thorntail   File: OpenApiHttpHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
 */
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (OAI.equalsIgnoreCase(exchange.getRequestPath()) && OpenApiDocument.INSTANCE.isSet()) {
        if (exchange.getRequestMethod().equals(Methods.GET)) {
            sendOai(exchange);
        } else if (exchange.getRequestMethod().equals(Methods.OPTIONS))  {
            sendPreflight(exchange);
        } else {
            next.handleRequest(exchange);
        }
    } else {
        next.handleRequest(exchange);
    }
}
 
Example #22
Source Project: lams   Author: lamsfoundation   File: Http2ReceiveListener.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Performs HTTP2 specification compliance check for headers and pseudo-headers of a current request.
 *
 * @param headers map of the request headers
 * @return true if check was successful, false otherwise
 */
private boolean checkRequestHeaders(HeaderMap headers) {
    // :method pseudo-header must be present always exactly one time;
    // HTTP2 request MUST NOT contain 'connection' header
    if (headers.count(METHOD) != 1 || headers.contains(Headers.CONNECTION)) {
        return false;
    }

    // if CONNECT type is used, then we expect :method and :authority to be present only;
    // :scheme and :path must not be present
    if (headers.get(METHOD).contains(Methods.CONNECT_STRING)) {
        if (headers.contains(SCHEME) || headers.contains(PATH) || headers.count(AUTHORITY) != 1) {
            return false;
        }
    // For other HTTP methods we expect that :scheme, :method, and :path pseudo-headers are
    // present exactly one time.
    } else if (headers.count(SCHEME) != 1 || headers.count(PATH) != 1) {
        return false;
    }

    // HTTP2 request MAY contain TE header but if so, then only with 'trailers' value.
    if (headers.contains(Headers.TE)) {
        for (String value : headers.get(Headers.TE)) {
            if (!value.equals("trailers")) {
                return false;
            }
        }
    }

    return true;
}
 
Example #23
Source Project: lams   Author: lamsfoundation   File: HttpServerConnection.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected StreamSinkConduit getSinkConduit(HttpServerExchange exchange, StreamSinkConduit conduit) {
    if(exchange.getRequestMethod().equals(Methods.CONNECT) && !connectHandled) {
        //make sure that any unhandled CONNECT requests result in a connection close
        exchange.setPersistent(false);
        exchange.getResponseHeaders().put(Headers.CONNECTION, "close");
    }
    return HttpTransferEncoding.createSinkConduit(exchange);
}
 
Example #24
Source Project: wildfly-core   Author: wildfly   File: DomainApiCheckHandler.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean commonChecks(HttpServerExchange exchange) throws Exception {
    // AS7-2284 If we are starting or stopping the web console won't be available, tell caller the service is unavailable and to try again
    // later. If "stopping" it's either a reload, in which case trying again will eventually succeed,
    // or it's a true process stop eventually the server will have stopped.
    if (!consoleAvailability.isAvailable()) {
        exchange.getResponseHeaders().add(Headers.RETRY_AFTER, "2"); //  2 secs is just a guesstimate
        Common.SERVICE_UNAVAIABLE.handleRequest(exchange);
        return false;
    }

    /*
     * Completely disallow OPTIONS - if the browser suspects this is a cross site request just reject it.
     */
    final HttpString requestMethod = exchange.getRequestMethod();
    if (!Methods.POST.equals(requestMethod) && !Methods.GET.equals(requestMethod)) {
        if (Methods.OPTIONS.equals(requestMethod)) {
            ROOT_LOGGER.debug("Request rejected due to 'OPTIONS' method which is not supported.");
        } else {
            ROOT_LOGGER.debug("Request rejected as method not one of (GET,POST).");
        }
        Common.METHOD_NOT_ALLOWED_HANDLER.handleRequest(exchange);
        return false;
    }

    /*
     *  Origin check, if it is set the Origin header should match the Host otherwise reject the request.
     *
     *  This check is for cross site scripted GET and POST requests.
     */
    final HeaderMap headers = exchange.getRequestHeaders();
    if (headers.contains(Headers.ORIGIN)) {
       return matchOrigin(exchange, allowedOrigins) != null;
    }
    return true;
}
 
Example #25
Source Project: lams   Author: lamsfoundation   File: DirectoryUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Serve static resource for the directory listing
 *
 * @param exchange The exchange
 * @return true if resources were served
 */
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;
}
 
Example #26
Source Project: lams   Author: lamsfoundation   File: MCMPWebManager.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void handleRequest(HttpString method, HttpServerExchange exchange) throws Exception {
    if (!Methods.GET.equals(method)) {
        super.handleRequest(method, exchange);
        return;
    }

    // Process the request
    processRequest(exchange);
}
 
Example #27
Source Project: lams   Author: lamsfoundation   File: ConfiguredPushHandler.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if(exchange.getConnection().isPushSupported()) {
        PathMatcher.PathMatch<String[]> result = pathMatcher.match(exchange.getRelativePath());
        if(result != null) {
            String[] value = result.getValue();
            for(int i = 0; i < value.length; ++i) {
                exchange.getConnection().pushResource(value[i], Methods.GET, requestHeaders);
            }
        }
    }
    next.handleRequest(exchange);
}
 
Example #28
Source Project: lams   Author: lamsfoundation   File: HttpTraceHandler.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if(exchange.getRequestMethod().equals(Methods.TRACE)) {
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "message/http");
        StringBuilder body = new StringBuilder("TRACE ");
        body.append(exchange.getRequestURI());
        if(!exchange.getQueryString().isEmpty()) {
            body.append('?');
            body.append(exchange.getQueryString());
        }
        body.append(' ');
        body.append(exchange.getProtocol().toString());
        body.append("\r\n");
        for(HeaderValues header : exchange.getRequestHeaders()) {
            for(String value : header) {
                body.append(header.getHeaderName());
                body.append(": ");
                body.append(value);
                body.append("\r\n");
            }
        }
        body.append("\r\n");
        exchange.getResponseSender().send(body.toString());
    } else {
        handler.handleRequest(exchange);
    }
}
 
Example #29
Source Project: light-4j   Author: networknt   File: ConsulClientImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void unregisterService(String serviceId, String token) {
	String path = "/v1/agent/service/deregister/" + serviceId;
	try {
		ConsulConnection connection = getConnection(UNREGISTER_CONNECTION_KEY + Thread.currentThread().getId());
           final AtomicReference<ClientResponse> reference = connection.send(Methods.PUT, path, token, null);
           int statusCode = reference.get().getResponseCode();
           if(statusCode >= UNUSUAL_STATUS_CODE){
               logger.error("Failed to unregister on Consul, body = {}", reference.get().getAttachment(Http2Client.RESPONSE_BODY));
           }
	} catch (Exception e) {
		logger.error("Failed to unregister on Consul, Exception:", e);
	}
}
 
Example #30
Source Project: spring4-understanding   Author: langtianya   File: UndertowXhrTransport.java    License: Apache License 2.0 5 votes vote down vote up
private void executeReceiveRequest(final TransportRequest transportRequest,
		final URI url, final HttpHeaders headers, final XhrClientSockJsSession session,
		final SettableListenableFuture<WebSocketSession> connectFuture) {

	if (logger.isTraceEnabled()) {
		logger.trace("Starting XHR receive request for " + url);
	}

	ClientCallback<ClientConnection> clientCallback = new ClientCallback<ClientConnection>() {
		@Override
		public void completed(ClientConnection connection) {
			ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(url.getPath());
			HttpString headerName = HttpString.tryFromString(HttpHeaders.HOST);
			request.getRequestHeaders().add(headerName, url.getHost());
			addHttpHeaders(request, headers);
			HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
			connection.sendRequest(request, createReceiveCallback(transportRequest,
					url, httpHeaders, session, connectFuture));
		}

		@Override
		public void failed(IOException ex) {
			throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
		}
	};

	this.undertowBufferSupport.httpClientConnect(this.httpClient, clientCallback, url, worker, this.optionMap);
}