org.eclipse.jetty.http.MetaData Java Examples

The following examples show how to use org.eclipse.jetty.http.MetaData. 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: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testAdminRequired_NoUser() throws Exception {
  String path = "/admin/blah";
  Request request = spy(new Request(null, null));
  //request.setServerPort(9999);
  HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path);
  HttpFields httpf = new HttpFields();
  MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
  request.setMetaData(metadata);
//  request.setAuthority(SERVER_NAME,9999);
  Response response = mock(Response.class);
  String output = runRequest(path, request, response);
  // Verify that the servlet never was run (there is no output).
  assertEquals("", output);
  // Verify that the request was redirected to the login url.
  String loginUrl = UserServiceFactory.getUserService()
      .createLoginURL(String.format("http://%s%s", SERVER_NAME + ":9999", path));
  verify(response).sendRedirect(loginUrl);
}
 
Example #2
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testUserRequired_PreserveQueryParams() throws Exception {
  String path = "/user/blah";
  
  Request request = new Request(null, null);
  // request.setServerPort(9999);
      HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path,"foo=baqr","foo=bar","foo=barff");
  HttpFields httpf = new HttpFields();
  MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
  request.setMetaData(metadata);
  MultiMap<String> queryParameters = new MultiMap<> ();
  queryParameters.add("ffo", "bar");
  request.setQueryParameters(queryParameters);
      request = spy(request);

 /// request.setAuthority(SERVER_NAME,9999);
  request.setQueryString("foo=bar");
  Response response = mock(Response.class);
  String output = runRequest2(path, request, response);
  // Verify that the servlet never was run (there is no output).
  assertEquals("", output);
  // Verify that the request was redirected to the login url.
  String loginUrl = UserServiceFactory.getUserService()
      .createLoginURL(String.format("http://%s%s?foo=bar", SERVER_NAME + ":9999", path));
  verify(response).sendRedirect(loginUrl);
}
 
Example #3
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testUserRequired_NoUser() throws Exception {
  String path = "/user/blah";
  Request request = spy(new Request(null, null));
  //request.setServerPort(9999);
      HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path);
  HttpFields httpf = new HttpFields();
  MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
  request.setMetaData(metadata);
 // request.setAuthority(SERVER_NAME,9999);
  Response response = mock(Response.class);
  String output = runRequest(path, request, response);
  // Verify that the servlet never was run (there is no output).
  assertEquals("", output);
  // Verify that the request was redirected to the login url.
  String loginUrl = UserServiceFactory.getUserService()
      .createLoginURL(String.format("http://%s%s", SERVER_NAME + ":9999", path));
  verify(response).sendRedirect(loginUrl);
}
 
Example #4
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
private String runRequest2(String path, Request request, Response response)
     throws IOException, ServletException {
   //request.setMethod(/*HttpMethod.GET,*/ "GET");
   HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path);
   HttpFields httpf = new HttpFields();
   MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
//   request.setMetaData(metadata);

   // request.setServerName(SERVER_NAME);
  // request.setAuthority(SERVER_NAME,9999);
  //// request.setPathInfo(path);
  //// request.setURIPathQuery(path);
   request.setDispatcherType(DispatcherType.REQUEST);
   doReturn(response).when(request).getResponse();

   ByteArrayOutputStream output = new ByteArrayOutputStream();
   try (PrintWriter writer = new PrintWriter(output)) {
     when(response.getWriter()).thenReturn(writer);
     securityHandler.handle(path, request, request, response);
   }
   return new String(output.toByteArray());
 }
 
Example #5
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * Fire one request at the security handler (and by extension to the AuthServlet behind it).
 *
 * @param path The path to hit.
 * @param request The request object to use.
 * @param response The response object to use. Must be created by Mockito.mock()
 * @return Any data written to response.getWriter()
 * @throws IOException
 * @throws ServletException
 */
