org.eclipse.jetty.http.HttpURI Java Examples

The following examples show how to use org.eclipse.jetty.http.HttpURI. 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: OAuth2InteractiveAuthenticatorTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private Map<String, String> getRedirectParameters(final String redirectLocation)
{

    final MultiMap<String> parameterMap = new MultiMap<>();
    HttpURI httpURI = new HttpURI(redirectLocation);
    httpURI.decodeQueryTo(parameterMap);
    Map<String,String> parameters = new HashMap<>(parameterMap.size());
    for (Map.Entry<String, List<String>> paramEntry : parameterMap.entrySet())
    {
        assertEquals(String.format("param '%s' specified more than once", paramEntry.getKey()),
                            (long) 1,
                            (long) paramEntry.getValue().size());

        parameters.put(paramEntry.getKey(), paramEntry.getValue().get(0));
    }
    return parameters;
}
 
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_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 #4
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 #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: 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 #7
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 #8
Source File: Jetty9RequestTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetRequestUri() {
    HttpURI requestUri = new HttpURI("foo/bar/baz");
    when(request.getHttpURI()).thenReturn(requestUri);
    jetty9Request.setRequestURI("foo/junk?a=b&c=d");
    assertThat(requestUri.getPath(), is("foo/junk?a=b&c=d"));
}
 
Example #9
Source File: Jetty9RequestTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    initMocks(this);
    jetty9Request = new Jetty9Request(request);
    when(request.getHttpURI()).thenReturn(new HttpURI("foo/bar/baz"));
    when(request.getRootURL()).thenReturn(new StringBuilder("http://junk/"));
}
 
Example #10
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 #11
Source File: RemoteURLProxyServlet.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public RemoteURLProxyServlet(URL url, boolean failEarlyOn404) {
	try {
		this.url = new HttpURI(url.toURI());
		this.failEarlyOn404 = failEarlyOn404;
	} catch (URISyntaxException e) {
		//should be well formed
		throw new RuntimeException(e);
	}
}
 
Example #12
Source File: ServerRuntime.java    From EDDI with Apache License 2.0 5 votes vote down vote up
private Filter createInitThreadBoundValuesFilter() {
    return new Filter() {
        @Override
        public void init(FilterConfig filterConfig) {
            //not implemented
        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpURI httpURI;
            String requestUrl;
            if (servletRequest instanceof Request) {
                httpURI = ((Request) servletRequest).getHttpURI();
                requestUrl = ((Request) servletRequest).getRequestURL().toString();
            } else {
                HttpServletRequest httpservletRequest = (HttpServletRequest) servletRequest;
                requestUrl = httpservletRequest.getRequestURL().toString();
                Request request = Request.getBaseRequest(((HttpServletRequestWrapper) httpservletRequest).getRequest());
                httpURI = request.getHttpURI();
            }

            URL requestURL = URI.create(requestUrl).toURL();
            String currentResourceURI = httpURI.getPathQuery();
            ThreadContext.put("currentResourceURI", currentResourceURI);
            ThreadContext.put("currentURLProtocol", requestURL.getProtocol());
            ThreadContext.put("currentURLHost", requestURL.getHost());
            ThreadContext.put("currentURLPort", requestURL.getPort());

            filterChain.doFilter(servletRequest, servletResponse);

            ThreadContext.remove();
        }

        @Override
        public void destroy() {
            //not implemented
        }
    };
}
 
Example #13
Source File: HttpRequest.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static Map<String, List<String>> getUriQueryParameters(URI uri) {
    MultiMap<String> queryParameters = new MultiMap<>();
    new HttpURI(uri).decodeQueryTo(queryParameters);

    // Do a deep copy so we do not leak Jetty classes outside
    Map<String, List<String>> deepCopiedQueryParameters = new HashMap<>();
    for (Map.Entry<String, List<String>> entry : queryParameters.entrySet()) {
        deepCopiedQueryParameters.put(entry.getKey(), new ArrayList<>(entry.getValue()));
    }
    return deepCopiedQueryParameters;
}
 
Example #14
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 #15
Source File: CustomOpenIdProviderHandler.java    From OpenID-Attacker with GNU General Public License v2.0 5 votes vote down vote up
private void handleRequest(ParameterList requestParameter, String target, HttpServletResponse response, Request baseRequest) throws IOException, OpenIdAttackerServerException, TransformerException {
       // get the openIdProcessor.mode
       final String method = baseRequest.getMethod();
       final HttpURI uri = baseRequest.getUri();
       final String protocol = baseRequest.getProtocol();
       final String info = String.format("%s %s %s", method, uri, protocol);
       final String mode = requestParameter.hasParameter("openid.mode")
         ? requestParameter.getParameterValue("openid.mode") : null;

if (uri.getCompletePath().equals("/favicon.ico")) {
           handleFaviconRequest(info, response);
       } else if (target.contains("xxe")) {
           // Case: XXE
           handleXxeRequest(info, response, requestParameter);
       } /*else if (target.contains("dtd")) {
           // Case: DTD
           handleDtdRequest(info, response, requestParameter);
       }*/ else if (mode == null) {
           if (target.contains("xrds") || requestParameter.toString().contains("xrds")) {
               // Case: Request XRDS Document
               handleXrdsRequest(info, response);                
           } else {
               // Case: Request HTML Document
               handleHtmlDiscovery(info, response);
           }
       } else if ("associate".equals(mode)) {
           // Case: Process Association
           handleAssociationRequest(info, response, requestParameter);
       } else if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) {
           // Case: Generate Token
           handleTokenRequest(info, response, requestParameter);
       } else if ("check_authentication".equals(mode)) {
           handleCheckAuthentication(info, response, requestParameter);
       } else {
           throw new IllegalStateException("Unknown Request");
       }
       baseRequest.setHandled(true);
   }
 
Example #16
Source File: EchoServiceClient.java    From java-11-examples with Apache License 2.0 4 votes vote down vote up
public EchoServiceClient(String host, int port, KeyStore keyStore, String keyStorePassword) {
    super(host, port, keyStore, keyStorePassword);
    this.objectMapper = new ObjectMapper();
    this.echoServiceURI = new HttpURI("https://" + host + ":" + port + "/stream/echo");
}
 
Example #17
Source File: RemoteURLProxyServlet.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected HttpURI proxyHttpURI(final String scheme, final String serverName, int serverPort, final String uri) throws MalformedURLException {
	return url;
}
 
Example #18
Source File: SystemInfoServiceClient.java    From java-11-examples with Apache License 2.0 4 votes vote down vote up
public SystemInfoServiceClient(String host, int port, KeyStore keyStore, String keyStorePassword) {
    super(host, port, keyStore, keyStorePassword);
    this.getSystemInfoURI = new HttpURI("https://" + host + ":" + port + "/data/system/info");
}
 
Example #19
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 #20
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();
}