Java Code Examples for io.vertx.core.http.HttpServerRequest#getHeader()

The following examples show how to use io.vertx.core.http.HttpServerRequest#getHeader() . 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: Requests.java    From mpns with Apache License 2.0 6 votes vote down vote up
public static String getIp(HttpServerRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.remoteAddress().host();
    }
    if (ip.startsWith("0:0:0")) ip = "127.0.0.1";
    else if (ip.lastIndexOf(',') != -1) {
        try {
            ip = ip.split(",")[0];
        } catch (Exception e) {
            ip = request.remoteAddress().host();
        }
    }
    return ip;
}
 
Example 2
Source File: RoutingContextImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private void fillParsedHeaders(HttpServerRequest request) {
  String accept = request.getHeader("Accept");
  String acceptCharset = request.getHeader ("Accept-Charset");
  String acceptEncoding = request.getHeader("Accept-Encoding");
  String acceptLanguage = request.getHeader("Accept-Language");
  String contentType = ensureNotNull(request.getHeader("Content-Type"));

  parsedHeaders = new ParsableHeaderValuesContainer(
      HeaderParser.sort(HeaderParser.convertToParsedHeaderValues(accept, ParsableMIMEValue::new)),
      HeaderParser.sort(HeaderParser.convertToParsedHeaderValues(acceptCharset, ParsableHeaderValue::new)),
      HeaderParser.sort(HeaderParser.convertToParsedHeaderValues(acceptEncoding, ParsableHeaderValue::new)),
      HeaderParser.sort(HeaderParser.convertToParsedHeaderValues(acceptLanguage, ParsableLanguageValue::new)),
      new ParsableMIMEValue(contentType)
  );

}
 
Example 3
Source File: BaseTransport.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
static void setCORS(RoutingContext rc) {
  if (rc.get(CorsHandlerImpl.CORS_HANDLED_FLAG) == null || !((boolean)rc.get(CorsHandlerImpl.CORS_HANDLED_FLAG))) {
    HttpServerRequest req = rc.request();
    String origin = req.getHeader(ORIGIN);
    if (origin == null) {
      origin = "*";
    }
    req.response().headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
    if ("*".equals(origin)) {
      req.response().headers().set(ACCESS_CONTROL_ALLOW_CREDENTIALS, "false");
    } else {
      req.response().headers().set(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    }
    String hdr = req.headers().get(ACCESS_CONTROL_REQUEST_HEADERS);
    if (hdr != null) {
      req.response().headers().set(ACCESS_CONTROL_ALLOW_HEADERS, hdr);
    }
  }
}
 
Example 4
Source File: SSEHandlerImpl.java    From vertx-sse with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
	HttpServerRequest request = context.request();
	HttpServerResponse response = context.response();
	response.setChunked(true);
	SSEConnection connection = SSEConnection.create(context);
	String accept = request.getHeader("Accept");
	if (accept != null && !accept.contains("text/event-stream")) {
		connection.reject(406, "Not acceptable");
		return;
	}
	response.closeHandler(aVoid -> {
		closeHandlers.forEach(closeHandler -> closeHandler.handle(connection));
		connection.close();
	});
	response.headers().add("Content-Type", "text/event-stream");
	response.headers().add("Cache-Control", "no-cache");
	response.headers().add("Connection", "keep-alive");
	connectHandlers.forEach(handler -> handler.handle(connection));
	if (!connection.rejected()) {
		response.setStatusCode(200);
		response.setChunked(true);
		response.write(EMPTY_BUFFER);
	}
}
 
Example 5
Source File: LanAccessSubRouter.java    From AlipayWechatPlatform with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 判断当前请求是否允许,如果不允许,则将状态码设为403并结束响应
 * 
 * @return true:禁止访问 false=允许访问
 * @author Leibniz.Hu
 */
protected boolean refuseNonLanAccess(RoutingContext rc) {
    HttpServerRequest req = rc.request();
    HttpServerResponse resp = rc.response();
    String realIp = req.getHeader("X-Real-IP");
    String xforward = req.getHeader("X-Forwarded-For");
    //禁止外网访问
    if (realIp != null && !isLanIP(realIp)) {
        log.warn("检测到非法访问,来自X-Real-IP={}", realIp);
        resp.setStatusCode(403).end();
        return true;
    }
    if (xforward != null && !isLanIP(xforward)) {
        log.warn("检测到非法访问,来自X-Forwarded-For={}", xforward);
        resp.setStatusCode(403).end();
        return true;
    }
    return false;
}
 
