javax.ws.rs.client.Client Java Examples

The following examples show how to use javax.ws.rs.client.Client. 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 Project: AIDR   Author: qcri-social   File: ChannelBufferManager.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Calls the manager's public collection REST API.
 * @return publiclyListed value of given channel name
 */
@SuppressWarnings("unchecked")
public Boolean getChannelPublicStatus(String channelName) {
	String channelCode = parseChannelName(channelName);
	Response clientResponse = null;
	Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();
	try {
		WebTarget webResource = client.target(managerMainUrl 
				+ "/public/collection/getChannelPublicFlagStatus?channelCode=" + channelCode);

		clientResponse = webResource.request(MediaType.APPLICATION_JSON).get();
		Map<String, Boolean> collectionMap = new HashMap<String, Boolean>();

		if (clientResponse.getStatus() == 200) {
			//convert JSON string to Map
			collectionMap = clientResponse.readEntity(Map.class);
			logger.info("Channel info received from manager: " + collectionMap);
			if (collectionMap != null) {
				return collectionMap.get(channelCode);
			}
		} else {
			logger.warn("Couldn't contact AIDRFetchManager for publiclyListed status, channel: " + channelName);
		}
	} catch (Exception e) {
		logger.error("Error in querying manager for running collections: " + clientResponse);
	}
	return true;		// Question: should default be true or false?
}
 
Example #2
Source Project: gitlab4j-api   Author: gitlab4j   File: GitLabApiClient.java    License: MIT License 6 votes vote down vote up
protected Client createApiClient() {

        // Explicitly use an instance of the JerseyClientBuilder, this allows this
        // library to work when both Jersey and Resteasy are present
        ClientBuilder clientBuilder = new JerseyClientBuilder().withConfig(clientConfig);

        // Register JacksonJson as the ObjectMapper provider.
        clientBuilder.register(JacksonJson.class);

        if (ignoreCertificateErrors) {
            clientBuilder.sslContext(openSslContext).hostnameVerifier(openHostnameVerifier);
        }

        apiClient = clientBuilder.build();
        return (apiClient);
    }
 
Example #3
Source Project: mattermost4j   Author: maruTA-bis5   File: FilesApiTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getPublicFileLink() throws URISyntaxException, IOException {
  Path filePath = th.getResourcePath(TestHelper.EMOJI_GLOBE);
  String channelId = th.basicChannel().getId();
  FileUploadResult uploadResult = assertNoError(client.uploadFile(channelId, filePath)).readEntity();
  FileInfo fileInfo = uploadResult.getFileInfos()[0];
  String fileId = fileInfo.getId();

  Post post = new Post(channelId, "file attached post");
  post.setFileIds(Collections.singletonList(fileId));
  post = assertNoError(client.createPost(post)).readEntity();

  String publicLink = assertNoError(client.getPublicFileLink(fileId)).readEntity();

  Client jaxrsClient = ClientBuilder.newClient();
  WebTarget target = jaxrsClient.target(publicLink);
  Response response = target.request().get();
  InputStream downloadFile = response.readEntity(InputStream.class);
  Path tempFile = Files.createTempFile(null, null);
  Files.copy(downloadFile, tempFile, StandardCopyOption.REPLACE_EXISTING);

  assertSameFile(filePath, tempFile);
}
 
Example #4
Source Project: pay-publicapi   Author: alphagov   File: GetPaymentRefundsServiceTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() {
    when(mockConfiguration.getLedgerUrl()).thenReturn(ledgerRule.getUrl());
    when(mockConfiguration.getConnectorUrl()).thenReturn(connectorRule.getUrl());
    when(mockConfiguration.getBaseUrl()).thenReturn("http://publicapi.test.localhost/");

    PublicApiUriGenerator publicApiUriGenerator = new PublicApiUriGenerator(mockConfiguration);
    LedgerUriGenerator ledgerUriGenerator = new LedgerUriGenerator(mockConfiguration);

    Client client = RestClientFactory.buildClient(new RestClientConfig(false));
    LedgerService ledgerService = new LedgerService(client, ledgerUriGenerator);

    ConnectorUriGenerator connectorUriGenerator = new ConnectorUriGenerator(mockConfiguration);
    ConnectorService connectorService = new ConnectorService(client, connectorUriGenerator);

    getPaymentRefundsService = new GetPaymentRefundsService(connectorService, ledgerService, publicApiUriGenerator);
}
 
