Java Code Examples for io.undertow.util.HeaderMap#put()

The following examples show how to use io.undertow.util.HeaderMap#put() . 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: CorsHandler.java    From pivotal-bank-demo with Apache License 2.0 7 votes vote down vote up
private boolean setOrigin(String origin, HeaderMap responseHeaders) {
  if ("null".equals(origin)) {
    responseHeaders.put(ACCESS_CONTROL_ALLOW_ORIGIN, "null");
    return true;
  }
  if (wildcardOrigin) {
    responseHeaders.put(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    return true;
  } else if (allowedOrigins.contains(origin)) {
    responseHeaders.put(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
    return true;
  }
  if (logger.isLoggable(Level.FINE)) {
    logger.fine(origin + " is not an allowed origin: " + allowedOrigins);
  }
  return false;
}
 
Example 2
Source File: CorsHandler.java    From pivotal-bank-demo with Apache License 2.0 6 votes vote down vote up
/** Statically allows headers used by the api */
void handlePreflight(HttpServerExchange exchange) {
  HeaderMap requestHeaders = exchange.getRequestHeaders();
  String origin = requestHeaders.getFirst(ORIGIN);
  String method = requestHeaders.getFirst(ACCESS_CONTROL_REQUEST_METHOD);
  String requestedHeaders = requestHeaders.getFirst(ACCESS_CONTROL_REQUEST_HEADERS);
  HeaderMap responseHeaders = exchange.getResponseHeaders();

  responseHeaders.put(VARY,
    "origin,access-control-request-method,access-control-request-headers");
  if (
    ("POST".equals(method) || "GET".equals(method))
      && requestedHeadersAllowed(requestedHeaders)
      && setOrigin(origin, responseHeaders)
    ) {
    responseHeaders.put(ACCESS_CONTROL_ALLOW_METHODS, method);
    if (requestedHeaders != null) {
      responseHeaders.put(ACCESS_CONTROL_ALLOW_HEADERS, requestedHeaders);
    }
  }
}
 
Example 3
Source File: CRLRule.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    String fullFile = AbstractX509AuthenticationTest.getAuthServerHome() + File.separator + crlFileName;
    InputStream is = new FileInputStream(new File(fullFile));

    final byte[] responseBytes = IOUtils.toByteArray(is);

    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    responseHeaders.put(Headers.CONTENT_TYPE, "application/pkix-crl");
    // TODO: Add caching support? CRLs provided by well-known CA usually adds them

    final Sender responseSender = exchange.getResponseSender();
    responseSender.send(ByteBuffer.wrap(responseBytes));

    exchange.endExchange();
}
 
Example 4
Source File: SymjaServer.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
	String jsonStr;
	HeaderMap responseHeaders = exchange.getResponseHeaders();
	responseHeaders.put(new HttpString("Access-Control-Allow-Origin"), "*");
	responseHeaders.put(Headers.CONTENT_TYPE, "application/json");

	Map<String, Deque<String>> queryParameters = exchange.getQueryParameters();
	String appid = getAppID(queryParameters, "appid");
	if (appid != null) {
		if (appid.equals("DEMO")) {
			String inputStr = SymjaServer.getParam(queryParameters, "input", "i", "");
			String[] formformatStrs = SymjaServer.getParams(queryParameters, "format", "f", Pods.PLAIN_STR);
			int formats = Pods.internFormat(formformatStrs);
			ObjectNode messageJSON = Pods.createResult(inputStr, formats);
			jsonStr = messageJSON.toString();
		} else {
			jsonStr = Pods.errorJSONString("1", "Invalid appid");
		}
	} else {
		jsonStr = Pods.errorJSONString("2", "Appid missing");
	}
	exchange.getResponseSender().send(jsonStr);
}
 