private String runRequest(String path, Request request, Response response)
    throws IOException, ServletException {
  //request.setMethod(/*HttpMethod.GET,*/ "GET");
  HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path);
  HttpFields httpf = new HttpFields();
  MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
  request.setMetaData(metadata);

  // request.setServerName(SERVER_NAME);
 // request.setAuthority(SERVER_NAME,9999);
 //// request.setPathInfo(path);
 //// request.setURIPathQuery(path);
  request.setDispatcherType(DispatcherType.REQUEST);
  doReturn(response).when(request).getResponse();

  ByteArrayOutputStream output = new ByteArrayOutputStream();
  try (PrintWriter writer = new PrintWriter(output)) {
    when(response.getWriter()).thenReturn(writer);
    securityHandler.handle(path, request, request, response);
  }
  return new String(output.toByteArray());
}
 
Example #6
Source File: SystemInfoServiceClient.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
@Override
public SystemInfo getSystemInfo() {
    try {
        Session session = createSession();
        HttpFields requestFields = new HttpFields();
        requestFields.put(USER_AGENT, USER_AGENT_VERSION);
        MetaData.Request request = new MetaData.Request("GET", getSystemInfoURI, HttpVersion.HTTP_2, requestFields);
        HeadersFrame headersFrame = new HeadersFrame(request, null, true);
        GetListener getListener = new GetListener();
        session.newStream(headersFrame, new FuturePromise<>(), getListener);
        SystemInfo response = getListener.get(SystemInfo.class);
        session.close(0, null, new Callback() {});
        return response;
    } catch (Exception e) {
        throw new HttpAccessException(e);
    }
}
 
Example #7
Source File: CustomSessionListener.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
@Override
public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
    LOG.info("onNewStream");
    if (frame.getMetaData().isRequest()) {
        MetaData.Request request = (MetaData.Request)frame.getMetaData();
        String uriPath = request.getURI().getPath();
        LOG.info("isRequest {} {}", request.getMethod(), uriPath);
        StreamProcessorRegistration streamProcessorRegistration = streamProcessors.get(uriPath);
        if (streamProcessorRegistration != null) {
            LOG.info("diverting to stream processor {}", uriPath);
            return streamProcessorRegistration.getFactory().create(stream);
        }
    }
    getConnection().onNewStream(connector, (IStream)stream, frame);
    return this;
}
 
Example #8
Source File: JettyService.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static ResponseHeaders toResponseHeaders(ArmeriaHttpTransport transport) {
    final MetaData.Response info = transport.info;
    if (info == null) {
        throw new IllegalStateException("response metadata unavailable");
    }

    final ResponseHeadersBuilder headers = ResponseHeaders.builder();
    headers.status(info.getStatus());
    info.getFields().forEach(e -> headers.add(HttpHeaderNames.of(e.getName()), e.getValue()));

    if (transport.method != HttpMethod.HEAD) {
        headers.setLong(HttpHeaderNames.CONTENT_LENGTH, transport.contentLength);
    }

    return headers.build();
}
 
Example #9
Source File: JettyService.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static MetaData.Request toRequestMetadata(ServiceRequestContext ctx, AggregatedHttpRequest aReq) {
    // Construct the HttpURI
    final StringBuilder uriBuf = new StringBuilder();
    final RequestHeaders aHeaders = aReq.headers();

    uriBuf.append(ctx.sessionProtocol().isTls() ? "https" : "http");
    uriBuf.append("://");
    uriBuf.append(aHeaders.authority());
    uriBuf.append(aHeaders.path());

    final HttpURI uri = new HttpURI(uriBuf.toString());
    uri.setPath(ctx.mappedPath());

    // Convert HttpHeaders to HttpFields
    final HttpFields jHeaders = new HttpFields(aHeaders.size());
    aHeaders.forEach(e -> {
        final AsciiString key = e.getKey();
        if (!key.isEmpty() && key.byteAt(0) != ':') {
            jHeaders.add(key.toString(), e.getValue());
        }
    });

    return new MetaData.Request(aHeaders.get(HttpHeaderNames.METHOD), uri,
                                HttpVersion.HTTP_1_1, jHeaders, aReq.content().length());
}
 
