Java Code Examples for org.eclipse.jetty.http.HttpFields#put()

The following examples show how to use org.eclipse.jetty.http.HttpFields#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: JettyReactiveHttpClient.java    From feign-reactive with Apache License 2.0 6 votes vote down vote up
protected void setUpHeaders(ReactiveHttpRequest request, HttpFields httpHeaders) {
	request.headers().forEach(httpHeaders::put);

	String acceptHeader;
	if(CharSequence.class.isAssignableFrom(returnActualClass) && returnPublisherClass == Mono.class){
		acceptHeader = TEXT;
	}
	else if(returnActualClass == ByteBuffer.class || returnActualClass == byte[].class){
		acceptHeader = APPLICATION_OCTET_STREAM;
	}
	else if(returnPublisherClass == Mono.class){
		acceptHeader = APPLICATION_JSON;
	}
	else {
		acceptHeader = APPLICATION_STREAM_JSON;
	}
	httpHeaders.put(ACCEPT.asString(), singletonList(acceptHeader));
}
 
Example 2
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 3
Source File: AssetServlet.java    From onedev with MIT License 5 votes vote down vote up
public AssetServlet() {
	super(new ResourceService() {
		
		@Override
		protected void putHeaders(HttpServletResponse response, HttpContent content, long contentLength) {
			super.putHeaders(response, content, contentLength);
			
			HttpFields fields;
			if (response instanceof Response)
				fields = ((Response) response).getHttpFields();
			else
				fields = ((Response)((HttpServletResponseWrapper) response).getResponse()).getHttpFields();
			
			if (requestHolder.get().getDispatcherType() == DispatcherType.ERROR) {
				/*
				 * Do not cache error page and also makes sure that error page is not eligible for 
				 * modification check. That is, error page will be always retrieved.
				 */
	            fields.put(HttpHeader.CACHE_CONTROL, "must-revalidate,no-cache,no-store");
			} else if (requestHolder.get().getRequestURI().equals("/favicon.ico")) {
				/*
				 * Make sure favicon request is cached. Otherwise, it will be requested for every 
				 * page request.
				 */
				fields.put(HttpHeader.CACHE_CONTROL, "max-age=86400,public");
			}
		}
		
	});
}
 
Example 4
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 5
Source File: FileHandler.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void setCaching(final HttpServletResponse response, final int expiresSeconds) {
    if (response instanceof org.eclipse.jetty.server.Response) {
        org.eclipse.jetty.server.Response r = (org.eclipse.jetty.server.Response) response;
        HttpFields fields = r.getHttpFields();
        
        // remove the last-modified field since caching otherwise does not work
        /*
           https://www.ietf.org/rfc/rfc2616.txt
           "if the response does have a Last-Modified time, the heuristic
           expiration value SHOULD be no more than some fraction of the interval
           since that time. A typical setting of this fraction might be 10%."
        */
        fields.remove(HttpHeader.LAST_MODIFIED); // if this field is present, the reload-time is a 10% fraction of ttl and other caching headers do not work

        // cache-control: allow shared caching (i.e. proxies) and set expires age for cache
        if(expiresSeconds == 0){
            fields.put(HttpHeader.CACHE_CONTROL, "public, no-store, max-age=" + Integer.toString(expiresSeconds)); // seconds
        }
        else {
            fields.put(HttpHeader.CACHE_CONTROL, "public, max-age=" + Integer.toString(expiresSeconds)); // seconds
        }
    } else {
        response.setHeader(HttpHeader.LAST_MODIFIED.asString(), ""); // not really the best wqy to remove this header but there is no other option
        if(expiresSeconds == 0){
            response.setHeader(HttpHeader.CACHE_CONTROL.asString(), "public, no-store, max-age=" + Integer.toString(expiresSeconds));
        }
        else{
            response.setHeader(HttpHeader.CACHE_CONTROL.asString(), "public, max-age=" + Integer.toString(expiresSeconds));
        }

    }

    // expires: define how long the file shall stay in a cache if cache-control is not used for this information
    response.setDateHeader(HttpHeader.EXPIRES.asString(), System.currentTimeMillis() + expiresSeconds * 1000);
}
 
Example 6
Source File: BasicToApiKeyAuthenticationFilter.java    From emodb with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 7
Source File: JettyHTTPDestinationTest.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(Request.class);
    response = EasyMock.createMock(Response.class);
    request.getMethod();
    EasyMock.expectLastCall().andReturn(method).atLeastOnce();
    //request.getConnection();
    //EasyMock.expectLastCall().andReturn(null).anyTimes();
    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();
        request.setHandled(true);
        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.getMethod()).andReturn(method);
            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("org.eclipse.jetty.ajax.Continuation")).andReturn(null);
            EasyMock.expect(request.getAttribute("http.service.redirection")).andReturn(null).anyTimes();

            HttpFields httpFields = new HttpFields();
            httpFields.add("content-type", "text/xml");
            httpFields.add("content-type", "charset=utf8");
            httpFields.put(JettyHTTPDestinationTest.AUTH_HEADER, JettyHTTPDestinationTest.BASIC_AUTH);

            EasyMock.expect(request.getHeaderNames()).andReturn(httpFields.getFieldNames());
            request.getHeaders("content-type");
            EasyMock.expectLastCall().andReturn(httpFields.getValues("content-type"));
            request.getHeaders(JettyHTTPDestinationTest.AUTH_HEADER);
            EasyMock.expectLastCall().andReturn(
                httpFields.getValues(JettyHTTPDestinationTest.AUTH_HEADER));

            EasyMock.expect(request.getInputStream()).andReturn(is);
            request.setHandled(true);
            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 8
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();
}