Example 6
Source File: UserHandler.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
@Override
public User provide(HttpServerRequest request) {
	String token = request.getHeader("X-Token");

	// set user ...
	if (token != null) {
		return users.getUser(token);
	}

	return null;
}
 
Example 7
Source File: TokenProvider.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
@Override
public Token provide(HttpServerRequest request) {
	String token = request.getHeader("X-Token");
	if (token != null) {
		return new Token(token);
	}

	return null;
}
 
Example 8
Source File: NewTokenProvider.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
@Override
public Token provide(HttpServerRequest request) {
	String token = request.getHeader("X-Token");
	if (token != null) {
		return new Token("***" + token + "***");
	}

	return null;
}
 
Example 9
Source File: HttpBridge.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
/**
 * Process an HTTP request related to the producer
 * 
 * @param routingContext RoutingContext instance
 */
private void processProducer(RoutingContext routingContext) {
    HttpServerRequest httpServerRequest = routingContext.request();
    String contentType = httpServerRequest.getHeader("Content-Type") != null ?
            httpServerRequest.getHeader("Content-Type") : BridgeContentType.KAFKA_JSON_BINARY;

    SourceBridgeEndpoint<byte[], byte[]> source = this.httpBridgeContext.getHttpSourceEndpoints().get(httpServerRequest.connection());

    try {
        if (source == null) {
            source = new HttpSourceBridgeEndpoint<>(this.vertx, this.bridgeConfig,
                    contentTypeToFormat(contentType), new ByteArraySerializer(), new ByteArraySerializer());

            source.closeHandler(s -> {
                this.httpBridgeContext.getHttpSourceEndpoints().remove(httpServerRequest.connection());
            });
            source.open();
            this.httpBridgeContext.getHttpSourceEndpoints().put(httpServerRequest.connection(), source);
        }
        source.handle(new HttpEndpoint(routingContext));

    } catch (Exception ex) {
        if (source != null) {
            source.close();
        }
        HttpBridgeError error = new HttpBridgeError(
                HttpResponseStatus.INTERNAL_SERVER_ERROR.code(),
                ex.getMessage()
        );
        HttpUtils.sendResponse(routingContext, HttpResponseStatus.INTERNAL_SERVER_ERROR.code(),
                BridgeContentType.KAFKA_JSON, error.toJson().toBuffer());
    }
}
 
Example 10
Source File: ChecksBase.java    From vertx-consul-client with Apache License 2.0 5 votes vote down vote up
@Override
void handle(HttpServerRequest request) {
  String headerValue = request.getHeader(TEST_HEADER_NAME);
  Assert.assertEquals(TEST_HEADER_VALUE, headerValue);
  request.response()
    .setStatusCode(statusCode(status))
    .end(status.name());
}
 
Example 11
Source File: VertxWebSocketReactorHandler.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
private boolean isWebSocket(HttpServerRequest httpServerRequest) {
    String connectionHeader = httpServerRequest.getHeader(HttpHeaders.CONNECTION);
    String upgradeHeader = httpServerRequest.getHeader(HttpHeaders.UPGRADE);

    return httpServerRequest.method() == HttpMethod.GET &&
            HttpHeaderValues.UPGRADE.contentEqualsIgnoreCase(connectionHeader) &&
            HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgradeHeader);
}
 
Example 12
Source File: SimulatedUserProvider.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
@Override public SimulatedUser provide(HttpServerRequest request) throws MyExceptionClass {

		String token = request.getHeader("X-Token");
		if (token == null) {
			throw new MyExceptionClass("No user present!", 404);
		}
		return users.getUser(token);
	}
 
Example 13
Source File: RestBodyHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private long parseContentLengthHeader(HttpServerRequest request) {
  String contentLength = request.getHeader(HttpHeaders.CONTENT_LENGTH);
  if (contentLength == null || contentLength.isEmpty()) {
    return -1;
  }
  try {
    long parsedContentLength = Long.parseLong(contentLength);
    return parsedContentLength < 0 ? null : parsedContentLength;
  } catch (NumberFormatException ex) {
    return -1;
  }
}
 
Example 14
Source File: BodyHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private long parseContentLengthHeader(HttpServerRequest request) {
  String contentLength = request.getHeader(HttpHeaders.CONTENT_LENGTH);
  if(contentLength == null || contentLength.isEmpty()) {
    return -1;
  }
  try {
    long parsedContentLength = Long.parseLong(contentLength);
    return  parsedContentLength < 0 ? null : parsedContentLength;
  }
  catch (NumberFormatException ex) {
    return -1;
  }
}
 