Example #10
Source File: HeadersFrameTest.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
@Test
public void bigData() throws Exception {
	byte[] a = Hex.decodeHex("3fe15f0085b8848d36a38264026e959d29ad171863c78f0bcc73cd415721e963c1639ebf5885aec3771a4b5f92497ca589d34d1f6a1271d882a60e1bf0acf7788ca47e561cc58190b6cb80003f008390692f96df3dbf4a082a693f750400bea01cb8cb5704053168df76036777735c82109b408cf2b794216aec3a4a4498f57f0130408bf2b4b60e92ac7ad263d48f89dd0e8c1ab6e4c5934f00874152b10e7ea62fcb0eb8b2c3b601002fac10ac20ac073ed42f9acd615106e1a7e941056be522c2005f500e5c65ab820298b46ffb52b1a67818fb5243d2335502f31cf35055c87a7ed4dc3a4bb8c92c151ea2ff40851d09591dc9ff07ed698907f371a699fe7ed4a47009b7c40003ed4ef07f2d39f4d33fcfd4ecadb00d820fe6e34d33fcfda948e0136f880007d4ecadb00d3f07f371a699fe7ed4a47009b7c40003ea7656d8069e83f9b8d34cff3f6a523804dbe20001f53b2b6c034e41fcdc69a67f9fb5291c026df10000fa9d95b601a660fe6e34d33fcfda948e0136f880007f".toCharArray());
	HpackDecoder decoder = new HpackDecoder(65535,65535);
	ByteBuffer bb = ByteBuffer.allocate(4096);
	bb.put(a);
	bb.flip();
	MetaData m = decoder.decode(bb);
	System.out.println(m);
}
 
Example #11
Source File: JettyService.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public void send(@Nullable MetaData.Response info, boolean head,
                 ByteBuffer content, boolean lastContent, Callback callback) {

    if (info != null) {
        this.info = info;
    }

    final int length = content.remaining();
    if (length == 0) {
        callback.succeeded();
        return;
    }

    if (content.hasArray()) {
        final int from = content.arrayOffset() + content.position();
        out.add(HttpData.wrap(Arrays.copyOfRange(content.array(), from, from + length)));
        content.position(content.position() + length);
    } else {
        final byte[] data = new byte[length];
        content.get(data);
        out.add(HttpData.wrap(data));
    }

    contentLength += length;
    callback.succeeded();
}
 
Example #12
Source File: HttpResponseStatisticsCollectorTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
private Request testRequest(String scheme, int responseCode, String httpMethod, String path) throws Exception {
    HttpChannel channel = new HttpChannel(connector, new HttpConfiguration(), null, new DummyTransport());
    MetaData.Request metaData = new MetaData.Request(httpMethod, new HttpURI(scheme + "://" + path), HttpVersion.HTTP_1_1, new HttpFields());
    Request req = channel.getRequest();
    req.setMetaData(metaData);

    this.httpResponseCode = responseCode;
    channel.handle();
    return req;
}
 
Example #13
Source File: RestClient20.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public Stream createStream(Session session, HttpURI uri, Stream.Listener listener) throws Exception {
    HttpFields requestFields = new HttpFields();
    requestFields.put(USER_AGENT, USER_AGENT_VERSION);
    MetaData.Request request = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, requestFields);
    HeadersFrame headersFrame = new HeadersFrame(request, null, false);
    FuturePromise<Stream> streamPromise = new FuturePromise<>();
    session.newStream(headersFrame, streamPromise, listener);
    return streamPromise.get();
}
 
