org.eclipse.jetty.client.api.Response Java Examples

The following examples show how to use org.eclipse.jetty.client.api.Response. 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: JettyXhrTransport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void onContent(Response response, ByteBuffer buffer) {
	while (true) {
		if (this.sockJsSession.isDisconnected()) {
			if (logger.isDebugEnabled()) {
				logger.debug("SockJS sockJsSession closed, closing response.");
			}
			response.abort(new SockJsException("Session closed.", this.sockJsSession.getId(), null));
			return;
		}
		if (buffer.remaining() == 0) {
			break;
		}
		int b = buffer.get();
		if (b == '\n') {
			handleFrame();
		}
		else {
			this.outputStream.write(b);
		}
	}
}
 
Example #2
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 #3
Source File: ReverseProxyServlet.java    From logbook with MIT License 6 votes vote down vote up
@Override
protected void onResponseContent(HttpServletRequest request, HttpServletResponse response, Response proxyResponse,
        byte[] buffer, int offset, int length, Callback callback) {
    // フィルタークラスで必要かどうかを判別後、必要であれば内容をキャプチャする
    // 注意: 1回のリクエストで複数回の応答が帰ってくるので全ての応答をキャプチャする必要がある
    if (Filter.isNeed(request.getServerName(), response.getContentType())) {
        ByteArrayOutputStream stream = (ByteArrayOutputStream) request.getAttribute(Filter.RESPONSE_BODY);
        if (stream == null) {
            stream = new ByteArrayOutputStream();
            request.setAttribute(Filter.RESPONSE_BODY, stream);
        }
        // ストリームに書き込む
        stream.write(buffer, offset, length);
    }
    super.onResponseContent(request, response, proxyResponse, buffer, offset, length, callback);
}
 
Example #4
Source File: AsyncHttpExecutableTest.java    From cougar with Apache License 2.0 6 votes vote down vote up
private void fireResponse(CapturingRequest request, int errorCode, String responseText, int resultSize, ObservableObserver observer, boolean successfulResponse) throws InterruptedException {
    Response.CompleteListener listener = request.awaitSend(1000, TimeUnit.MILLISECONDS);
    assertNotNull(listener);
    InputStreamResponseListener responseListener = (InputStreamResponseListener) listener;

    Result result = mock(Result.class);
    Response response = mock(Response.class);
    when(result.getResponse()).thenReturn(response);
    when(result.isSucceeded()).thenReturn(successfulResponse);
    when(result.isFailed()).thenReturn(!successfulResponse);
    HttpFields headers = mock(HttpFields.class);
    when(response.getHeaders()).thenReturn(headers);
    when(headers.get(HttpHeader.CONTENT_LENGTH)).thenReturn(String.valueOf(resultSize));
    when(response.getStatus()).thenReturn(errorCode);
    when(response.getVersion()).thenReturn(HttpVersion.HTTP_1_1);

    // fire that event
    responseListener.onHeaders(response);
    responseListener.onContent(response, ByteBuffer.allocate(0));
    responseListener.onComplete(result);

    assertTrue(observer.getLatch().await(1000, TimeUnit.MILLISECONDS));
}
 
Example #5
Source File: JettyXhrTransport.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void onContent(Response response, ByteBuffer buffer) {
	while (true) {
		if (this.sockJsSession.isDisconnected()) {
			if (logger.isDebugEnabled()) {
				logger.debug("SockJS sockJsSession closed, closing response.");
			}
			response.abort(new SockJsException("Session closed.", this.sockJsSession.getId(), null));
			return;
		}
		if (buffer.remaining() == 0) {
			break;
		}
		int b = buffer.get();
		if (b == '\n') {
			handleFrame();
		}
		else {
			this.outputStream.write(b);
		}
	}
}
 