Example #5
Source Project: boost   Author: MicroShed   File: SystemEndpointIT.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testGetProperties() {
    // String port = System.getProperty("liberty.test.port");
    String port = System.getProperty("boost_http_port");
    // String port = "9000";
    String url = "http://localhost:" + port + "/";

    Client client = ClientBuilder.newClient();
    client.register(JsrJsonpProvider.class);

    WebTarget target = client.target(url + "system/properties");
    Response response = target.request().get();

    assertEquals("Incorrect response code from " + url, 200, response.getStatus());

    JsonObject obj = response.readEntity(JsonObject.class);

    assertEquals("The system property for the local and remote JVM should match", System.getProperty("os.name"),
            obj.getString("os.name"));

    response.close();
}
 
Example #6
Source Project: verify-service-provider   Author: alphagov   File: VerifyServiceProviderFactory.java    License: MIT License 6 votes vote down vote up
public VerifyServiceProviderFactory(
        VerifyServiceProviderConfiguration configuration,
        MetadataResolverBundle<VerifyServiceProviderConfiguration> verifyMetadataBundler,
        MetadataResolverBundle<VerifyServiceProviderConfiguration> msaMetadataBundle,
        Client client) throws KeyException {
    this.configuration = configuration;
    List<KeyPair> decryptionKeyPairs = getDecryptionKeyPairs(
            configuration.getSamlPrimaryEncryptionKey(),
            configuration.getSamlSecondaryEncryptionKey()
    );
    this.keyStore = new IdaKeyStore(null, decryptionKeyPairs);
    this.responseFactory = new ResponseFactory(decryptionKeyPairs);
    this.dateTimeComparator = new DateTimeComparator(configuration.getClockSkew());
    this.entityIdService = new EntityIdService(configuration.getServiceEntityIds());
    this.verifyMetadataBundler = verifyMetadataBundler;
    this.msaMetadataBundle = msaMetadataBundle;
    this.manifestReader = new ManifestReader();
    this.client = client;
    this.hubSignatureValidator = new SignatureValidatorFactory().getSignatureValidator(getHubSignatureTrustEngine());
}
 
Example #7
Source Project: javaee8-cookbook   Author: eldermoraes   File: MpMetricsResource.java    License: Apache License 2.0 6 votes vote down vote up
private String getResource() {
    Client client = null;
    String response;

    try {
        client = ClientBuilder.newClient();
        WebTarget target = client.target("https://eldermoraes.com/book");
        response = target.request()
                .header("Content-Type", "application/json")
                .get(String.class);
    } finally {
        if (client != null) {
            client.close();
        }
    }

    return response;
}
 
Example #8
Source Project: demo-restWS-spring-jersey-tomcat-mybatis   Author: adrianmatei-me   File: SpringContextJerseyTest.java    License: MIT License 6 votes vote down vote up
/**
 * Utility method that safely closes a client instance without throwing an exception.
 *
 * @param clients client instances to close. Each instance may be {@code null}.
 * @since 2.5
 */
public final void close(final Client... clients) {
    if (clients == null || clients.length == 0) {
        return;
    }

    for (Client c : clients) {
        if (c == null) {
            continue;
        }
        try {
            c.close();
        } catch (Throwable t) {
            LOGGER.log(Level.WARNING, "Error closing a client instance.", t);
        }

    }
}
 
Example #9
Source Project: cxf   Author: apache   File: JAXRSAsyncClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNonExistentJaxrs20WithGet() throws Exception {
    String address = "http://168.168.168.168/bookstore";
    Client c = ClientBuilder.newClient();
    c.register(new TestResponseFilter());
    WebTarget t1 = c.target(address);
    Future<Response> future = t1.request().async().get();
    try {
        future.get();
        fail("Exception expected");
    } catch (ExecutionException ex) {
        Throwable cause = ex.getCause();
        assertTrue(cause instanceof ProcessingException);
        assertTrue(ex.getCause().getCause() instanceof IOException);
    } finally {
        c.close();
    }
}
 
