Java Code Examples for com.sun.jersey.api.client.WebResource#Builder

The following examples show how to use com.sun.jersey.api.client.WebResource#Builder . 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: UserRoleDelegate.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private void initManaged( PurRepositoryMeta repositoryMeta, IUser userInfo ) throws JSONException {
  String baseUrl = repositoryMeta.getRepositoryLocation().getUrl();
  String webService = baseUrl + ( baseUrl.endsWith( "/" ) ? "" : "/" ) + "api/system/authentication-provider";
  HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter( userInfo.getLogin(), userInfo.getPassword() );
  Client client = new Client();
  client.addFilter( authFilter );

  WebResource.Builder resource = client.resource( webService ).accept( MediaType.APPLICATION_JSON_TYPE );
  /**
   * if set, _trust_user_ needs to be considered. See other places in pur-plugin's:
   *
   * @link https://github.com/pentaho/pentaho-kettle/blob/8.0.0.0-R/plugins/pur/core/src/main/java/org/pentaho/di/repository/pur/PurRepositoryConnector.java#L97-L101
   * @link https://github.com/pentaho/pentaho-kettle/blob/8.0.0.0-R/plugins/pur/core/src/main/java/org/pentaho/di/repository/pur/WebServiceManager.java#L130-L133
   */
  if ( StringUtils.isNotBlank( System.getProperty( "pentaho.repository.client.attemptTrust" ) ) ) {
    resource = resource.header( TRUST_USER, userInfo.getLogin() );
  }
  String response = resource.get( String.class );
  String provider = new JSONObject( response ).getString( "authenticationType" );
  managed = "jackrabbit".equals( provider );
}
 
Example 2
Source File: AtlasClientTest.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = IllegalArgumentException.class)
public void shouldThrowExceptionIfActiveServerIsNotFound() {
    setupRetryParams();

    when(client.resource(UriBuilder.fromUri("http://localhost:31000").build())).thenReturn(service);
    WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service);
    ClientResponse response = mock(ClientResponse.class);
    when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
    when(response.getEntity(String.class)).thenReturn("{\"Status\":\"BECOMING_ACTIVE\"}");
    when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)).
            thenThrow(new ClientHandlerException("Simulating connection exception")).
            thenReturn(response).
            thenReturn(response);

    AtlasClient atlasClient = new AtlasClient(service, configuration);

    String serviceURL = atlasClient.determineActiveServiceURL(
            new String[] {"http://localhost:31000","http://localhost:41000"},
            client);
    assertNull(serviceURL);
}
 
Example 3
Source File: AtlasClientTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRetryWithSameClientIfSingleAddressIsUsed() throws URISyntaxException, AtlasServiceException {
    setupRetryParams();

    ResourceCreator resourceCreator = mock(ResourceCreator.class);
    WebResource resourceObject = mock(WebResource.class);
    when(resourceObject.getURI()).
            thenReturn(new URI("http://localhost:31000/api/atlas/types"));

    WebResource.Builder builder = getBuilder(resourceObject);

    ClientResponse response = mock(ClientResponse.class);
    when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
    String activeStatus = "{\"Status\":\"ACTIVE\"}";
    when(response.getEntity(String.class)).thenReturn(activeStatus);
    when(response.getLength()).thenReturn(activeStatus.length());

    when(builder.method(AtlasClient.API.LIST_TYPES.getMethod(), ClientResponse.class, null)).
            thenThrow(new ClientHandlerException("simulating exception in calling API", new ConnectException())).
            thenReturn(response);

    when(resourceCreator.createResource()).thenReturn(resourceObject);
    when(configuration.getString("atlas.http.authentication.type", "simple")).thenReturn("simple");

    AtlasClient atlasClient = getClientForTest("http://localhost:31000");

    atlasClient.setService(resourceObject);
    atlasClient.setConfiguration(configuration);

    atlasClient.callAPIWithRetries(AtlasClient.API.LIST_TYPES, null, resourceCreator);

    verify(client).destroy();
    verify(client, times(2)).resource(UriBuilder.fromUri("http://localhost:31000").build());
}
 