Example 15
Source File: CORSFilter.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext event) {
    Objects.requireNonNull(corsConfig, "CORS config is not set");
    HttpServerRequest request = event.request();
    HttpServerResponse response = event.response();
    String origin = request.getHeader(HttpHeaders.ORIGIN);
    if (origin == null) {
        event.next();
    } else {
        final String requestedMethods = request.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD);

        if (requestedMethods != null) {
            processMethods(response, requestedMethods);
        }

        final String requestedHeaders = request.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);

        if (requestedHeaders != null) {
            processRequestedHeaders(response, requestedHeaders);
        }

        boolean allowsOrigin = !corsConfig.origins.isPresent() || corsConfig.origins.get().contains(origin);

        if (allowsOrigin) {
            response.headers().set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
        }

        response.headers().set(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");

        final Optional<List<String>> exposedHeaders = corsConfig.exposedHeaders;

        if (exposedHeaders.isPresent()) {
            response.headers().set(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS,
                    String.join(",", exposedHeaders.orElse(Collections.emptyList())));
        }

        if (request.method().equals(HttpMethod.OPTIONS)) {
            if ((requestedHeaders != null || requestedMethods != null) && corsConfig.accessControlMaxAge.isPresent()) {
                response.putHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE,
                        String.valueOf(corsConfig.accessControlMaxAge.get().getSeconds()));
            }
            response.end();
        } else {
            event.next();
        }
    }
}
 
Example 16
Source File: HttpServerRequestAdaptor.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
@Override
public String getHeader(HttpServerRequest request, String name) {
    return request.getHeader(name);
}
 
Example 17
Source File: Utils.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public static boolean fresh(RoutingContext ctx, long lastModified) {

    final HttpServerRequest req = ctx.request();
    final HttpServerResponse res = ctx.response();


    // fields
    final String modifiedSince = req.getHeader(HttpHeaders.IF_MODIFIED_SINCE);
    final String noneMatch = req.getHeader(HttpHeaders.IF_NONE_MATCH);

    // unconditional request
    if (modifiedSince == null && noneMatch == null) {
      return false;
    }

    // Always return stale when Cache-Control: no-cache
    // to support end-to-end reload requests
    // https://tools.ietf.org/html/rfc2616#section-14.9.4
    final String cacheControl = req.getHeader(HttpHeaders.CACHE_CONTROL);
    if (cacheControl != null && CACHE_CONTROL_NO_CACHE_REGEXP.matcher(cacheControl).find()) {
      return false;
    }

    // if-none-match
    if (noneMatch != null && !"*".equals(noneMatch)) {
      final String etag = res.headers().get(HttpHeaders.ETAG);

      if (etag == null) {
        return false;
      }

      boolean etagStale = true;

      // lookup etags
      int end = 0;
      int start = 0;

      loop: for (int i = 0; i < noneMatch.length(); i++) {
        switch (noneMatch.charAt(i)) {
          case ' ':
            if (start == end) {
              start = end = i + 1;
            }
            break;
          case ',':
            String match = noneMatch.substring(start, end);
            if (match.equals(etag) || match.equals("W/" + etag) || ("W/" + match).equals(etag)) {
              etagStale = false;
              break loop;
            }
            start = end = i + 1;
            break;
          default:
            end = i + 1;
            break;
        }
      }

      if (etagStale) {
        return false;
      }
    }

    // if-modified-since
    if (modifiedSince != null) {
      if (lastModified == -1) {
        // no custom last modified provided, will use the response headers if any
        lastModified = parseRFC1123DateTime(res.headers().get(HttpHeaders.LAST_MODIFIED));
      }

      boolean modifiedStale = lastModified == -1 || !(lastModified <= parseRFC1123DateTime(modifiedSince));

        return !modifiedStale;
    }

    return true;
  }
 
Example 18
Source File: FormLoginHandlerImpl.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
private String userAgent(HttpServerRequest request) {
    return request.getHeader(HttpHeaders.USER_AGENT);
}
 
Example 19
Source File: DummyProvider.java    From rest.vertx with Apache License 2.0 4 votes vote down vote up
@Override
public Dummy provide(HttpServerRequest request) throws Throwable {
	return new Dummy(request.getHeader("X-dummy-name"), request.getHeader("X-dummy-value"));
}