Example #10
Source Project: keycloak   Author: keycloak   File: FlowOverrideTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGrantAccessTokenWithClientOverride() throws Exception {
    String clientId = TEST_APP_DIRECT_OVERRIDE;
    Client httpClient = javax.ws.rs.client.ClientBuilder.newClient();
    String grantUri = oauth.getResourceOwnerPasswordCredentialGrantUrl();
    WebTarget grantTarget = httpClient.target(grantUri);

    {   // test no password
        String header = BasicAuthHelper.createHeader(clientId, "password");
        Form form = new Form();
        form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
        form.param("username", "[email protected]");
        Response response = grantTarget.request()
                .header(HttpHeaders.AUTHORIZATION, header)
                .post(Entity.form(form));
        assertEquals(200, response.getStatus());
        response.close();
    }

    httpClient.close();
    events.clear();
}
 
Example #11
Source Project: cloudbreak   Author: hortonworks   File: PrincipalCreator.java    License: Apache License 2.0 6 votes vote down vote up
private void checkTheAvailabilityWithResourceLogin(String objectId, String tenantId, AzureApplication app, Client client) {
    WebTarget loginResource = client.target(LOGIN_MICROSOFTONLINE + tenantId);
    Map<String, String> formData = new HashMap<>();
    formData.put("grant_type", "client_credentials");
    formData.put("client_id", app.getAppId());
    formData.put("client_secret", app.getAzureApplicationCreationView().getAppSecret());
    formData.put("resource", app.getAzureApplicationCreationView().getAppIdentifierURI());
    try (Response loginResponse = loginResource.path("/oauth2/token")
            .request()
            .accept(MediaType.APPLICATION_JSON)
            .header("Content-Type", "application/x-www-form-urlencoded")
            .post(Entity.form(new MultivaluedHashMap<>(formData)))) {
        if (loginResponse.getStatus() != HttpStatus.SC_OK) {
            throw new RetryException("Principal with objectId (" + objectId + ") hasn't been available yet");
        }
    }
}
 
Example #12
Source Project: apicurio-studio   Author: Apicurio   File: Keycloak.java    License: Apache License 2.0 6 votes vote down vote up
public void login() {
    Client client = ClientBuilder.newClient();

    Form form = new Form();
    form.param("client_id", "admin-cli");
    form.param("username", "admin");
    form.param("password", "admin");
    form.param("grant_type", "password");
    Entity<Form> entity = Entity.form(form);

    Response response = client.target(baseUrl + "/auth/realms/master/protocol/openid-connect/token")
            .request(MediaType.APPLICATION_JSON_TYPE)
            .post(entity);
    JsonObject data = (JsonObject) asJson(response);
    this.token = data.getString("access_token");
}
 
Example #13
Source Project: keycloak   Author: keycloak   File: FlowOverrideTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testClientOverrideFlowUsingDirectGrantHttpChallenge() {
    Client httpClient = javax.ws.rs.client.ClientBuilder.newClient();
    String grantUri = oauth.getResourceOwnerPasswordCredentialGrantUrl();
    WebTarget grantTarget = httpClient.target(grantUri);

    // no username/password
    Form form = new Form();
    form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
    form.param(OAuth2Constants.CLIENT_ID, TEST_APP_HTTP_CHALLENGE);
    Response response = grantTarget.request()
            .post(Entity.form(form));
    assertEquals("Basic realm=\"test\"", response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
    assertEquals(401, response.getStatus());
    response.close();

    // now, username password using basic challenge response
    response = grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("[email protected]", "password"))
            .post(Entity.form(form));
    assertEquals(200, response.getStatus());
    response.close();

    httpClient.close();
    events.clear();
}
 
Example #14
Source Project: sample-acmegifts   Author: OpenLiberty   File: OccasionResourceTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Helper method to send a simple http request without a payload
 *
 * @param url the url to call
 * @param requestType the http method to invoke
 * @return the response from the server
 */
public Response sendRequest(String url, String requestType) {
  String method = "sendRequest";
  logger.entering(clazz, method);
  logger.fine("  url: " + url);
  logger.fine("  requestType: " + requestType);

  String jwt = null;
  try {
    jwt = new JWTVerifier().createJWT("fred");
  } catch (Throwable t) {
    throw new RuntimeException(t);
  }

  Client client = ClientBuilder.newClient();
  WebTarget target = client.target(url);
  Invocation.Builder invoBuild = target.request();

  invoBuild.header(HttpHeaders.AUTHORIZATION, "Bearer " + jwt);
  Response response = invoBuild.build(requestType).invoke();

  logger.exiting(
      clazz, method, "\n\n- - - - - Exiting " + method + " with: " + response + "\n\n");
  return response;
}
 
