org.eclipse.jetty.http.HttpField Java Examples

The following examples show how to use org.eclipse.jetty.http.HttpField. 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: OcJettyHttpClientExtractorTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testExtraction() {
  HttpFields fields = new HttpFields();
  fields.add(new HttpField("User-Agent", "Test 1.0"));

  Request request = mock(Request.class);
  Response response = mock(Response.class);
  OcJettyHttpClientExtractor extractor = new OcJettyHttpClientExtractor();
  when(request.getHost()).thenReturn("localhost");
  when(request.getMethod()).thenReturn("GET");
  when(request.getHeaders()).thenReturn(fields);
  when(request.getPath()).thenReturn("/test");
  when(request.getURI()).thenReturn(uri);
  when(response.getStatus()).thenReturn(0);

  assertThat(extractor.getHost(request)).contains("localhost");
  assertThat(extractor.getMethod(request)).contains("GET");
  assertThat(extractor.getPath(request)).contains("/test");
  assertThat(extractor.getUrl(request)).contains(URI_STR);
  assertThat(extractor.getRoute(request)).contains("");
  assertThat(extractor.getUserAgent(request)).contains("Test 1.0");
  assertThat(extractor.getStatusCode(response)).isEqualTo(0);
}
 
Example #2
Source File: HttpOperatorFactory.java    From digdag with Apache License 2.0 6 votes vote down vote up
HttpClient client()
{
    boolean insecure = params.get("insecure", boolean.class, false);

    HttpClient httpClient = new HttpClient(new SslContextFactory(insecure));

    configureProxy(httpClient);

    boolean followRedirects = params.get("follow_redirects", boolean.class, true);

    httpClient.setFollowRedirects(followRedirects);
    httpClient.setMaxRedirects(maxRedirects);

    httpClient.setUserAgentField(new HttpField(
            USER_AGENT, userAgent + ' ' + httpClient.getUserAgentField().getValue()));

    try {
        httpClient.start();
    }
    catch (Exception e) {
        throw new TaskExecutionException(e);
    }
    return httpClient;
}
 
Example #3
Source File: JettyHeadersAdapter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Map<String, String> toSingleValueMap() {
	Map<String, String> singleValueMap = new LinkedHashMap<>(this.headers.size());
	Iterator<HttpField> iterator = this.headers.iterator();
	iterator.forEachRemaining(field -> {
		if (!singleValueMap.containsKey(field.getName())) {
			singleValueMap.put(field.getName(), field.getValue());
		}
	});
	return singleValueMap;
}
 
Example #4
Source File: JettyHeadersAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Map<String, String> toSingleValueMap() {
	Map<String, String> singleValueMap = new LinkedHashMap<>(this.headers.size());
	Iterator<HttpField> iterator = this.headers.iterator();
	iterator.forEachRemaining(field -> {
		if (!singleValueMap.containsKey(field.getName())) {
			singleValueMap.put(field.getName(), field.getValue());
		}
	});
	return singleValueMap;
}
 
Example #5
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 #6
Source File: Response.java    From onedev with MIT License 5 votes vote down vote up
public void resetContent()
{
    _out.resetBuffer();
    _outputType = OutputType.NONE;
    _contentLength = -1;
    _contentType = null;
    _mimeType = null;
    _characterEncoding = null;
    _encodingFrom = EncodingFrom.NOT_SET;

    // remove the content related response headers and keep all others
    for (Iterator<HttpField> i = getHttpFields().iterator(); i.hasNext(); )
    {
        HttpField field = i.next();
        if (field.getHeader() == null)
            continue;

        switch (field.getHeader())
        {
            case CONTENT_TYPE:
            case CONTENT_LENGTH:
            case CONTENT_ENCODING:
            case CONTENT_LANGUAGE:
            case CONTENT_RANGE:
            case CONTENT_MD5:
            case CONTENT_LOCATION:
            case TRANSFER_ENCODING:
            case CACHE_CONTROL:
            case LAST_MODIFIED:
            case EXPIRES:
            case ETAG:
            case DATE:
            case VARY:
                i.remove();
                continue;
            default:
        }
    }
}
 
