com.sun.jersey.api.client.ClientRequest Java Examples

The following examples show how to use com.sun.jersey.api.client.ClientRequest. 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: RequestLogger.java    From qaf with MIT License 6 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
	long id = ++_id;

	StringBuilder requestString = new StringBuilder();
	logRequest(id, request, requestString);

	LoggingBean loggingBean = new LoggingBean();
	loggingBean.setCommandName(request.getMethod() + ":" + request.getURI());

	loggingBean.setArgs(new String[] { request.getURI().getPath(), request.getURI().getQuery() });

	ClientResponse response = getNext().handle(request);
	loggingBean.setResult(response.toString());
	StringBuilder responseString = logResponse(id, response);

	LoggingBean detailsLoggingBean = new LoggingBean();
	detailsLoggingBean.setArgs(new String[] { noPrifix(requestString).toString() });
	detailsLoggingBean.setResult(noPrifix(responseString).toString());

	loggingBean.getSubLogs().add(detailsLoggingBean);

	TestBaseProvider.instance().get().getLog().add(loggingBean);

	return response;
}
 
Example #2
Source File: RequestLogger.java    From qaf with MIT License 6 votes vote down vote up
private void printRequestHeaders(StringBuilder b, long id, MultivaluedMap<String, Object> headers) {
	for (Map.Entry<String, List<Object>> e : headers.entrySet()) {
		List<Object> val = e.getValue();
		String header = e.getKey();

		if (val.size() == 1) {
			prefixId(b, id).append(REQUEST_PREFIX).append(header).append(": ")
					.append(ClientRequest.getHeaderValue(val.get(0))).append("\n");
		} else {
			StringBuilder sb = new StringBuilder();
			boolean add = false;
			for (Object o : val) {
				if (add) {
					sb.append(',');
				}
				add = true;
				sb.append(ClientRequest.getHeaderValue(o));
			}
			prefixId(b, id).append(REQUEST_PREFIX).append(header).append(": ").append(sb.toString()).append("\n");
		}
	}
}
 
Example #3
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest request)
		throws ClientHandlerException {
	if (this.logger.isLoggable(Level.FINE)) {
		long id = ++this._id;
		logRequest(id, request);
		
		ClientResponse response = getNext().handle(request);

		logResponse(id, response);

		return response;
	} else{
		return getNext().handle(request);			
	}

}
 
Example #4
Source File: RequestEncoder.java    From jersey-hmac-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Get the serialized representation of the request entity. This is used when generating the client
 * signature, because this is the representation that the server will receive and use when it generates
 * the server-side signature to compare to the client-side signature.
 *
 * @see com.sun.jersey.client.urlconnection.URLConnectionClientHandler
 */
private byte[] getSerializedEntity(ClientRequest request) {
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {
        // By using the RequestWriter parent class, we match the behavior of entity writing from
        // for example, com.sun.jersey.client.urlconnection.URLConnectionClientHandler.
        writeRequestEntity(request, new RequestEntityWriterListener() {
            public void onRequestEntitySize(long size) throws IOException {
            }

            public OutputStream onGetOutputStream() throws IOException {
                return outputStream;
            }
        });

    } catch (IOException e) {
        throw new ClientHandlerException("Unable to serialize request entity", e);
    }

    return outputStream.toByteArray();
}
 
Example #5
Source File: WebServicesVersionConversion.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest cr) throws ClientHandlerException
{
  URIBuilder uriBuilder = new URIBuilder(cr.getURI());
  String path = uriBuilder.getPath();
  uriBuilder.setPath(converter.convertCommandPath(path));
  try {
    cr.setURI(uriBuilder.build());
    ClientResponse response = getNext().handle(cr);
    String newEntity = converter.convertResponse(path, response.getEntity(String.class));
    response.setEntityInputStream(new ByteArrayInputStream(newEntity.getBytes()));
    return response;
  } catch (Exception ex) {
    throw new ClientHandlerException(ex);
  }
}
 