Example #6
Source File: BloomFilter.java    From presto-bloomfilter with Apache License 2.0 6 votes vote down vote up
public static BloomFilter fromUrl(String url) throws Exception
{
    log.info("Loading bloom filter from " + url);

    Request request = BloomFilterScalarFunctions.HTTP_CLIENT.newRequest(url);
    request.method("GET");
    InputStreamResponseListener listener = new InputStreamResponseListener();
    request.send(listener);

    // Wait for the response headers to arrive
    Response response = listener.get(10, TimeUnit.SECONDS);

    // Look at the response
    if (response.getStatus() == 200) {
        // Use try-with-resources to close input stream.
        try (InputStream responseContent = listener.getInputStream()) {
            byte[] bytes = ByteStreams.toByteArray(responseContent);
            return newInstance(bytes);
        }
    }
    log.warn("Non-200 response status " + response.getStatus());
    return null;
}
 
Example #7
Source File: JettyXhrTransport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void onContent(Response response, ByteBuffer buffer) {
	while (true) {
		if (this.sockJsSession.isDisconnected()) {
			if (logger.isDebugEnabled()) {
				logger.debug("SockJS sockJsSession closed, closing response.");
			}
			response.abort(new SockJsException("Session closed.", this.sockJsSession.getId(), null));
			return;
		}
		if (buffer.remaining() == 0) {
			break;
		}
		int b = buffer.get();
		if (b == '\n') {
			handleFrame();
		}
		else {
			this.outputStream.write(b);
		}
	}
}
 
Example #8
Source File: HttpOperatorFactory.java    From digdag with Apache License 2.0 6 votes vote down vote up
private RuntimeException error(Request req, boolean uriIsSecret, Response res)
{
    if (HttpStatus.isClientError(res.getStatus())) {
        switch (res.getStatus()) {
            case HttpStatus.REQUEST_TIMEOUT_408:
            case HttpStatus.TOO_MANY_REQUESTS_429:
                // Retry these.
                return new RuntimeException("Failed HTTP request: " + requestStatus(req, res, uriIsSecret));
            default:
                // 4xx: The request is invalid for this resource. Fail hard without retrying.
                return new TaskExecutionException("HTTP 4XX Client Error: " + requestStatus(req, res, uriIsSecret));
        }
    }
    else if (res.getStatus() >= 500 && res.getStatus() < 600) {
        // 5xx: Server Error. This is hopefully ephemeral.
        return ephemeralError("HTTP 5XX Server Error: " + requestStatus(req, res, uriIsSecret));
    }
    else {
        // Unknown status code. Treat as an ephemeral error.
        return ephemeralError("Unexpected HTTP status: " + requestStatus(req, res, uriIsSecret));
    }
}
 
Example #9
Source File: JettyClientTags.java    From micrometer with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@code uri} tag based on the URI of the given {@code result}.
 * {@code REDIRECTION} for 3xx responses, {@code NOT_FOUND} for 404 responses.
 *
 * @param result the request result
 * @param successfulUriPattern successful URI pattern
 * @return the uri tag derived from the request result
 */
public static Tag uri(Result result, Function<Result, String> successfulUriPattern) {
    Response response = result.getResponse();
    if (response != null) {
        int status = response.getStatus();
        if (HttpStatus.isRedirection(status)) {
            return URI_REDIRECTION;
        }
        if (status == 404) {
            return URI_NOT_FOUND;
        }
    }

    String matchingPattern = successfulUriPattern.apply(result);
    matchingPattern = MULTIPLE_SLASH_PATTERN.matcher(matchingPattern).replaceAll("/");
    if (matchingPattern.equals("/")) {
        return URI_ROOT;
    }
    matchingPattern = TRAILING_SLASH_PATTERN.matcher(matchingPattern).replaceAll("");
    return Tag.of("uri", matchingPattern);
}
 
Example #10
Source File: ReverseProxyServlet.java    From logbook with MIT License 5 votes vote down vote up
@Override
protected void onProxyResponseFailure(HttpServletRequest request, HttpServletResponse response,
        Response proxyResponse,
        Throwable failure) {

    Logger logger = LogManager.getLogger(ReverseProxyServlet.class);

    logger.warn("通信に失敗しました", failure);
    logger.warn(request);
    logger.warn(proxyResponse);

    super.onProxyResponseFailure(request, response, proxyResponse, failure);
}
 