Example #15
Source Project: mangooio   Author: svenkubiak   File: ServerSentEventServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseConnection() throws InterruptedException {
	//given
	ServerSentEventService ServerSentEventService = Application.getInstance(ServerSentEventService.class);
	Config config = Application.getInstance(Config.class);
	Client client = ClientBuilder.newClient();

	//when
	WebTarget webTarget = client.target("http://" + config.getConnectorHttpHost() + ":" + config.getConnectorHttpPort() + "/sse");
	SseEventSource sseEventSource = SseEventSource.target(webTarget).build();
	sseEventSource.register((sseEvent) -> {eventData = sseEvent.readData();}, (e) -> e.printStackTrace());
	sseEventSource.open();
	ServerSentEventService.close("/sse");
	sseEventSource.close();
	client.close();

	//then
	assertThat(ServerSentEventService.getConnections("/sse"), not(nullValue()));
	assertThat(ServerSentEventService.getConnections("/sse").size(), equalTo(0));
}
 
Example #16
Source Project: istio-tutorial   Author: redhat-developer-demos   File: PreferenceEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Produces("text/plain")
public Response getPreference(@HeaderParam("user-agent") String userAgent) {
    try {
        Client client = ClientBuilder.newClient();
        Response res = client.target(remoteURL).request("text/plain").header("user-agent", userAgent).get();
        if (res.getStatus() == Response.Status.OK.getStatusCode()){
            return Response.ok(String.format(RESPONSE_STRING_FORMAT, res.readEntity(String.class))).build();
        }else{
            logger.warn("Non HTTP 20x trying to get the response from preference service: " + res.getStatus());
            return Response
                    .status(Response.Status.SERVICE_UNAVAILABLE)
                    .entity(String.format(RESPONSE_STRING_FORMAT,
                            String.format("Error: %d - %s", res.getStatus(), res.readEntity(String.class)))
                    )
                    .build();
        }
    } catch (ProcessingException ex) {
        logger.warn("Exception trying to get the response from recommendation service.", ex);
        return Response
                .status(Response.Status.SERVICE_UNAVAILABLE)
                .entity(String.format(RESPONSE_STRING_FORMAT, ex.getCause().getClass().getSimpleName() + ": " + ex.getCause().getMessage()))
                .build();
    }
}
 
Example #17
Source Project: aries-jax-rs-whiteboard   Author: apache   File: TestHelper.java    License: Apache License 2.0 6 votes vote down vote up
protected WebTarget createDefaultTarget() {
    Client client = createClient();

    String[] runtimes = canonicalize(
        _runtimeServiceReference.getProperty("osgi.jaxrs.endpoint"));

    if (runtimes.length == 0) {
        throw new IllegalStateException(
            "No runtimes could be found on \"osgi.jaxrs.endpoint\" " +
                "runtime service property ");
    }

    String runtime = runtimes[0];

    return client.target(runtime);
}
 
Example #18
Source Project: cloudbreak   Author: hortonworks   File: ThreadLocalUserCrnWebTargetBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public WebTarget build() {
    ConfigKey configKey = new ConfigKey(secure, debug, ignorePreValidation, TWO_MINUTES_IN_MILLIS);
    Client client = RestClientUtil.get(configKey);
    client.register(clientRequestFilter);
    if (tracer != null) {
        client.register(tracer);
    }
    WebTarget webTarget = client.target(serviceAddress).path(apiRoot);
    LOGGER.info("WebTarget has been created with token: service address: {}, configKey: {}", serviceAddress, configKey);
    return webTarget;
}
 
Example #19
Source Project: cxf   Author: apache   File: FormBehaviorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInterceptorInvokedOnFormAndFormParamMatchesFormValue() throws Exception {
    Client client = ClientBuilder.newClient();
    String uri = "http://localhost:" + PORT + "/form";
    Form f = new Form("value", "ORIGINAL");
    Response r = client.target(uri)
                       .request(MediaType.APPLICATION_FORM_URLENCODED)
                       .post(Entity.form(f));

    Assert.assertEquals("MODIFIED", r.getHeaderString("FromForm"));
    Assert.assertEquals("MODIFIED", r.getHeaderString("FromFormParam"));
}
 