Example #14
Source File: HttpRequestParamsReader.java    From tika-server with Apache License 2.0 5 votes vote down vote up
private static MetaData getMetaDataField(Object stream) {
    while (true) {
        try {
            Field field = FieldLookup.findField(stream.getClass(), "val$req");
            if (field != null) {
                field.setAccessible(true);
                HttpServletRequest req = (HttpServletRequest) field.get(stream);
                field = FieldLookup.findField(req.getClass(), "_metaData");
                if (field == null)
                    return null;

                field.setAccessible(true);
                return (MetaData) field.get(req);
            }
        } catch (IllegalAccessException ex) {
            return null;
        }

        Field inField = FieldLookup.findField(stream.getClass(), "in");
        if (inField == null)
            return null;

        inField.setAccessible(true);
        try {
            stream = inField.get(stream);
        } catch (IllegalAccessException e) {
            return null;
        }
    }
}
 
Example #15
Source File: HttpRequestParamsReader.java    From tika-server with Apache License 2.0 5 votes vote down vote up
public void initialize(InputStream stream) {
    if (initialized)
        return;
    initialized = true;
    MetaData metaDict = getMetaDataField(stream);
    if (metaDict == null)
        return;

    HttpFields fields = metaDict.getFields();
    for (HttpField field : fields)
        rawParams.put(field.getName(), field.getValue());
    GetCommonFlags();
}
 
Example #16
Source File: HttpResponseStatisticsCollectorTest.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public void push(MetaData.Request request) {
}
 
Example #17
Source File: AccessLogRequestLogTest.java    From vespa with Apache License 2.0 4 votes vote down vote up
private Response createResponseMock() {
    Response response = mock(Response.class);
    when(response.getHttpChannel()).thenReturn(mock(HttpChannel.class));
    when(response.getCommittedMetaData()).thenReturn(mock(MetaData.Response.class));
    return response;
}
 
Example #18
Source File: JettyService.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public void push(MetaData.Request request) {}
 
Example #19
Source File: Response.java    From onedev with MIT License 4 votes vote down vote up
protected MetaData.Response newResponseMetaData()
{
    MetaData.Response info = new MetaData.Response(_channel.getRequest().getHttpVersion(), getStatus(), getReason(), _fields, getLongContentLength());
    info.setTrailerSupplier(getTrailers());
    return info;
}
 
Example #20
Source File: HeadersFrame.java    From PacketProxy with Apache License 2.0 4 votes vote down vote up
private void decodeToHttp(HpackDecoder decoder) throws Exception {
	if ((super.flags & FLAG_EXTRA) > 0) {
		return;
	}
	if (decoder == null) {
		return;
	}
   	ByteBuffer in = ByteBuffer.allocate(65535);
   	in.put(super.payload);
   	in.flip();
   	
   	if ((super.flags & FLAG_PRIORITY) > 0) {
   		priority = true;
   		dependency = in.getInt() & 0x7fffffff;
   		weight = in.get();
   	}

   	MetaData meta = decoder.decode(in);

   	isGRPC2ndResponseHeader = false;

   	if (meta instanceof Request) {
   		//System.out.println("# meta.request: " + meta);
   		bRequest = true;
   		Request req = (Request)meta;
   		method = req.getMethod();
   		version = req.getHttpVersion();
   		uriString = req.getURIString();
   		HttpURI uri = req.getURI();
   		scheme = uri.getScheme();
   		authority = uri.getAuthority();
   		path = uri.getPath();
   		query = uri.getQuery();
   		
   	} else if (meta instanceof Response) {
   		//System.out.println("# meta.response: " + meta);
   		bResponse = true;
   		Response res = (Response)meta;
   		status = res.getStatus();
   	} else {
   		//gRPC Trailer Frame
  			bTrailer = true;
   	}
   	fields = meta.getFields();

   	if(bTrailer){
   		for(HttpField i:fields){
   			if(i.getName().contains("grpc-status")){
   				isGRPC2ndResponseHeader = true;
   				break;
			}
		}
	}
   	
	ByteArrayOutputStream buf = new ByteArrayOutputStream();
	if (bRequest) {
		String queryStr = (query != null && query.length() > 0) ? "?" + query : "";
		//String fragmentStr = (fragment != null && fragment.length() > 0) ? "#"+fragment : "";
		String statusLine = String.format("%s %s%s HTTP/2\r\n", method, path, queryStr);
		buf.write(statusLine.getBytes());
	} else {
		buf.write(String.format("HTTP/2 %d %s\r\n", status, HttpStatus.getMessage(status)).getBytes());
	}
	for (HttpField field: fields) {
		buf.write(String.format("%s: %s\r\n", field.getName(), field.getValue()).getBytes());
	}
	if(!isGRPC2ndResponseHeader) {
		if (bRequest) {
			buf.write(String.format("X-PacketProxy-HTTP2-Host: %s\r\n", authority).getBytes());
		}
		if (priority) {
			buf.write(String.format("X-PacketProxy-HTTP2-Dependency: %d\r\n", dependency).getBytes());
			buf.write(String.format("X-PacketProxy-HTTP2-Weight: %d\r\n", weight & 0xff).getBytes());
		}
		buf.write(String.format("X-PacketProxy-HTTP2-Stream-Id: %d\r\n", streamId).getBytes());
		buf.write(String.format("X-PacketProxy-HTTP2-Flags: %d\r\n", flags).getBytes());
		buf.write(String.format("X-PacketProxy-HTTP2-UUID: %s\r\n", StringUtils.randomUUID()).getBytes());
	}
	buf.write("\r\n".getBytes());

   	saveExtra(buf.toByteArray());
}
 
