Java Code Examples for com.sun.jersey.api.client.ClientResponse#getHeaders()

The following examples show how to use com.sun.jersey.api.client.ClientResponse#getHeaders() . 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: Response.java    From qaf with MIT License 7 votes vote down vote up
protected void init(ClientResponse clientResponse) {

		this.clientResponse = clientResponse;
		// messageBody = clientResponse.getEntity(type);
		setRawMessageBody();
		headers = clientResponse.getHeaders();
		status = clientResponse.getClientResponseStatus();
		cookies = clientResponse.getCookies();
		lastModified = clientResponse.getLastModified();
		responseDate = clientResponse.getResponseDate();
		language = clientResponse.getLanguage();

		try {
			mediaType = clientResponse.getType();
		} catch (Exception e) {
			System.err.println("Unable to parse media type. If want to access media type, you may try using 'Content-Type' from header.");
			e.printStackTrace();
		}

	}
 
Example 2
Source File: DefaultDisseminationHandler.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
public static Response getResponse(RemoteObject remote, String dsId) throws DigitalObjectException {
    // This should limit fedora calls to 1.
    // XXX It works around FedoraClient.FedoraClient.getDatastreamDissemination that hides HTTP headers of the response.
    // Unfortunattely fedora does not return modification date as HTTP header
    // In case of large images it could be faster to ask datastream for modification date first.
    String pid = remote.getPid();
    String path = String.format("objects/%s/datastreams/%s/content", pid, dsId);
    ClientResponse response = remote.getClient().resource().path(path).get(ClientResponse.class);
    if (Status.fromStatusCode(response.getStatus()) != Status.OK) {
        throw new DigitalObjectNotFoundException(pid, null, dsId, response.getEntity(String.class), null);
    }
    MultivaluedMap<String, String> headers = response.getHeaders();
    String filename = headers.getFirst("Content-Disposition");
    filename = filename != null ? filename : "inline; filename=" + pid + '-' + dsId;
    return Response.ok(response.getEntity(InputStream.class), headers.getFirst("Content-Type"))
            .header("Content-Disposition", filename)
            .build();
}
 
Example 3
Source File: HttpHeaderSecurityIT.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test(timeout=10000)
public void shouldCheckAbsenceOfHsts() {
  // given

  // when
  ClientResponse response = client.resource(APP_BASE_PATH + TASKLIST_PATH)
      .get(ClientResponse.class);

  // then
  assertEquals(200, response.getStatus());
  MultivaluedMap<String, String> headers = response.getHeaders();
  List<String> values = headers.get("Strict-Transport-Security");
  assertNull(values);

  // cleanup
  response.close();
}
 
Example 4
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Invoke API by sending HTTP request with the given options.
 *
 * @param <T> Type
 * @param path The sub-path of the HTTP URL
 * @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
 * @param queryParams The query parameters
 * @param collectionQueryParams The collection query parameters
 * @param body The request body object - if it is not binary, otherwise null
 * @param headerParams The header parameters
 * @param cookieParams The cookie parameters
 * @param formParams The form parameters
 * @param accept The request's Accept header
 * @param contentType The request's Content-Type header
 * @param authNames The authentications to apply
 * @param returnType Return type
 * @return The response body in type of string
 * @throws ApiException API exception
 */
 public <T> T invokeAPI(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {

  ClientResponse response = getAPIResponse(path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames);

  statusCode = response.getStatusInfo().getStatusCode();
  responseHeaders = response.getHeaders();

  if(response.getStatusInfo().getStatusCode() == ClientResponse.Status.NO_CONTENT.getStatusCode()) {
    return null;
  } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
    if (returnType == null)
      return null;
    else
      return response.getEntity(returnType);
  } else {
    String message = "error";
    String respBody = null;
    if (response.hasEntity()) {
      try {
        respBody = response.getEntity(String.class);
        message = respBody;
      } catch (RuntimeException e) {
        // e.printStackTrace();
      }
    }
    throw new ApiException(
      response.getStatusInfo().getStatusCode(),
      message,
      response.getHeaders(),
      respBody);
  }
}
 