Example #20
Source Project: shiro-jersey   Author: silb   File: AnnotationAuthTest.java    License: Apache License 2.0 5 votes vote down vote up
private Client newClient(Map<String, Object> props) {
    ClientConfig config = new ClientConfig().connectorProvider(new ApacheConnectorProvider());
    if (props != null)
        for (Entry<String, Object> entry : props.entrySet())
            config.property(entry.getKey(), entry.getValue());
    return ClientBuilder.newClient(config);
}
 
Example #21
Source Project: verify-service-provider   Author: alphagov   File: AuthnRequestAcceptanceTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldReturn400WhenPassedNoEntityIdForMultiTenantApplication() throws Exception {
    Client client = new JerseyClientBuilder(multiTenantApplication.getEnvironment()).build("Test Client");

    setupComplianceToolWithEntityId(client, MULTI_ENTITY_ID_1);

    Response authnResponse = client
        .target(URI.create(String.format("http://localhost:%d/generate-request", multiTenantApplication.getLocalPort())))
        .request()
        .buildPost(Entity.json(new RequestGenerationBody(null)))
        .invoke();

    assertThat(authnResponse.getStatus()).isEqualTo(BAD_REQUEST.getStatusCode());
}
 
Example #22
Source Project: pay-publicapi   Author: alphagov   File: CreateTelephonePaymentServiceTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setup() {
    when(configuration.getConnectorUrl()).thenReturn(connectorRule.getUrl()); // We will actually send real requests here, which will be intercepted by pact        

    ConnectorUriGenerator connectorUriGenerator = new ConnectorUriGenerator(configuration);
    Client client = RestClientFactory.buildClient(new RestClientConfig(false));

    createTelephonePaymentService = new CreateTelephonePaymentService(client, connectorUriGenerator);
}
 
Example #23
Source Project: demo-restWS-spring-jersey-jpa2-hibernate   Author: adrianmatei-me   File: RestDemoServiceIT.java    License: MIT License 5 votes vote down vote up
@Test
public void testGetLegacyPodcasts() throws JsonGenerationException,
		JsonMappingException, IOException {

	ClientConfig clientConfig = new ClientConfig();
	clientConfig.register(JacksonFeature.class);

	Client client = ClientBuilder.newClient(clientConfig);

	WebTarget webTarget = client
			.target("http://localhost:8888/demo-rest-spring-jersey-jpa2-hibernate-0.0.1-SNAPSHOT/legacy/podcasts/");

	Builder request = webTarget.request();
	request.header("Content-type", MediaType.APPLICATION_JSON);

	Response response = request.get();
	Assert.assertTrue(response.getStatus() == 200);

	List<Podcast> podcasts = response
			.readEntity(new GenericType<List<Podcast>>() {
			});

	ObjectMapper mapper = new ObjectMapper();
	System.out.print(mapper.writerWithDefaultPrettyPrinter()
			.writeValueAsString(podcasts));

	Assert.assertTrue("At least one podcast is present in the LEGACY",
			podcasts.size() > 0);
}
 
Example #24
Source Project: cloudbreak   Author: hortonworks   File: CloudbreakInfoTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
private void testInfo() {
    String infoUrl = getItContext().getContextParam(CLOUDBREAK_SERVER_ROOT);
    Client client = ClientBuilder.newBuilder().build();
    WebTarget target = client.target(infoUrl).path("info");
    CBVersion cbVersion = target.request().get().readEntity(CBVersion.class);

    Assert.assertEquals(cbVersion.getApp().getName(), "cloudbreak");
    if (getTestParameter().get("target.cbd.version") != null) {
        LOGGER.warn("TARGET_CBD_VERSION is provided.");
        Assert.assertEquals(cbVersion.getApp().getVersion(), getTestParameter().get("target.cbd.version"));
    } else {
        LOGGER.warn("TARGET_CBD_VERSION is not provided!");
    }
}
 
Example #25
Source Project: resteasy-examples   Author: resteasy   File: SimpleClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testProxy() throws Exception
{
   Client client = ClientBuilder.newClient();
   CustomerProxy proxy = ((ResteasyClient) client).target("http://localhost:9095").proxy(CustomerProxy.class);
   Customer cust = proxy.getCustomer("Monica");
   Assert.assertEquals("Monica", cust.getName());
   client.close();
}
 
Example #26
Source Project: java-jaxrs   Author: opentracing-contrib   File: AbstractServerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTracedFalseMethod() {
    Client client = ClientBuilder.newClient();
    Response response = client.target(url("/tracedFalseIn"))
        .request()
        .get();
    response.close();
    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(0, mockSpans.size());
}
 