Example #6
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest request)
		throws ClientHandlerException {
	if (this.logger.isLoggable(Level.FINE)) {
		long id = ++this._id;
		logRequest(id, request);
		
		ClientResponse response = getNext().handle(request);

		logResponse(id, response);

		return response;
	} else{
		return getNext().handle(request);			
	}

}
 
Example #7
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest request)
		throws ClientHandlerException {
	if (this.logger.isLoggable(Level.FINE)) {
		long id = ++this._id;
		logRequest(id, request);
		
		ClientResponse response = getNext().handle(request);

		logResponse(id, response);

		return response;
	} else{
		return getNext().handle(request);			
	}

}
 
Example #8
Source File: WebServicesVersionConversion.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest cr) throws ClientHandlerException
{
  URIBuilder uriBuilder = new URIBuilder(cr.getURI());
  String path = uriBuilder.getPath();
  uriBuilder.setPath(converter.convertCommandPath(path));
  try {
    cr.setURI(uriBuilder.build());
    ClientResponse response = getNext().handle(cr);
    String newEntity = converter.convertResponse(path, response.getEntity(String.class));
    response.setEntityInputStream(new ByteArrayInputStream(newEntity.getBytes()));
    return response;
  } catch (Exception ex) {
    throw new ClientHandlerException(ex);
  }
}
 
Example #9
Source File: HmacClientFilter.java    From jersey-hmac-auth with Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
    // Modify the request to include security credentials if appropriate
    if (shouldEncode(request)) {
        requestEncoder.encode(request);
    }

    // Following the ClientFilter protocol, pass the request to the next filter in the chain
    return getNext().handle(request);
}
 
Example #10
Source File: RequestLogger.java    From qaf with MIT License 5 votes vote down vote up
private void logRequest(long id, ClientRequest request, StringBuilder b) {

		printRequestLine(b, id, request);
		printRequestHeaders(b, id, request.getHeaders());
		if (request.getEntity() != null) {
			prefixId(b, id).append(REQUEST_PREFIX).append(request.getEntity());
			request.setAdapter(new Adapter(request.getAdapter(), b));
		}
		log(b.toString());
	}
 
Example #11
Source File: RequestTracker.java    From qaf with MIT License 5 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest request) throws ClientHandlerException {

	ClientResponse response = getNext().handle(request);
	clientRequest = request;
	clientResponse = response;
	return response;
}
 
Example #12
Source File: ClientFilterAdapter.java    From spring-cloud-services-connector with Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest cr) throws ClientHandlerException {
	if (decorator.getHeaders() != null) {
		for (Entry<String, List<String>> entry : decorator.getHeaders().entrySet()) {
			for (String value : entry.getValue()) {
				cr.getHeaders().add(entry.getKey(), value);
			}
		}
	}
	return getNext().handle(cr);
}
 
Example #13
Source File: EurekaOAuth2ClientFilterAdapter.java    From spring-cloud-services-starters with Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest cr) throws ClientHandlerException {
	Instant now = Clock.systemUTC().instant();
	if (accessToken == null || now.isAfter(accessToken.getExpiresAt())) {
		DefaultClientCredentialsTokenResponseClient tokenResponseClient = new DefaultClientCredentialsTokenResponseClient();
		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
				clientRegistration);
		accessToken = tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest).getAccessToken();
	}

	cr.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken.getTokenValue());

	return getNext().handle(cr);
}
 
Example #14
Source File: HeaderClientFilter.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException
{
  final MultivaluedMap<String, Object> headers = clientRequest.getHeaders();
  List<Object> hcookies = headers.get(COOKIE_HEADER);
  if (hcookies == null) {
    hcookies = new ArrayList<>();
  }
  hcookies.addAll(cookies);
  headers.put(COOKIE_HEADER, hcookies);
  return getNext().handle(clientRequest);
}
 