Example 5
Source File: ApiClient.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Invoke API by sending HTTP request with the given options.
 *
 * @param path         The sub-path of the HTTP URL
 * @param method       The request method, one of "GET", "POST", "PUT", and "DELETE"
 * @param queryParams  The query parameters
 * @param body         The request body object - if it is not binary, otherwise null
 * @param headerParams The header parameters
 * @param formParams   The form parameters
 * @param accept       The request's Accept header
 * @param contentType  The request's Content-Type header
 * @param authNames    The authentications to apply
 * @return The response body in type of string
 */
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {

    ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames);

    statusCode = response.getStatusInfo().getStatusCode();
    responseHeaders = response.getHeaders();

    if (response.getStatusInfo().getStatusCode() == ClientResponse.Status.NO_CONTENT.getStatusCode()) {

        throw new ApiException(204, "No content Found");

    } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
        if (returnType == null) {
            return null;
        } else {
            return response.getEntity(returnType);
        }
    } else {
        String message = "error";
        String respBody = null;
        if (response.hasEntity()) {
            try {
                respBody = response.getEntity(String.class);
                message = respBody;
            } catch (RuntimeException e) {
                // e.printStackTrace();
            }
        }
        throw new ApiException(
                response.getStatusInfo().getStatusCode(),
                message,
                response.getHeaders(),
                respBody);
    }
}
 
Example 6
Source File: ApiClient.java    From docusign-java-client with MIT License 5 votes vote down vote up
/**
 *
 * @param accessToken the bearer token to use to authenticate for this call.
 * @return OAuth UserInfo model
 * @throws ApiException if the HTTP call status is different than 2xx.
 * @see OAuth.UserInfo
 */
public OAuth.UserInfo getUserInfo(String accessToken) throws IllegalArgumentException, ApiException {
  try {
    if (accessToken == null || "".equals(accessToken)) {
      throw new IllegalArgumentException("Cannot find a valid access token. Make sure OAuth is configured before you try again.");
    }

    Client client = buildHttpClient(debugging);
    WebResource webResource = client.resource("https://" + getOAuthBasePath() + "/oauth/userinfo");
    ClientResponse response = webResource
        .header("Authorization", "Bearer " + accessToken)
        .header("Cache-Control", "no-store")
        .header("Pragma", "no-cache")
        .get(ClientResponse.class);
    if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
      String respBody = response.getEntity(String.class);
      throw new ApiException(
        response.getStatusInfo().getStatusCode(),
        "Error while requesting server, received a non successful HTTP code " + response.getStatusInfo().getStatusCode() + " with response Body: '" + respBody + "'",
        response.getHeaders(),
        respBody);
    }
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    OAuth.UserInfo userInfo = mapper.readValue(response.getEntityInputStream(), OAuth.UserInfo.class);

    // TODO "auto-assign base uri of the default account" is coming in next versions
    /*for (OAuth.UserInfo.Account account: userInfo.getAccounts()) {
        if ("true".equals(account.getIsDefault())) {
            setBasePath(account.getBaseUri() + "/restapi");
            Configuration.setDefaultApiClient(this);
            return userInfo;
        }
    }*/
    return userInfo;
  } catch (Exception e) {
    throw new ApiException("Error while fetching user info: " + e.getMessage());
  }
}
 
Example 7
Source File: SessionCookieSecurityIT.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected boolean isCookieHeaderValuePresent(String expectedHeaderValue, ClientResponse response) {
  MultivaluedMap<String, String> headers = response.getHeaders();

  List<String> values = headers.get("Set-Cookie");
  for (String value : values) {
    if (value.startsWith("JSESSIONID=")) {
      return value.contains(expectedHeaderValue);
    }
  }

  return false;
}
 