Example 4
Source File: AtlasClientTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRetryIfCannotConnectToServiceInitially() {
    setupRetryParams();

    when(client.resource(UriBuilder.fromUri("http://localhost:31000").build())).thenReturn(service);
    WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service);
    ClientResponse response = mock(ClientResponse.class);
    when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
    when(response.getEntity(String.class)).thenReturn("{\"Status\":\"BECOMING_ACTIVE\"}");
    ClientResponse nextResponse = mock(ClientResponse.class);
    when(nextResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
    String activeStatus = "{\"Status\":\"ACTIVE\"}";
    when(response.getEntity(String.class)).thenReturn(activeStatus);
    when(response.getLength()).thenReturn(activeStatus.length());
    when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)).
            thenThrow(new ClientHandlerException("Simulating connection exception")).
            thenReturn(response).
            thenReturn(nextResponse);

    AtlasClient atlasClient = new AtlasClient(service, configuration);
    atlasClient.setService(service);
    atlasClient.setConfiguration(configuration);

    String serviceURL = atlasClient.determineActiveServiceURL(
            new String[] {"http://localhost:31000","http://localhost:41000"},
            client);
    assertEquals(serviceURL, "http://localhost:31000");
}
 
Example 5
Source File: AtlasClientTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnStatusAsUnknownIfJSONIsInvalid() throws AtlasServiceException {
    setupRetryParams();
    AtlasClient atlasClient = new AtlasClient(service, configuration);

    WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service);
    ClientResponse response = mock(ClientResponse.class);
    when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
    when(response.getEntity(String.class)).thenReturn("{\"status\":\"Active\"}");
    when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)).thenReturn(response);

    String status = atlasClient.getAdminStatus();
    assertEquals(status, AtlasClient.UNKNOWN_STATUS);
}
 
Example 6
Source File: BrooklynMetricsRetrieverV1.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private WebResource.Builder applyHeaders(WebResource.Builder builder,
        MultivaluedMap<String, String> headers) {

    for (String key : headers.keySet()) {
        for (String value : headers.get(key)) {
            builder = builder.header(key, value);
        }
    }
    return builder;
}
 
Example 7
Source File: WsClient.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
/**
 * @param resource a web resource
 * @return a builder with an optional cookie (for authentication)
 */
public WebResource.Builder createBuilder( WebResource resource ) {

	WebResource.Builder result;
	if( this.sessionId != null )
		result = resource.cookie( new Cookie( UrlConstants.SESSION_ID, this.sessionId ));
	else
		result = resource.getRequestBuilder();

	return result;
}
 
Example 8
Source File: NiFiTestUser.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Conditionally adds the proxied entities chain.
 *
 * @param builder the resource builder
 * @return the resource builder
 */
private WebResource.Builder addProxiedEntities(final WebResource.Builder builder) {
    if (proxyDn == null) {
        return builder;
    } else {
        return builder.header(ProxiedEntitiesUtils.PROXY_ENTITIES_CHAIN, proxyDn);
    }
}
 
Example 9
Source File: RequestJob.java    From ingestion with Apache License 2.0 5 votes vote down vote up
/**
 * Set an Application Type to the request depending on a parameter and its corresponding
 * {@code MediaType}.
 *
 * @param webResource     Current target url.
 * @param applicationType ApplicationType to set.
 * @return
 */
public WebResource.Builder setApplicationType(WebResource webResource, String applicationType) {
    if ("TEXT".equals(applicationType)) {
        mediaType = MediaType.TEXT_PLAIN_TYPE;
    } else {
        mediaType = MediaType.APPLICATION_JSON_TYPE;
    }

    return webResource.accept(mediaType);
}
 