Example 5
Source File: HttpTransferEncoding.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static StreamSinkConduit handleExplicitTransferEncoding(HttpServerExchange exchange, StreamSinkConduit channel, ConduitListener<StreamSinkConduit> finishListener, HeaderMap responseHeaders, String transferEncodingHeader, boolean headRequest) {
    HttpString transferEncoding = new HttpString(transferEncodingHeader);
    if (transferEncoding.equals(Headers.CHUNKED)) {
        if (headRequest) {
            return channel;
        }
        Boolean preChunked = exchange.getAttachment(HttpAttachments.PRE_CHUNKED_RESPONSE);
        if(preChunked != null && preChunked) {
            return new PreChunkedStreamSinkConduit(channel, finishListener, exchange);
        } else {
            return new ChunkedStreamSinkConduit(channel, exchange.getConnection().getByteBufferPool(), true, !exchange.isPersistent(), responseHeaders, finishListener, exchange);
        }
    } else {

        if (headRequest) {
            return channel;
        }
        log.trace("Cancelling persistence because response is identity with no content length");
        // make it not persistent - very unfortunate for the next request handler really...
        exchange.setPersistent(false);
        responseHeaders.put(Headers.CONNECTION, Headers.CLOSE.toString());
        return new FinishableStreamSinkConduit(channel, terminateResponseListener(exchange));
    }
}
 