Example #27
Source Project: tessera   Author: jpmorganchase   File: PartyInfoResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void onSetup() {
    this.partyInfoService = mock(PartyInfoService.class);
    this.partyInfoParser = mock(PartyInfoParser.class);
    this.enclave = mock(Enclave.class);
    this.restClient = mock(Client.class);
    this.payloadEncoder = mock(PayloadEncoder.class);
    this.partyInfoResource =
            new PartyInfoResource(partyInfoService, partyInfoParser, restClient, enclave, payloadEncoder, true);
}
 
Example #28
Source Project: tenacity   Author: yammer   File: TenacityClientBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public TenacityClient build() {
    final Client client = new JerseyClientBuilder(environment)
            .using(jerseyConfiguration)
            .build("tenacity-" + tenacityPropertyKey);
    return new TenacityClient(environment.metrics(), TenacityJerseyClientBuilder
            .builder(tenacityPropertyKey)
            .build(client));
}
 
Example #29
Source Project: demo-rest-jersey-spring   Author: CodepediaOrg   File: RestDemoServiceIT.java    License: MIT License 5 votes vote down vote up
@Test
public void testGetLegacyPodcasts() throws JsonGenerationException,
		JsonMappingException, IOException {

	ClientConfig clientConfig = new ClientConfig();
	clientConfig.register(JacksonFeature.class);

	Client client = ClientBuilder.newClient(clientConfig);

	WebTarget webTarget = client
			.target("http://localhost:8888/demo-rest-jersey-spring/legacy/podcasts/");

	Builder request = webTarget.request();
	request.header("Content-type", MediaType.APPLICATION_JSON);

	Response response = request.get();
	Assert.assertTrue(response.getStatus() == 200);

	List<Podcast> podcasts = response
			.readEntity(new GenericType<List<Podcast>>() {
			});

	ObjectMapper mapper = new ObjectMapper();
	System.out.print(mapper.writerWithDefaultPrettyPrinter()
			.writeValueAsString(podcasts));

	Assert.assertTrue("At least one podcast is present in the LEGACY",
			podcasts.size() > 0);
}
 
Example #30
Source Project: cloudbreak   Author: hortonworks   File: AzureRoleManager.java    License: Apache License 2.0 5 votes vote down vote up
@Retryable(value = InteractiveLoginException.class, maxAttempts = 15, backoff = @Backoff(delay = 1000))
public void assignRole(String accessToken, String subscriptionId, String roleDefinitionId, String principalObjectId) throws InteractiveLoginException {
    Client client = ClientBuilder.newClient();
    WebTarget resource = client.target(AZURE_MANAGEMENT);
    Builder request = resource.path("subscriptions/" + subscriptionId + "/providers/Microsoft.Authorization/roleAssignments/"
            + UUID.randomUUID()).queryParam("api-version", "2015-07-01").request();
    request.accept(MediaType.APPLICATION_JSON);

    request.header("Authorization", "Bearer " + accessToken);

    JsonObject properties = new JsonObject();
    properties.addProperty("roleDefinitionId", roleDefinitionId);
    properties.addProperty("principalId", principalObjectId);

    JsonObject jsonObject = new JsonObject();
    jsonObject.add("properties", properties);

    try (Response response = request.put(Entity.entity(jsonObject.toString(), MediaType.APPLICATION_JSON))) {
        if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
            String errorResponse = response.readEntity(String.class);
            LOGGER.info("Assign role request error - status code: {} - error message: {}", response.getStatus(), errorResponse);
            if (response.getStatusInfo().getStatusCode() == Status.FORBIDDEN.getStatusCode()) {
                throw new InteractiveLoginException("You don't have enough permissions to assign roles, please contact with your administrator");
            } else {
                try {
                    String errorMessage = new ObjectMapper().readTree(errorResponse).get("error").get("message").asText();
                    throw new InteractiveLoginException("Failed to assing role: " + errorMessage);
                } catch (IOException e) {
                    throw new InteractiveLoginException("Failed to assing role (status " + response.getStatus() + "): " + errorResponse);
                }
            }
        } else {
            LOGGER.debug("Role assigned successfully. subscriptionId '{}', roleDefinitionId {}, principalObjectId {}",
                    subscriptionId, roleDefinitionId, principalObjectId);
        }
    }
}