Example 10
Source File: AtlasClientTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = AtlasServiceException.class)
public void shouldReturnStatusAsUnknownOnException() throws AtlasServiceException {
    setupRetryParams();

    AtlasClient atlasClient = new AtlasClient(service, configuration);

    WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service);
    ClientResponse response = mock(ClientResponse.class);
    when(response.getStatus()).thenReturn(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    when(response.getClientResponseStatus()).thenReturn(ClientResponse.Status.INTERNAL_SERVER_ERROR);
    when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)).thenReturn(response);

    String status = atlasClient.getAdminStatus();
    fail("Should fail with AtlasServiceException");
}
 
Example 11
Source File: AtlasClientTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = AtlasServiceException.class)
public void shouldThrowErrorIfAnyResponseOtherThanServiceUnavailable() throws AtlasServiceException {
    setupRetryParams();

    AtlasClient atlasClient = new AtlasClient(service, configuration);
    WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.VERSION, service);
    ClientResponse response = mock(ClientResponse.class);
    when(response.getStatus()).thenReturn(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    when(response.getClientResponseStatus()).thenReturn(ClientResponse.Status.INTERNAL_SERVER_ERROR);

    when(builder.method(AtlasClient.API_V1.VERSION.getMethod(), ClientResponse.class, null)).thenReturn(response);

    atlasClient.isServerReady();
    fail("Should throw exception");
}
 
Example 12
Source File: AtlasClientTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldVerifyServerIsReady() throws AtlasServiceException {
    setupRetryParams();

    AtlasClient atlasClient = new AtlasClient(service, configuration);

    WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.VERSION, service);
    ClientResponse response = mock(ClientResponse.class);
    when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
    when(response.getEntity(String.class)).thenReturn("{\"Version\":\"version-rrelease\",\"Name\":\"apache-atlas\"," +
            "\"Description\":\"Metadata Management and Data Governance Platform over Hadoop\"}");
    when(builder.method(AtlasClient.API_V1.VERSION.getMethod(), ClientResponse.class, null)).thenReturn(response);

    assertTrue(atlasClient.isServerReady());
}
 
Example 13
Source File: AtlasClientTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnFalseIfServiceIsUnavailable() throws AtlasServiceException {
    setupRetryParams();
    AtlasClient atlasClient = new AtlasClient(service, configuration);
    WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.VERSION, service);
    ClientResponse response = mock(ClientResponse.class);
    when(response.getStatus()).thenReturn(Response.Status.SERVICE_UNAVAILABLE.getStatusCode());
    when(response.getClientResponseStatus()).thenReturn(ClientResponse.Status.SERVICE_UNAVAILABLE);

    when(builder.method(AtlasClient.API_V1.VERSION.getMethod(), ClientResponse.class, null)).thenReturn(response);

    assertFalse(atlasClient.isServerReady());
}
 
Example 14
Source File: AtlasClientV2Test.java    From atlas with Apache License 2.0 4 votes vote down vote up
@Test
public void updateClassificationsShouldNotThrowExceptionIfResponseIs204() {

    AtlasClientV2 atlasClient = new AtlasClientV2(service, configuration);


    AtlasClassification atlasClassification = new AtlasClassification("Testdb");
    atlasClassification.setEntityGuid("abb672b1-e4bd-402d-a98f-73cd8f775e2a");
    WebResource.Builder builder = setupBuilder(AtlasClientV2.API_V2.UPDATE_CLASSIFICATIONS, service);


    ClientResponse response = mock(ClientResponse.class);
    when(response.getStatus()).thenReturn(Response.Status.NO_CONTENT.getStatusCode());


    when(builder.method(anyString(), Matchers.<Class>any(), anyString())).thenReturn(response);

    try {
        atlasClient.updateClassifications("abb672b1-e4bd-402d-a98f-73cd8f775e2a", Collections.singletonList(atlasClassification));

    } catch (AtlasServiceException e) {
        Assert.fail("Failed with Exception");
    }

}
 