Example #7
Source File: HttpClientWrapper.java    From EDDI with Apache License 2.0 5 votes vote down vote up
private static Map<String, String> convertHeaderToMap(HttpFields headers) {
    Map<String, String> httpHeader = new HashMap<>();
    for (HttpField header : headers) {
        httpHeader.put(header.getName(), header.getValue());
    }
    return httpHeader;
}
 
Example #8
Source File: RestBufferManager.java    From incubator-retired-htrace with Apache License 2.0 5 votes vote down vote up
/**
 * Create an HttpClient instance.
 *
 * @param connTimeout         The timeout to use for connecting.
 * @param idleTimeout         The idle timeout to use.
 */
static HttpClient createHttpClient(long connTimeout, long idleTimeout) {
  HttpClient httpClient = new HttpClient();
  httpClient.setUserAgentField(
      new HttpField(HttpHeader.USER_AGENT, "HTracedSpanReceiver"));
  httpClient.setConnectTimeout(connTimeout);
  httpClient.setIdleTimeout(idleTimeout);
  return httpClient;
}
 
Example #9
Source File: ProxyServlet.java    From logbook-kai with MIT License 5 votes vote down vote up
protected void onResponseHeaders(HttpServletRequest request, HttpServletResponse response, Response proxyResponse) {
    for (HttpField field : proxyResponse.getHeaders()) {
        String headerName = field.getName();
        String lowerHeaderName = headerName.toLowerCase(Locale.ENGLISH);
        if (HOP_HEADERS.contains(lowerHeaderName))
            continue;

        String newHeaderValue = this.filterResponseHeader(request, headerName, field.getValue());
        if ((newHeaderValue == null) || (newHeaderValue.trim().length() == 0))
            continue;

        response.addHeader(headerName, newHeaderValue);
    }
}
 
Example #10
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 #11
Source File: JettyReactiveHttpResponse.java    From feign-reactive with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, List<String>> headers() {
	return clientResponse.getHeaders().stream()
			.collect(Collectors.toMap(HttpField::getName, field -> asList(field.getValues())));
}
 
Example #12
Source File: Response.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Replace (or add) a cookie.
 * Using name, path and domain, look for a matching set-cookie header and replace it.
 *
 * @param cookie The cookie to add/replace
 */
public void replaceCookie(HttpCookie cookie)
{
    for (ListIterator<HttpField> i = _fields.listIterator(); i.hasNext(); )
    {
        HttpField field = i.next();

        if (field.getHeader() == HttpHeader.SET_COOKIE)
        {
            CookieCompliance compliance = getHttpChannel().getHttpConfiguration().getResponseCookieCompliance();

            HttpCookie oldCookie;
            if (field instanceof SetCookieHttpField)
                oldCookie = ((SetCookieHttpField)field).getHttpCookie();
            else
                oldCookie = new HttpCookie(field.getValue());

            if (!cookie.getName().equals(oldCookie.getName()))
                continue;

            if (cookie.getDomain() == null)
            {
                if (oldCookie.getDomain() != null)
                    continue;
            }
            else if (!cookie.getDomain().equalsIgnoreCase(oldCookie.getDomain()))
                continue;

            if (cookie.getPath() == null)
            {
                if (oldCookie.getPath() != null)
                    continue;
            }
            else if (!cookie.getPath().equals(oldCookie.getPath()))
                continue;

            i.set(new SetCookieHttpField(cookie, compliance));
            return;
        }
    }

    // Not replaced, so add normally
    addCookie(cookie);
}
 