Example #11
Source File: ProxyServlet.java    From logbook-kai with MIT License 5 votes vote down vote up
protected void onResponseContent(HttpServletRequest request, HttpServletResponse response, Response proxyResponse,
        byte[] buffer, int offset, int length) throws IOException {
    response.getOutputStream().write(buffer, offset, length);
    if (this._isDebugEnabled) {
        this._log.debug("{} proxying content to downstream: {} bytes", getRequestId(request), length);
    }
}
 
Example #12
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 #13
Source File: JettyXhrTransport.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void onBegin(Response response) {
	if (response.getStatus() != 200) {
		HttpStatus status = HttpStatus.valueOf(response.getStatus());
		response.abort(new HttpServerErrorException(status, "Unexpected XHR receive status"));
	}
}
 
Example #14
Source File: ZeppelinhubRestApiHandler.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch zeppelin instances for a given user.
 * @param ticket
 * @return
 * @throws IOException
 */
public List<Instance> getInstances(String ticket) throws IOException {
  InputStreamResponseListener listener = new InputStreamResponseListener();
  Response response;
  String url = zepelinhubUrl + "instances";
  String data;

  Request request = client.newRequest(url).header(USER_SESSION_HEADER, ticket);
  request.send(listener);

  try {
    response = listener.get(30, TimeUnit.SECONDS);
  } catch (InterruptedException | TimeoutException | ExecutionException e) {
    LOG.error("Cannot perform request to ZeppelinHub", e);
    throw new IOException("Cannot perform  GET request to ZeppelinHub", e);
  }

  int code = response.getStatus();
  if (code == 200) {
    try (InputStream responseContent = listener.getInputStream()) {
      data = IOUtils.toString(responseContent, "UTF-8");
    }
  } else {
    LOG.error("ZeppelinHub GET {} returned with status {} ", url, code);
    throw new IOException("Cannot perform  GET request to ZeppelinHub");
  }
  Type listType = new TypeToken<ArrayList<Instance>>() {}.getType();
  return new Gson().fromJson(data, listType);
}
 
Example #15
Source File: ProxyServlet.java    From logbook-kai with MIT License 5 votes vote down vote up
@Override
public void onBegin(Response proxyResponse) {
    // 返事があったらサーバ側での処理は完了しているのでリトライしない
    this.retryEnabled = false;

    this.response.setStatus(proxyResponse.getStatus());
}
 
Example #16
Source File: ReverseProxyServlet.java    From logbook with MIT License 5 votes vote down vote up
@Override
protected void onProxyResponseSuccess(HttpServletRequest request, HttpServletResponse response,
        Response proxyResponse) {

    if (Filter.isNeed(request.getServerName(), response.getContentType())) {
        byte[] postField = (byte[]) request.getAttribute(Filter.REQUEST_BODY);
        ByteArrayOutputStream stream = (ByteArrayOutputStream) request.getAttribute(Filter.RESPONSE_BODY);
        if (stream != null) {
            UndefinedData data = new UndefinedData(request.getRequestURI(), postField, stream.toByteArray());
            Runnable task = new ParseDataTask(data, request.getServerName());
            ThreadManager.getExecutorService().submit(task);
        }
    }
    super.onProxyResponseSuccess(request, response, proxyResponse);
}
 
Example #17
Source File: JettyXhrTransport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void onHeaders(Response response) {
	if (logger.isTraceEnabled()) {
		// Convert to HttpHeaders to avoid "\n"
		logger.trace("XHR receive headers: " + toHttpHeaders(response.getHeaders()));
	}
}
 
Example #18
Source File: JettyXhrTransport.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void onFailure(Response response, Throwable failure) {
	if (this.connectFuture.setException(failure)) {
		return;
	}
	if (this.sockJsSession.isDisconnected()) {
		this.sockJsSession.afterTransportClosed(null);
	}
	else {
		this.sockJsSession.handleTransportError(failure);
		this.sockJsSession.afterTransportClosed(new CloseStatus(1006, failure.getMessage()));
	}
}
 