Example #15
Source File: RequestEncoder.java    From jersey-hmac-auth with Apache License 2.0 5 votes vote down vote up
public void encode(ClientRequest request) {
    String timestamp = TimeUtils.getCurrentTimestamp();
    addApiKey(request);
    addTimestamp(request, timestamp);
    addSignature(request, timestamp);
    addVersion(request);
}
 
Example #16
Source File: RequestEncoder.java    From jersey-hmac-auth with Apache License 2.0 5 votes vote down vote up
private void addApiKey(ClientRequest request) {
    URI uriWithApiKey = UriBuilder.fromUri(request.getURI())
            .queryParam(this.requestConfiguration.getApiKeyQueryParamName(), apiKey)
            .build();

    request.setURI(uriWithApiKey);
}
 
Example #17
Source File: RequestEncoder.java    From jersey-hmac-auth with Apache License 2.0 5 votes vote down vote up
private String buildSignature(ClientRequest request, String timestamp) {
    String method = getMethod(request);
    String path = getPath(request);
    byte[] content = this.requestConfiguration.isDataInSignature() ? getContent(request) : null;

    return signatureGenerator.generate(secretKey, method, timestamp, path, content);
}
 
Example #18
Source File: CookiesHandlerFilter.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public ClientResponse handle( ClientRequest request ) throws ClientHandlerException {
  List<Object> authorizationHeader = request.getHeaders().get( "Authorization" );
  String authToken = (String) authorizationHeader.get( 0 );
  // If we have cookies, inject them. When session is expired, basic auth
  // header is not used instead of the expired cookies, so we just use
  // them as a token.
  List<Object> cookiesList = getCachedCookiesByAuthToken( authToken );
  if ( cookiesList != null ) {
    request.getHeaders().put( "Cookie", cookiesList );
    request.getHeaders().remove( "Authorization" );
  }
  ClientResponse response = getNext().handle( request );
  // If session has expired, remove cookies, put back basic auth header,
  // try one more time and save new cookies.
  if ( response.getStatus() == HttpStatus.SC_UNAUTHORIZED ) {
    logger.warn( "Request to" + request.getURI() + "returned Unauthorized." );
    if ( logger.isDebugEnabled() ) {
      logger.debug( "http status=" + response.getStatus() + " response=" + response.getEntity( String.class ) );
    }
    request.getHeaders().remove( "Cookie" );
    request.getHeaders().put( "Authorization", authorizationHeader );
    logger.warn( "Trying one more time" );
    response = getNext().handle( request );
    if ( response.getStatus() == HttpStatus.SC_UNAUTHORIZED ) {
      logger.error( "Request to" + request.getURI() + "returned Unauthorized 2nd time." );
      logger.error( "http status=" + response.getStatus() + " response=" + response.getEntity( String.class ) );
    }
  }
  // always use the new cookies.
  if ( response.getCookies() != null && response.getCookies().isEmpty() == false ) {
    cookiesList = new ArrayList<Object>();
    cookiesList.addAll( response.getCookies() );
    setCookiesByAuthToken( authToken, cookiesList );
  }
  return response;
}
 
Example #19
Source File: JsonClientFilter.java    From docker-java with Apache License 2.0 5 votes vote down vote up
public ClientResponse handle(ClientRequest cr) {
    // Call the next filter
    ClientResponse resp = getNext().handle(cr);
    String respContentType = resp.getHeaders().getFirst("Content-Type");
    if (respContentType.startsWith("text/plain")) {
        String newContentType = "application/json" + respContentType.substring(10);
        resp.getHeaders().putSingle("Content-Type", newContentType);
    }
    return resp;
}
 
Example #20
Source File: HttpBasicAuthenticationFilter.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
	if (!request.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) {
		request.getHeaders().add(HttpHeaders.AUTHORIZATION, authentication);
	}

	return getNext().handle(request);
}
 
Example #21
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
private void printRequestLine(StringBuilder b, long id,
		ClientRequest request) {
	prefixId(b, id).append(NOTIFICATION_PREFIX)
			.append("Client out-bound request").append("\n");
	prefixId(b, id).append(REQUEST_PREFIX).append(request.getMethod())
			.append(" ").append(request.getURI().toASCIIString())
			.append("\n");
}
 