Example 8
Source File: CsrfPreventionIT.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected boolean checkCookieSet(ClientResponse response) {
  MultivaluedMap<String, String> headers = response.getHeaders();

  List<String> values = headers.get("Set-Cookie");
  for (String value : values) {
    if (value.startsWith("XSRF-TOKEN=")) {
      return value.contains(";SameSite=Lax");
    }
  }

  return false;
}
 
Example 9
Source File: CsrfPreventionIT.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected boolean checkXsrfTokenHeaderPresent(ClientResponse response) {
  MultivaluedMap<String, String> headers = response.getHeaders();

  List<String> values = headers.get("X-XSRF-TOKEN");
  for (String value : values) {
    if (value.length() == 32) {
      return true;
    }
  }

  return false;
}
 
Example 10
Source File: HttpHeaderSecurityIT.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected boolean isHeaderPresent(String expectedName, String expectedValue, ClientResponse response) {
  MultivaluedMap<String, String> headers = response.getHeaders();

  List<String> values = headers.get(expectedName);
  for (String value : values) {
    if (value.equals(expectedValue)) {
      return true;
    }
  }

  return false;
}
 
Example 11
Source File: Rest.java    From hop with Apache License 2.0 4 votes vote down vote up
protected MultivaluedMap<String, String> searchForHeaders( ClientResponse response ) {
  return response.getHeaders();
}
 
Example 12
Source File: ApiClient.java    From forge-api-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * Invoke API by sending HTTP request with the given options.
 *
 * @param oauth2 The oauth object used to send secure requests
 * @param credentials The credentials containing the access token used to send secure requests
 * @param path The sub-path of the HTTP URL
 * @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
 * @param queryParams The query parameters
 * @param body The request body object - if it is not binary, otherwise null
 * @param headerParams The header parameters
 * @param formParams The form parameters
 * @param accept The request's Accept header
 * @param contentType The request's Content-Type header
 * @return The response body in type of string
 */
 public <T> ApiResponse<T> invokeAPI(Authentication oauth2, Credentials credentials, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, GenericType<T> returnType) throws ApiException, Exception{

  //try to auto refresh 2-legged/3-legged access token
  if (oauth2 instanceof OAuth2TwoLegged){
      OAuth2TwoLegged oauth2TwoLegged = (OAuth2TwoLegged)oauth2;
      if(oauth2TwoLegged.isAutoRefresh() && oauth2TwoLegged.isAccessTokenExpired()){
          credentials = oauth2TwoLegged.authenticate();
      }
  }
  else if (oauth2 instanceof OAuth2ThreeLegged && credentials instanceof ThreeLeggedCredentials){
      OAuth2ThreeLegged oauth2ThreeLegged = (OAuth2ThreeLegged)oauth2;
      if(oauth2ThreeLegged.isAutoRefresh() && !oauth2ThreeLegged.isAuthorized((ThreeLeggedCredentials)credentials)){
          credentials = oauth2ThreeLegged.refreshAccessToken(((ThreeLeggedCredentials) credentials).getRefreshToken());
      }
  }

  ClientResponse response = getAPIResponse(credentials, path, method, queryParams, body, headerParams, formParams, accept, contentType);

  statusCode = response.getStatusInfo().getStatusCode();
  responseHeaders = response.getHeaders();

  if(response.getStatusInfo().getStatusCode() == ClientResponse.Status.NO_CONTENT.getStatusCode()) {
          return null;
  } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
    if (returnType == null || statusCode == 202)
      return new ApiResponse<T>(statusCode, responseHeaders, null);
    else
      return new ApiResponse<T>(statusCode, responseHeaders, response.getEntity(returnType));
  } else {
    String message = "error";
    String respBody = null;
    if (response.hasEntity()) {
      try {
        respBody = response.getEntity(String.class);
        message = respBody;
      } catch (RuntimeException e) {
        // e.printStackTrace();
      }
    }
    throw new ApiException(
      response.getStatusInfo().getStatusCode(),
      message,
      response.getHeaders(),
      respBody);
  }
}
 
Example 13
Source File: Rest.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
protected MultivaluedMap<String, String> searchForHeaders( ClientResponse response ) {
  return response.getHeaders();
}