Example #19
Source File: ProxyServlet.java    From logbook-kai with MIT License 5 votes vote down vote up
protected void onResponseSuccess(HttpServletRequest request, HttpServletResponse response, Response proxyResponse) {
    AsyncContext asyncContext = (AsyncContext) request.getAttribute(ASYNC_CONTEXT);
    asyncContext.complete();
    if (this._isDebugEnabled) {
        this._log.debug("{} proxying successful", getRequestId(request));
    }
}
 
Example #20
Source File: ProxyServlet.java    From logbook-kai with MIT License 5 votes vote down vote up
protected void onResponseFailure(HttpServletRequest request, HttpServletResponse response, Response proxyResponse,
        Throwable failure) {
    if (this._isDebugEnabled) {
        this._log.debug(getRequestId(request) + " proxying failed", failure);
    }
    if (!response.isCommitted()) {
        if (failure instanceof TimeoutException)
            response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
        else
            response.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
    }
    AsyncContext asyncContext = (AsyncContext) request.getAttribute(ASYNC_CONTEXT);
    asyncContext.complete();
}
 
Example #21
Source File: ZeppelinhubRestApiHandler.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private String sendToZeppelinHubWithoutResponseBody(Request request) throws IOException {
  request.send(new Response.CompleteListener() {
    @Override
    public void onComplete(Result result) {
      Request req = result.getRequest();
      LOG.info("ZeppelinHub {} {} returned with status {}: {}", req.getMethod(),
          req.getURI(), result.getResponse().getStatus(), result.getResponse().getReason());
    }
  });
  return StringUtils.EMPTY;
}
 
Example #22
Source File: ProxyServlet.java    From logbook-kai with MIT License 5 votes vote down vote up
@Override
public void onHeaders(Response proxyResponse) {
    ProxyServlet.this.onResponseHeaders(this.request, this.response, proxyResponse);

    if (ProxyServlet.this._isDebugEnabled) {
        StringBuilder builder = new StringBuilder("\r\n");
        builder.append(this.request.getProtocol()).append(" ").append(this.response.getStatus()).append(" ")
                .append(proxyResponse.getReason()).append("\r\n");
        for (String headerName : this.response.getHeaderNames()) {
            builder.append(headerName).append(": ");
            for (Iterator<String> headerValues = this.response.getHeaders(headerName).iterator(); headerValues
                    .hasNext();) {
                String headerValue = headerValues.next();
                if (headerValue != null)
                    builder.append(headerValue);
                if (headerValues.hasNext())
                    builder.append(",");
            }
            builder.append("\r\n");
        }
        ProxyServlet.this._log.debug("{} proxying to downstream:{}{}{}{}{}",
                getRequestId(this.request),
                System.lineSeparator(),
                proxyResponse,
                System.lineSeparator(),
                proxyResponse.getHeaders().toString().trim(),
                System.lineSeparator(),
                builder);
    }
}
 
Example #23
Source File: ProxyServlet.java    From logbook-kai with MIT License 5 votes vote down vote up
@Override
public void onContent(Response proxyResponse, ByteBuffer content) {
    int offset = 0;
    int length = content.remaining();
    byte[] buffer = new byte[length];
    content.get(buffer);

    try {
        ProxyServlet.this.onResponseContent(this.request, this.response, proxyResponse, buffer, offset, length);
    } catch (IOException x) {
        proxyResponse.abort(x);
    }
}
 
Example #24
Source File: ProxyServlet.java    From logbook-kai with MIT License 5 votes vote down vote up
@Override
public void onFailure(Response proxyResponse, Throwable failure) {
    if (!this.isRetry(failure)) {
        // リトライしない
        this.retryEnabled = false;
        ProxyServlet.this.onResponseFailure(this.request, this.response, proxyResponse, failure);
    }
}
 
Example #25
Source File: ReverseProxyServlet.java    From logbook-kai with MIT License 5 votes vote down vote up
@Override
protected void onResponseContent(HttpServletRequest request, HttpServletResponse response,
        Response proxyResponse,
        byte[] buffer, int offset, int length) throws IOException {

    CaptureHolder holder = (CaptureHolder) request.getAttribute(Filter.CONTENT_HOLDER);
    if (holder == null) {
        holder = new CaptureHolder();
        request.setAttribute(Filter.CONTENT_HOLDER, holder);
    }
    // ストリームに書き込む
    holder.putResponse(buffer);

    super.onResponseContent(request, response, proxyResponse, buffer, offset, length);
}
 