Example 6
Source File: DomainUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void writeResponse(final HttpServerExchange exchange, final int status, ModelNode response,
        OperationParameter operationParameter) {

    exchange.setStatusCode(status);

    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    final String contentType = operationParameter.isEncode() ? Common.APPLICATION_DMR_ENCODED : Common.APPLICATION_JSON;
    responseHeaders.put(Headers.CONTENT_TYPE, contentType + "; charset=" + Common.UTF_8);

    writeCacheHeaders(exchange, status, operationParameter);

    if (operationParameter.isGet() && status == 200) {
        // For GET request the response is purely the model nodes result. The outcome
        // is not send as part of the response but expressed with the HTTP status code.
        response = response.get(RESULT);
    }
    try {
        byte[] data = getResponseBytes(response, operationParameter);
        responseHeaders.put(Headers.CONTENT_LENGTH, data.length);
        exchange.getResponseSender().send(ByteBuffer.wrap(data));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
Source File: CorsHandler.java    From pivotal-bank-demo with Apache License 2.0 5 votes vote down vote up
boolean validateOrigin(HttpServerExchange exchange) {
  HeaderMap responseHeaders = exchange.getResponseHeaders();
  responseHeaders.put(VARY, "origin");
  String origin = exchange.getRequestHeaders().getFirst(ORIGIN);
  if (origin == null) return true; // just vary
  return setOrigin(origin, responseHeaders);
}
 
Example 8
Source File: StaticHeadersHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
void apply(HttpServerExchange exchange, Predicate<String> putHeader) {
    HeaderMap headers = exchange.getResponseHeaders();
    if (putHeader.test(headerName.toString())) {
        headers.put(headerName, value);
    } else {
        headers.add(headerName, value);
    }
}
 
Example 9
Source File: DomainUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
static void writeCacheHeaders(final HttpServerExchange exchange, final int status, final OperationParameter operationParameter) {
    final HeaderMap responseHeaders = exchange.getResponseHeaders();

    // No need to send this in a 304
    // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
    if (operationParameter.getMaxAge() > 0 && status != 304) {
        responseHeaders.put(Headers.CACHE_CONTROL, "max-age=" + operationParameter.getMaxAge() + ", private, must-revalidate");
    }
    if (operationParameter.getEtag() != null) {
        responseHeaders.put(Headers.ETAG, operationParameter.getEtag().toString());
    }
}
 
Example 10
Source File: RequestUtilsTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsNonJsonRequest() {
    // given
    HttpServerExchange mockedExchange = Mockito.mock(HttpServerExchange.class);
    HeaderMap headerMap = new HeaderMap();
    headerMap.put(Header.CONTENT_TYPE.toHttpString(), MediaType.CSS_UTF_8.withoutParameters().toString());

    // when
    when(mockedExchange.getRequestHeaders()).thenReturn(headerMap);
    boolean isJson = RequestUtils.isJsonRequest(mockedExchange);

    // then
    assertThat(isJson, equalTo(false));
}
 
Example 11
Source File: RequestUtilsTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsJsonRequest() {
    // given
    HttpServerExchange mockedExchange = Mockito.mock(HttpServerExchange.class);
    HeaderMap headerMap = new HeaderMap();
    headerMap.put(Header.CONTENT_TYPE.toHttpString(), MediaType.JSON_UTF_8.withoutParameters().toString());

    // when
    when(mockedExchange.getRequestHeaders()).thenReturn(headerMap);
    boolean isJson = RequestUtils.isJsonRequest(mockedExchange);

    // then
    assertThat(isJson, equalTo(true));
}
 
Example 12
Source File: ResponseHandler.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
private void putHeaders(ResponseImpl response, HttpServerExchange exchange) {
    HeaderMap headers = exchange.getResponseHeaders();
    for (var entry : response.headers.entrySet()) {
        HttpString name = entry.getKey();
        String value = entry.getValue();
        headers.put(name, value);
        logger.debug("[response:header] {}={}", name, new FieldLogParam(name.toString(), value));
    }
}
 
Example 13
Source File: OpenApiHttpHandler.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private static void addCorsResponseHeaders(HttpServerExchange exchange) {
    HeaderMap headerMap = exchange.getResponseHeaders();
    headerMap.put(new HttpString("Access-Control-Allow-Origin"), "*");
    headerMap.put(new HttpString("Access-Control-Allow-Credentials"), "true");
    headerMap.put(new HttpString("Access-Control-Allow-Methods"), ALLOWED_METHODS);
    headerMap.put(new HttpString("Access-Control-Allow-Headers"), "Content-Type, Authorization");
    headerMap.put(new HttpString("Access-Control-Max-Age"), "86400");
}
 
Example 14
Source File: HttpServerExchange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Upgrade the channel to a raw socket. This method set the response code to 101, and then marks both the
 * request and response as terminated, which means that once the current request is completed the raw channel
 * can be obtained from {@link io.undertow.server.protocol.http.HttpServerConnection#getChannel()}
 *
 * @param productName the product name to report to the client
 * @throws IllegalStateException if a response or upgrade was already sent, or if the request body is already being
 *                               read
 */
public HttpServerExchange upgradeChannel(String productName, final HttpUpgradeListener listener) {
    if (!connection.isUpgradeSupported()) {
        throw UndertowMessages.MESSAGES.upgradeNotSupported();
    }
    UndertowLogger.REQUEST_LOGGER.debugf("Upgrading request %s", this);
    connection.setUpgradeListener(listener);
    setStatusCode(StatusCodes.SWITCHING_PROTOCOLS);
    final HeaderMap headers = getResponseHeaders();
    headers.put(Headers.UPGRADE, productName);
    headers.put(Headers.CONNECTION, Headers.UPGRADE_STRING);
    return this;
}
 
Example 15
Source File: HttpTransferEncoding.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static StreamSinkConduit handleResponseConduit(HttpServerExchange exchange, boolean headRequest, StreamSinkConduit channel, HeaderMap responseHeaders, ConduitListener<StreamSinkConduit> finishListener, String transferEncodingHeader) {

        if (transferEncodingHeader == null) {
            if (exchange.isHttp11()) {
                if (exchange.isPersistent()) {
                    responseHeaders.put(Headers.TRANSFER_ENCODING, Headers.CHUNKED.toString());

                    if (headRequest) {
                        return channel;
                    }
                    return new ChunkedStreamSinkConduit(channel, exchange.getConnection().getByteBufferPool(), true, !exchange.isPersistent(), responseHeaders, finishListener, exchange);
                } else {
                    if (headRequest) {
                        return channel;
                    }
                    return new FinishableStreamSinkConduit(channel, finishListener);
                }
            } else {
                exchange.setPersistent(false);
                responseHeaders.put(Headers.CONNECTION, Headers.CLOSE.toString());
                if (headRequest) {
                    return channel;
                }
                return new FinishableStreamSinkConduit(channel, finishListener);
            }
        } else {
            //moved outside because this is rarely used
            //and makes the method small enough to be inlined
            return handleExplicitTransferEncoding(exchange, channel, finishListener, responseHeaders, transferEncodingHeader, headRequest);
        }
    }
 
Example 16
Source File: UndertowHTTPDestinationTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void setUpDoService(boolean setRedirectURL,
                            boolean sendResponse,
                            boolean decoupled,
                            String method,
                            String query,
                            int status
                            ) throws Exception {

    is = EasyMock.createMock(ServletInputStream.class);
    os = EasyMock.createMock(ServletOutputStream.class);
    request = EasyMock.createMock(HttpServletRequest.class);
    response = EasyMock.createMock(HttpServletResponse.class);
    request.getMethod();
    EasyMock.expectLastCall().andReturn(method).atLeastOnce();
    request.getUserPrincipal();
    EasyMock.expectLastCall().andReturn(null).anyTimes();

    if (setRedirectURL) {
        policy.setRedirectURL(NOWHERE + "foo/bar");
        response.sendRedirect(EasyMock.eq(NOWHERE + "foo/bar"));
        EasyMock.expectLastCall();
        response.flushBuffer();
        EasyMock.expectLastCall();
        EasyMock.expectLastCall();
    } else {
        //getQueryString for if statement
        request.getQueryString();
        EasyMock.expectLastCall().andReturn(query);

        if ("GET".equals(method) && "?wsdl".equals(query)) {
            verifyGetWSDLQuery();
        } else { // test for the post
            EasyMock.expect(request.getAttribute(AbstractHTTPDestination.CXF_CONTINUATION_MESSAGE))
                .andReturn(null);


            EasyMock.expect(request.getInputStream()).andReturn(is);
            EasyMock.expect(request.getContextPath()).andReturn("/bar");
            EasyMock.expect(request.getServletPath()).andReturn("");
            EasyMock.expect(request.getPathInfo()).andReturn("/foo");
            EasyMock.expect(request.getRequestURI()).andReturn("/foo");
            EasyMock.expect(request.getRequestURL())
                .andReturn(new StringBuffer("http://localhost/foo")).anyTimes();
            EasyMock.expect(request.getCharacterEncoding()).andReturn(StandardCharsets.UTF_8.name());
            EasyMock.expect(request.getQueryString()).andReturn(query);
            EasyMock.expect(request.getHeader("Accept")).andReturn("*/*");
            EasyMock.expect(request.getContentType()).andReturn("text/xml charset=utf8").times(2);
            EasyMock.expect(request.getAttribute("http.service.redirection")).andReturn(null).anyTimes();

            HeaderMap httpFields = new HeaderMap();
            httpFields.add(new HttpString("content-type"), "text/xml");
            httpFields.add(new HttpString("content-type"), "charset=utf8");
            httpFields.put(new HttpString(UndertowHTTPDestinationTest.AUTH_HEADER),
                           UndertowHTTPDestinationTest.BASIC_AUTH);
            List<String> headers = new ArrayList<>();
            for (HttpString header : httpFields.getHeaderNames()) {
                headers.add(header.toString());
            }
            EasyMock.expect(request.getHeaderNames()).andReturn(Collections.enumeration(headers));
            request.getHeaders("content-type");
            EasyMock.expectLastCall().andReturn(Collections.enumeration(httpFields.get("content-type")));
            request.getHeaders(UndertowHTTPDestinationTest.AUTH_HEADER);
            EasyMock.expectLastCall().andReturn(Collections.enumeration(
                                                httpFields.get(UndertowHTTPDestinationTest.AUTH_HEADER)));

            EasyMock.expect(request.getInputStream()).andReturn(is);
            EasyMock.expectLastCall();
            response.flushBuffer();
            EasyMock.expectLastCall();
            if (sendResponse) {
                response.setStatus(status);
                EasyMock.expectLastCall();
                response.setContentType("text/xml charset=utf8");
                EasyMock.expectLastCall();
                response.addHeader(EasyMock.isA(String.class), EasyMock.isA(String.class));
                EasyMock.expectLastCall().anyTimes();
                response.setContentLength(0);
                EasyMock.expectLastCall().anyTimes();
                response.getOutputStream();
                EasyMock.expectLastCall().andReturn(os);
                response.getStatus();
                EasyMock.expectLastCall().andReturn(status).anyTimes();
                response.flushBuffer();
                EasyMock.expectLastCall();
            }
            request.getAttribute("javax.servlet.request.cipher_suite");
            EasyMock.expectLastCall().andReturn("anythingwilldoreally");
            request.getAttribute("javax.net.ssl.session");
            EasyMock.expectLastCall().andReturn(null);
            request.getAttribute("javax.servlet.request.X509Certificate");
            EasyMock.expectLastCall().andReturn(null);
        }
    }

    if (decoupled) {
        setupDecoupledBackChannel();
    }
    EasyMock.replay(response);
    EasyMock.replay(request);
}
 
Example 17
Source File: JavaScriptHandler.java    From divolte-collector with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("Requested received for {} from {}",
                     resource.getResourceName(), exchange.getSourceAddress().getHostString());
    }
    // Start with headers that we always set the same way.
    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    responseHeaders.put(Headers.CACHE_CONTROL, CACHE_CONTROL_HEADER_VALUE);

    // Figure out if we possibly need to deal with a compressed response,
    // based on client capability.
    final GzippableHttpBody uncompressedBody = resource.getEntityBody();
    final Optional<HttpBody> gzippedBody = uncompressedBody.getGzippedBody();
    final HttpBody bodyToSend;
    if (gzippedBody.isPresent()) {
        /*
         * Compressed responses can use Content-Encoding and/or Transfer-Encoding.
         * The semantics differ slightly, but it is suffice to say that most user
         * agents don't advertise their Transfer-Encoding support.
         * So for now we only support the Content-Encoding mechanism.
         * Some other notes:
         *  - Some clients implement 'deflate' incorrectly. Hence we only support 'gzip',
         *    despite it having slightly more overhead.
         *  - We don't use Undertow's built-in compression support because we've
         *    pre-calculated the compressed response and expect to serve it up
         *    repeatedly, instead of calculating it on-the-fly for every request.
         */
        responseHeaders.put(Headers.VARY, Headers.ACCEPT_ENCODING_STRING);
        final HeaderValues acceptEncoding =
                exchange.getRequestHeaders().get(Headers.ACCEPT_ENCODING);
        if (null != acceptEncoding &&
                acceptEncoding.stream()
                              .anyMatch((header) -> Iterables.contains(HEADER_SPLITTER.split(header), "gzip"))) {
            responseHeaders.put(Headers.CONTENT_ENCODING, "gzip");
            bodyToSend = gzippedBody.get();
        } else {
            bodyToSend = uncompressedBody;
        }
    } else {
        bodyToSend = uncompressedBody;
    }

    // Now we know which version of the entity is visible to this user-agent,
    // figure out if the client already has the current version or not.
    final ETag eTag = bodyToSend.getETag();
    responseHeaders.put(Headers.ETAG, eTag.toString());
    if (ETagUtils.handleIfNoneMatch(exchange, eTag, true)) {
        final ByteBuffer entityBody = bodyToSend.getBody();
        responseHeaders.put(Headers.CONTENT_TYPE, "application/javascript");
        exchange.getResponseSender().send(entityBody);
    } else {
        exchange.setStatusCode(StatusCodes.NOT_MODIFIED);
        exchange.endExchange();
    }
}
 
Example 18
Source File: HttpTransferEncoding.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
static StreamSinkConduit createSinkConduit(final HttpServerExchange exchange) {
    DateUtils.addDateHeaderIfRequired(exchange);

    boolean headRequest = exchange.getRequestMethod().equals(Methods.HEAD);
    HttpServerConnection serverConnection = (HttpServerConnection) exchange.getConnection();

    HttpResponseConduit responseConduit = serverConnection.getResponseConduit();
    responseConduit.reset(exchange);
    StreamSinkConduit channel = responseConduit;
    if (headRequest) {
        //if this is a head request we add a head channel underneath the content encoding channel
        //this will just discard the data
        //we still go through with the rest of the logic, to make sure all headers are set correctly
        channel = new HeadStreamSinkConduit(channel, terminateResponseListener(exchange));
    } else if(!Connectors.isEntityBodyAllowed(exchange)) {
        //we are not allowed to send an entity body for some requests
        exchange.getResponseHeaders().remove(Headers.CONTENT_LENGTH);
        exchange.getResponseHeaders().remove(Headers.TRANSFER_ENCODING);
        channel = new HeadStreamSinkConduit(channel, terminateResponseListener(exchange));
        return channel;
    }

    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    // test to see if we're still persistent
    String connection = responseHeaders.getFirst(Headers.CONNECTION);
    if (!exchange.isPersistent()) {
        responseHeaders.put(Headers.CONNECTION, Headers.CLOSE.toString());
    } else if (exchange.isPersistent() && connection != null) {
        if (HttpString.tryFromString(connection).equals(Headers.CLOSE)) {
            exchange.setPersistent(false);
        }
    } else if (exchange.getConnection().getUndertowOptions().get(UndertowOptions.ALWAYS_SET_KEEP_ALIVE, true)) {
        responseHeaders.put(Headers.CONNECTION, Headers.KEEP_ALIVE.toString());
    }
    //according to the HTTP RFC we should ignore content length if a transfer coding is specified
    final String transferEncodingHeader = responseHeaders.getLast(Headers.TRANSFER_ENCODING);
    if(transferEncodingHeader == null) {
        final String contentLengthHeader = responseHeaders.getFirst(Headers.CONTENT_LENGTH);
        if (contentLengthHeader != null) {
            StreamSinkConduit res = handleFixedLength(exchange, headRequest, channel, responseHeaders, contentLengthHeader, serverConnection);
            if (res != null) {
                return res;
            }
        }
    } else {
        responseHeaders.remove(Headers.CONTENT_LENGTH); //if there is a transfer-encoding header we remove content length if present
    }
    return handleResponseConduit(exchange, headRequest, channel, responseHeaders, terminateResponseListener(exchange), transferEncodingHeader);
}
 
Example 19
Source File: EventBusToServerSentEvents.java    From syndesis with Apache License 2.0 4 votes vote down vote up
protected boolean reservationCheck(HttpServerExchange exchange) {
    HeaderMap requestHeaders = exchange.getRequestHeaders();
    String origin = requestHeaders.getFirst(CorsHeaders.ORIGIN);
    if (cors.getAllowedOrigins().contains("*") || cors.getAllowedOrigins().contains(origin)) {
        HeaderMap responseHeaders = exchange.getResponseHeaders();
        responseHeaders.put(new HttpString(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN), origin);

        String value = requestHeaders.getFirst(CorsHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
        if (value != null) {
            responseHeaders.put(new HttpString(CorsHeaders.ACCESS_CONTROL_ALLOW_HEADERS), value);
        }

        value = requestHeaders.getFirst(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS);
        if (value != null) {
            responseHeaders.put(new HttpString(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS), value);
        }

        value = requestHeaders.getFirst(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD);
        if (value != null) {
            responseHeaders.put(new HttpString(CorsHeaders.ACCESS_CONTROL_ALLOW_METHODS), value);
        }
    }

    String uri = exchange.getRequestURI();
    if (uri.indexOf(path + "/") != 0) {
        exchange.setStatusCode(404);
        return false;
    }

    final String subscriptionId = uri.substring(path.length() + 1);
    if (subscriptionId.isEmpty()) {
        exchange.setStatusCode(404);
        return false;
    }

    EventReservationsHandler.Reservation reservation = eventReservationsHandler.existsReservation(subscriptionId);
    if (reservation == null) {
        exchange.setStatusCode(404);
        return false;
    }
    return true;
}
 
Example 20
Source File: OcspHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    final byte[] buffy = new byte[16384];
    try (InputStream requestStream = exchange.getInputStream()) {
        requestStream.read(buffy);
    }

    final OCSPReq request = new OCSPReq(buffy);
    final Req[] requested = request.getRequestList();

    final Extension nonce = request.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);

    final DigestCalculator sha1Calculator = new JcaDigestCalculatorProviderBuilder().build()
            .get(AlgorithmIdentifier.getInstance(RespID.HASH_SHA1));

    final BasicOCSPRespBuilder responseBuilder = new BasicOCSPRespBuilder(subjectPublicKeyInfo, sha1Calculator);

    if (nonce != null) {
        responseBuilder.setResponseExtensions(new Extensions(nonce));
    }

    for (final Req req : requested) {
        final CertificateID certId = req.getCertID();

        final BigInteger certificateSerialNumber = certId.getSerialNumber();
        responseBuilder.addResponse(certId, REVOKED_CERTIFICATES_STATUS.get(certificateSerialNumber));
    }

    final ContentSigner contentSigner = new BcRSAContentSignerBuilder(
            new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption),
            new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)).build(privateKey);

    final OCSPResp response = new OCSPRespBuilder().build(OCSPResp.SUCCESSFUL,
            responseBuilder.build(contentSigner, chain, new Date()));

    final byte[] responseBytes = response.getEncoded();

    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    responseHeaders.put(Headers.CONTENT_TYPE, "application/ocsp-response");

    final Sender responseSender = exchange.getResponseSender();
    responseSender.send(ByteBuffer.wrap(responseBytes));

    exchange.endExchange();
}