Example #13
Source File: Response.java    From onedev with MIT License 4 votes vote down vote up
public void putHeaders(HttpContent content, long contentLength, boolean etag)
{
    HttpField lm = content.getLastModified();
    if (lm != null)
        _fields.put(lm);

    if (contentLength == 0)
    {
        _fields.put(content.getContentLength());
        _contentLength = content.getContentLengthValue();
    }
    else if (contentLength > 0)
    {
        _fields.putLongField(HttpHeader.CONTENT_LENGTH, contentLength);
        _contentLength = contentLength;
    }

    HttpField ct = content.getContentType();
    if (ct != null)
    {
        if (_characterEncoding != null &&
            content.getCharacterEncoding() == null &&
            content.getContentTypeValue() != null &&
            __explicitCharset.contains(_encodingFrom))
        {
            setContentType(MimeTypes.getContentTypeWithoutCharset(content.getContentTypeValue()));
        }
        else
        {
            _fields.put(ct);
            _contentType = ct.getValue();
            _characterEncoding = content.getCharacterEncoding();
            _mimeType = content.getMimeType();
        }
    }

    HttpField ce = content.getContentEncoding();
    if (ce != null)
        _fields.put(ce);

    if (etag)
    {
        HttpField et = content.getETag();
        if (et != null)
            _fields.put(et);
    }
}
 
Example #14
Source File: JettyHttpServer.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public HttpField getVaryField() {
    return GzipHttpOutputInterceptor.VARY_ACCEPT_ENCODING;
}
 
Example #15
Source File: BlockingProxyServlet.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    URI uri = service.uriFromRequest(request);

    if (uri == null) {
        service.sendError(request, response);
    } else {
        Request httpRequest = httpClient.newRequest(uri);

        service.maybeAppendAuthHeader(uri, httpRequest);

        InputStreamResponseListener listener = new InputStreamResponseListener();

        // do the client request
        try {
            httpRequest.send(listener);
            // wait for the response headers to arrive or the timeout to expire
            Response httpResponse = listener.get(TIMEOUT, TimeUnit.MILLISECONDS);

            // get response headers
            HttpFields headers = httpResponse.getHeaders();
            Iterator<HttpField> iterator = headers.iterator();

            // copy all headers
            while (iterator.hasNext()) {
                HttpField header = iterator.next();
                response.setHeader(header.getName(), header.getValue());
            }
        } catch (Exception e) {
            if (e instanceof TimeoutException) {
                logger.warn("Proxy servlet failed to stream content due to a timeout");
                response.sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT);
            } else {
                logger.warn("Proxy servlet failed to stream content: {}", e.getMessage());
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            }
            return;
        }
        // now copy/stream the body content
        try (InputStream responseContent = listener.getInputStream()) {
            responseContent.transferTo(response.getOutputStream());
        }
    }
}
 
Example #16
Source File: BlockingProxyServlet.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    URI uri = service.uriFromRequest(request);

    if (uri == null) {
        service.sendError(request, response);
    } else {
        Request httpRequest = httpClient.newRequest(uri);

        service.maybeAppendAuthHeader(uri, httpRequest);

        InputStreamResponseListener listener = new InputStreamResponseListener();

        // do the client request
        try {
            httpRequest.send(listener);
            // wait for the response headers to arrive or the timeout to expire
            Response httpResponse = listener.get(TIMEOUT, TimeUnit.MILLISECONDS);

            // get response headers
            HttpFields headers = httpResponse.getHeaders();
            Iterator<HttpField> iterator = headers.iterator();

            // copy all headers
            while (iterator.hasNext()) {
                HttpField header = iterator.next();
                response.setHeader(header.getName(), header.getValue());
            }
        } catch (Exception e) {
            if (e instanceof TimeoutException) {
                logger.warn("Proxy servlet failed to stream content due to a timeout");
                response.sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT);
            } else {
                logger.warn("Proxy servlet failed to stream content: {}", e.getMessage());
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            }
            return;
        }
        // now copy/stream the body content
        try (InputStream responseContent = listener.getInputStream()) {
            IOUtils.copy(responseContent, response.getOutputStream());
        }
    }
}