Example #22
Source File: HeaderClientFilter.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException
{
  final MultivaluedMap<String, Object> headers = clientRequest.getHeaders();
  List<Object> hcookies = headers.get(COOKIE_HEADER);
  if (hcookies == null) {
    hcookies = new ArrayList<>();
  }
  hcookies.addAll(cookies);
  headers.put(COOKIE_HEADER, hcookies);
  return getNext().handle(clientRequest);
}
 
Example #23
Source File: DiscoveryHeaderClientFilter.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest cr) throws ClientHandlerException {
    Map<String, String> headers = DiscoveryHeaderHelper.getInstance().getRequestHeaderInfo();
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        cr.getHeaders().put(entry.getKey(), Collections.singletonList(entry.getValue()));
    }
    return getNext().handle(cr);
}
 
Example #24
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
private void logRequest(long id, ClientRequest request) {
	StringBuilder b = new StringBuilder();

	printRequestLine(b, id, request);
	printRequestHeaders(b, id, request.getHeaders());

	if (request.getEntity() != null) {
		request.setAdapter(new Adapter(request.getAdapter(), b));
	} else {
		log(b);
	}
}
 
Example #25
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
private void printRequestHeaders(StringBuilder b, long id,
		MultivaluedMap<String, Object> headers) {
	for (Map.Entry<String, List<Object>> e : headers.entrySet()) {
		String header = e.getKey();
		for (Object value : e.getValue()) {
			prefixId(b, id).append(REQUEST_PREFIX).append(header)
					.append(": ")
					.append(ClientRequest.getHeaderValue(value))
					.append("\n");
		}
	}
	prefixId(b, id).append(REQUEST_PREFIX).append("\n");
}
 
Example #26
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
private void logRequest(long id, ClientRequest request) {
	StringBuilder b = new StringBuilder();

	printRequestLine(b, id, request);
	printRequestHeaders(b, id, request.getHeaders());

	if (request.getEntity() != null) {
		request.setAdapter(new Adapter(request.getAdapter(), b));
	} else {
		log(b);
	}
}
 
Example #27
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
private void printRequestLine(StringBuilder b, long id,
		ClientRequest request) {
	prefixId(b, id).append(NOTIFICATION_PREFIX)
			.append("Client out-bound request").append("\n");
	prefixId(b, id).append(REQUEST_PREFIX).append(request.getMethod())
			.append(" ").append(request.getURI().toASCIIString())
			.append("\n");
}
 
Example #28
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
private void printRequestHeaders(StringBuilder b, long id,
		MultivaluedMap<String, Object> headers) {
	for (Map.Entry<String, List<Object>> e : headers.entrySet()) {
		String header = e.getKey();
		for (Object value : e.getValue()) {
			prefixId(b, id).append(REQUEST_PREFIX).append(header)
					.append(": ")
					.append(ClientRequest.getHeaderValue(value))
					.append("\n");
		}
	}
	prefixId(b, id).append(REQUEST_PREFIX).append("\n");
}
 
Example #29
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
private void logRequest(long id, ClientRequest request) {
	StringBuilder b = new StringBuilder();

	printRequestLine(b, id, request);
	printRequestHeaders(b, id, request.getHeaders());

	if (request.getEntity() != null) {
		request.setAdapter(new Adapter(request.getAdapter(), b));
	} else {
		log(b);
	}
}
 
Example #30
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
private void printRequestHeaders(StringBuilder b, long id,
		MultivaluedMap<String, Object> headers) {
	for (Map.Entry<String, List<Object>> e : headers.entrySet()) {
		String header = e.getKey();
		for (Object value : e.getValue()) {
			prefixId(b, id).append(REQUEST_PREFIX).append(header)
					.append(": ")
					.append(ClientRequest.getHeaderValue(value))
					.append("\n");
		}
	}
	prefixId(b, id).append(REQUEST_PREFIX).append("\n");
}