下面列出了怎么用org.eclipse.jetty.server.HttpConnection的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onClosed(Connection connection) {
Timer.Sample sample;
synchronized (connectionSamplesLock) {
sample = connectionSamples.remove(connection);
}
if (sample != null) {
String serverOrClient = connection instanceof HttpConnection ? "server" : "client";
sample.stop(Timer.builder("jetty.connections.request")
.description("Jetty client or server requests")
.tag("type", serverOrClient)
.tags(tags)
.register(registry));
}
messagesIn.increment(connection.getMessagesIn());
messagesOut.increment(connection.getMessagesOut());
bytesIn.record(connection.getBytesIn());
bytesOut.record(connection.getBytesOut());
}
/**
* Certain aspects of the container, such as logging, need the authentication information to behave properly.
* This method updates the request with the necessary objects to recognize the authenticated user.
*/
private void setJettyAuthentication(Subject subject) {
// In unit test environments there may not be a current connection. If any nulls are encountered
// then, by definition, there is no container to update.
HttpConnection connection = HttpConnection.getCurrentConnection();
if (connection == null) {
return;
}
Request jettyRequest = connection.getHttpChannel().getRequest();
if (jettyRequest == null) {
return;
}
// This cast down is safe; subject is always created with this type of principal
PrincipalWithRoles principal = (PrincipalWithRoles) subject.getPrincipal();
UserIdentity identity = principal.toUserIdentity();
jettyRequest.setAuthentication(new UserAuthentication(SecurityContext.BASIC_AUTH, identity));
}
private static HttpServletRequest createMockRequest(String scheme, String serverName, String path, String queryString) {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpConnection connection = mock(HttpConnection.class);
ServerConnector connector = mock(ServerConnector.class);
when(connector.getLocalPort()).thenReturn(LOCAL_PORT);
when(connection.getCreatedTimeStamp()).thenReturn(System.currentTimeMillis());
when(connection.getConnector()).thenReturn(connector);
when(request.getAttribute("org.eclipse.jetty.server.HttpConnection")).thenReturn(connection);
when(request.getProtocol()).thenReturn("HTTP/1.1");
when(request.getScheme()).thenReturn(scheme);
when(request.getServerName()).thenReturn(serverName);
when(request.getRemoteAddr()).thenReturn("127.0.0.1");
when(request.getRemotePort()).thenReturn(1234);
when(request.getLocalPort()).thenReturn(LOCAL_PORT);
when(request.getMethod()).thenReturn("GET");
when(request.getQueryString()).thenReturn(queryString);
when(request.getRequestURI()).thenReturn(path);
return request;
}
@Override
HttpServletResponse toHttpServletResponse(Object[] args) {
if (args == null || args.length < 1) {
return null;
}
if (args[0] instanceof HttpConnection) {
try {
HttpConnection connection = (HttpConnection) args[0];
return connection.getResponse();
} catch (Throwable ignored) {
}
}
return null;
}
public void handle(String target, Request serverRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (!NODE_HANDLER_PATH.equals(target)) return;
if("POST".equals(request.getMethod()) && secretToken.equals(request.getParameter("secret"))) {
available = !("offline".equals(request.getParameter("state")));
}
response.setContentType("text/plain");
response.setStatus(available ? SC_OK : IM_USED);
PrintWriter out = response.getWriter();
out.println(available ? "online" : "offline");
out.close();
HttpConnection.getCurrentConnection().getRequest().setHandled(true);
}
private ServletRequest newServletRequest() throws Exception {
MockHttpServletRequest parent = new MockHttpServletRequest("GET", uri.toString());
parent.setProtocol(Version.HTTP_1_1.toString());
parent.setRemoteHost(host);
parent.setRemotePort(port);
parent.setParameter(paramName, paramValue);
parent.setParameter(listParamName, listParamValue);
parent.addHeader(headerName, headerValue);
parent.setAttribute(attributeName, attributeValue);
HttpConnection connection = Mockito.mock(HttpConnection.class);
when(connection.getCreatedTimeStamp()).thenReturn(System.currentTimeMillis());
parent.setAttribute("org.eclipse.jetty.server.HttpConnection", connection);
return new ServletRequest(parent, uri);
}
@Override
HttpServletRequest toHttpServletRequest(Object[] args) {
if (args == null || args.length < 1) {
return null;
}
if (args[0] instanceof HttpConnection) {
try {
HttpConnection connection = (HttpConnection) args[0];
return connection.getRequest();
} catch (Throwable ignored) {
}
}
return null;
}
private Request getCurrentRequest() {
try {
HttpConnection con = HttpConnection.getCurrentConnection();
HttpChannel channel = con.getHttpChannel();
return channel.getRequest();
} catch (Throwable t) {
//
}
return null;
}
public HttpChannelOverHttpCustom(HttpConnection httpConnection, Connector connector,
HttpConfiguration config, EndPoint endPoint,
HttpTransport transport) {
super(httpConnection, connector, config, endPoint, transport);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
Request httpRequest = (request instanceof Request) ?
(Request) request :
HttpConnection.getCurrentConnection().getHttpChannel().getRequest();
// If there already is an API key present then perform no further action
String apiKeyHeader = httpRequest.getHeader(ApiKeyRequest.AUTHENTICATION_HEADER);
String apiKeyParam = httpRequest.getParameter(ApiKeyRequest.AUTHENTICATION_PARAM);
if (!Strings.isNullOrEmpty(apiKeyHeader) || !Strings.isNullOrEmpty(apiKeyParam)) {
chain.doFilter(request, response);
return;
}
// If there is no authentication header then perform no further action
String authenticationHeader = httpRequest.getHeader(HttpHeader.AUTHORIZATION.asString());
if (Strings.isNullOrEmpty(authenticationHeader)) {
chain.doFilter(request, response);
return;
}
// Parse the authentication header to determine if it matches the replication user's credentials
int space = authenticationHeader.indexOf(' ');
if (space != -1 && "basic".equalsIgnoreCase(authenticationHeader.substring(0, space))) {
try {
String credentials = new String(
BaseEncoding.base64().decode(authenticationHeader.substring(space+1)), Charsets.UTF_8);
for (Map.Entry<String, String> entry : _basicAuthToApiKeyMap.entrySet()) {
if (entry.getKey().equals(credentials)) {
// The user name and password matches the replication credentials. Insert the header.
HttpFields fields = httpRequest.getHttpFields();
fields.put(ApiKeyRequest.AUTHENTICATION_HEADER, entry.getValue());
}
}
} catch (Exception e) {
// Ok, the header wasn't formatted properly. Do nothing.
}
}
chain.doFilter(request, response);
}
public static HttpConnection getConnection(HttpServletRequest request) {
return (HttpConnection)request.getAttribute("org.eclipse.jetty.server.HttpConnection");
}