Example #21
Source File: JettyClientExample.java    From http2-examples with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) throws Exception {
    long startTime = System.nanoTime();

    // Create and start HTTP2Client.
    HTTP2Client client = new HTTP2Client();
    SslContextFactory sslContextFactory = new SslContextFactory(true);
    client.addBean(sslContextFactory);
    client.start();

    // Connect to host.
    String host = "localhost";
    int port = 8443;

    FuturePromise<Session> sessionPromise = new FuturePromise<>();
    client.connect(sslContextFactory, new InetSocketAddress(host, port), new ServerSessionListener.Adapter(), sessionPromise);

    // Obtain the client Session object.
    Session session = sessionPromise.get(5, TimeUnit.SECONDS);

    // Prepare the HTTP request headers.
    HttpFields requestFields = new HttpFields();
    requestFields.put("User-Agent", client.getClass().getName() + "/" + Jetty.VERSION);
    // Prepare the HTTP request object.
    MetaData.Request request = new MetaData.Request("GET", new HttpURI("https://" + host + ":" + port + "/"), HttpVersion.HTTP_2, requestFields);
    // Create the HTTP/2 HEADERS frame representing the HTTP request.
    HeadersFrame headersFrame = new HeadersFrame(request, null, true);

    // Prepare the listener to receive the HTTP response frames.
    Stream.Listener responseListener = new Stream.Listener.Adapter()
    {
        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback)
        {
            byte[] bytes = new byte[frame.getData().remaining()];
            frame.getData().get(bytes);
            int duration = (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
            System.out.println("After " + duration + " seconds: " + new String(bytes));
            callback.succeeded();
        }
    };

    session.newStream(headersFrame, new FuturePromise<>(), responseListener);
    session.newStream(headersFrame, new FuturePromise<>(), responseListener);
    session.newStream(headersFrame, new FuturePromise<>(), responseListener);

    Thread.sleep(TimeUnit.SECONDS.toMillis(20));

    client.stop();
}
 
Example #22
Source File: Response.java    From onedev with MIT License 3 votes vote down vote up
/**
 * Get the MetaData.Response committed for this response.
 * This may differ from the meta data in this response for
 * exceptional responses (eg 4xx and 5xx responses generated
 * by the container) and the committedMetaData should be used
 * for logging purposes.
 *
 * @return The committed MetaData or a {@link #newResponseMetaData()}
 * if not yet committed.
 */
public MetaData.Response getCommittedMetaData()
{
    MetaData.Response meta = _channel.getCommittedMetaData();
    if (meta == null)
        return newResponseMetaData();
    return meta;
}