Example 15
Source File: RestTest.java    From hop with Apache License 2.0 4 votes vote down vote up
@Test
public void testCallEndpointWithDeleteVerb() throws HopException {
  MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
  headers.add( "Content-Type", "application/json" );

  ClientResponse response = mock( ClientResponse.class );
  doReturn( 200 ).when( response ).getStatus();
  doReturn( headers ).when( response ).getHeaders();
  doReturn( "true" ).when( response ).getEntity( String.class );

  WebResource.Builder builder = mock( WebResource.Builder.class );
  doReturn( response ).when( builder ).delete( ClientResponse.class );

  WebResource resource = mock( WebResource.class );
  doReturn( builder ).when( resource ).getRequestBuilder();

  ApacheHttpClient4 client = mock( ApacheHttpClient4.class );
  doReturn( resource ).when( client ).resource( anyString() );

  mockStatic( ApacheHttpClient4.class );
  when( ApacheHttpClient4.create( any() ) ).thenReturn( client );

  RestMeta meta = mock( RestMeta.class );
  doReturn( false ).when( meta ).isDetailed();
  doReturn( false ).when( meta ).isUrlInField();
  doReturn( false ).when( meta ).isDynamicMethod();

  IRowMeta rmi = mock( IRowMeta.class );
  doReturn( 1 ).when( rmi ).size();

  RestData data = mock( RestData.class );
  data.method = RestMeta.HTTP_METHOD_DELETE;
  data.inputRowMeta = rmi;
  data.resultFieldName = "result";
  data.resultCodeFieldName = "status";
  data.resultHeaderFieldName = "headers";

  Rest rest = mock( Rest.class );
  doCallRealMethod().when( rest ).callRest( any() );
  doCallRealMethod().when( rest ).searchForHeaders( any() );

  setInternalState( rest, "meta", meta );
  setInternalState( rest, "data", data );

  Object[] output = rest.callRest( new Object[] { 0 } );

  verify( builder, times( 1 ) ).delete( ClientResponse.class );
  assertEquals( "true", output[ 1 ] );
  assertEquals( 200L, output[ 2 ] );
  assertEquals( "{\"Content-Type\":\"application\\/json\"}", output[ 3 ] );
}
 
Example 16
Source File: EagleServiceBaseClient.java    From Eagle with Apache License 2.0 4 votes vote down vote up
protected WebResource.Builder putAuthHeaderIfNeeded(WebResource.Builder r) {
    if (username != null && password != null) {
       r.header(SecurityConstants.AUTHORIZATION, SecurityConstants.BASIC_AUTHORIZATION_HEADER_PREFIX + Base64.encode(username + ":" + password));
    }
    return r;
}
 
Example 17
Source File: WebServicesClient.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override
public T process(WebResource.Builder webResource, Class<T> clazz)
{
  return webResource.delete(clazz);
}
 
Example 18
Source File: AtlasClientV2Test.java    From atlas with Apache License 2.0 4 votes vote down vote up
@Test
public void updateClassificationsShouldThrowExceptionIfResponseIsNot204() {

    AtlasClientV2 atlasClient = new AtlasClientV2(service, configuration);


    AtlasClassification atlasClassification = new AtlasClassification("Testdb");
    atlasClassification.setEntityGuid("abb672b1-e4bd-402d-a98f-73cd8f775e2a");
    WebResource.Builder builder = setupBuilder(AtlasClientV2.API_V2.UPDATE_CLASSIFICATIONS, service);


    ClientResponse response = mock(ClientResponse.class);
    when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());


    when(builder.method(anyString(), Matchers.<Class>any(), anyString())).thenReturn(response);

    try {
        atlasClient.updateClassifications("abb672b1-e4bd-402d-a98f-73cd8f775e2a", Collections.singletonList(atlasClassification));
        Assert.fail("Failed with Exception");
    } catch (AtlasServiceException e) {
        Assert.assertTrue(e.getMessage().contains(" failed with status 200 "));
    }

}
 
Example 19
Source File: WebServicesClient.java    From attic-apex-core with Apache License 2.0 votes vote down vote up
public abstract T process(WebResource.Builder webResource, Class<T> clazz); 
Example 20
Source File: WebServicesClient.java    From Bats with Apache License 2.0 votes vote down vote up
public abstract T process(WebResource.Builder webResource, Class<T> clazz);