Example #26
Source File: ReverseProxyServlet.java    From logbook-kai with MIT License 5 votes vote down vote up
@Override
protected void onResponseSuccess(HttpServletRequest request, HttpServletResponse response,
        Response proxyResponse) {
    try {
        if(response.getStatus() == HttpServletResponse.SC_OK) {
            CaptureHolder holder = (CaptureHolder) request.getAttribute(Filter.CONTENT_HOLDER);
            if (holder != null) {
                RequestMetaDataWrapper req = new RequestMetaDataWrapper();
                req.set(request);

                ResponseMetaDataWrapper res = new ResponseMetaDataWrapper();
                res.set(response);

                Runnable task = () -> {
                    this.invoke(req, res, holder);
                };
                ThreadManager.getExecutorService().submit(task);
            }
        }
    } catch (Exception e) {
        LoggerHolder.get().warn("リバースプロキシ サーブレットで例外が発生 req=" + request, e);
    } finally {
        // Help GC
        request.removeAttribute(Filter.CONTENT_HOLDER);
    }
    super.onResponseSuccess(request, response, proxyResponse);
}
 
Example #27
Source File: AsyncHttpExecutableTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
private BlockingQueue<Connection> queued(int inside) {
    BlockingQueue<Connection> ret = new LinkedBlockingDeque<>();
    for (int i=0; i<inside; i++) {
        ret.add(new Connection() {
            @Override
            public void send(Request request, Response.CompleteListener listener) {}
            @Override
            public void close() {}
        });
    }
    return ret;
}
 
Example #28
Source File: BaselineAsyncClientIdentityTokenResolver.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
public List<IdentityToken> resolve(Response input, X509Certificate[] certificateChain) {
    List<IdentityToken> credentials = new ArrayList<IdentityToken>();

    for (SimpleIdentityTokenName securityToken : SimpleIdentityTokenName.values()) {
        String authHeaderValue = input.getHeaders().getStringField(TOKEN_PREFIX + securityToken.name());
        if (authHeaderValue != null) {
            credentials.add(new IdentityToken(securityToken.name(), authHeaderValue));
        }
    }

    return credentials;
}
 
Example #29
Source File: CommandProxyServlet.java    From Scribengin with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onHeaders(Response proxyResponse){
    onResponseHeaders(request, response, proxyResponse);

    if (_log.isDebugEnabled())
    {
        StringBuilder builder = new StringBuilder("\r\n");
        builder.append(request.getProtocol()).append(" ").append(response.getStatus()).append(" ").append(proxyResponse.getReason()).append("\r\n");
        for (String headerName : response.getHeaderNames())
        {
            builder.append(headerName).append(": ");
            for (Iterator<String> headerValues = response.getHeaders(headerName).iterator(); headerValues.hasNext();)
            {
                String headerValue = headerValues.next();
                if (headerValue != null)
                    builder.append(headerValue);
                if (headerValues.hasNext())
                    builder.append(",");
            }
            builder.append("\r\n");
        }
        _log.debug("{} proxying to downstream:{}{}{}{}{}",
                getRequestId(request),
                System.lineSeparator(),
                proxyResponse,
                System.lineSeparator(),
                proxyResponse.getHeaders().toString().trim(),
                System.lineSeparator(),
                builder);
    }
}
 
Example #30
Source File: CommandProxyServlet.java    From Scribengin with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onContent(final Response proxyResponse, ByteBuffer content, final Callback callback){
    byte[] buffer;
    int offset;
    int length = content.remaining();
    if (content.hasArray())
    {
        buffer = content.array();
        offset = content.arrayOffset();
    }
    else
    {
        buffer = new byte[length];
        content.get(buffer);
        offset = 0;
    }

    onResponseContent(request, response, proxyResponse, buffer, offset, length, new Callback(){
        @Override
        public void succeeded()
        {
            callback.succeeded();
        }

        @Override
        public void failed(Throwable x)
        {
            callback.failed(x);
            proxyResponse.abort(x);
        }
    });
}