Java Code Examples for javax.ws.rs.core.Response#getLocation()

The following examples show how to use javax.ws.rs.core.Response#getLocation() . 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: NativeApiV15ServiceImpl.java    From paymentgateway with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String paymentProcess(String payId) throws MipsException {
	try {
		PayReq req = new PayReq(merchantId, payId);
		cryptoService.createSignature(req);
		Response response = nativeApiV15Resource.paymentProcess(req.merchantId, req.payId, req.dttm, URLEncoder.encode(req.signature, "UTF-8"));
		if (response == null || response.getStatus() != 303) {
			throw new MipsException(RespCode.INTERNAL_ERROR, "Expected 303 http response from nativeAPI for paymentProcess operation, got response " 
					+ (response != null ? response.getStatus() : "--") + ", payment not found or expired?"); 
		}
		URI uri = response.getLocation();
		if (uri == null) {
			throw new MipsException(RespCode.INTERNAL_ERROR, "Missing location header in response of paymentProcess operation"); 
		}
		return uri.toString();
	} 
	catch (Exception e) {
		throw new MipsException(RespCode.INTERNAL_ERROR, "nativeAPI call for paymentProcess operation failed: ", e); 
	}
}
 
Example 2
Source File: DigdagClient.java    From digdag with Apache License 2.0 6 votes vote down vote up
private <T> T withFollowingRedirect(WebTarget initialWebTarget, RequestWithFollowingRedirect<T> request)
{
    WebApplicationException firstRedirectException = null;
    WebTarget webTarget = initialWebTarget;
    Optional<Response> lastResponse = Optional.absent();

    for (int i = 0; i < MAX_REDIRECT; i++) {
        try {
            return request.invoke(webTarget, lastResponse);
        }
        catch (WebApplicationException e) {
            if (firstRedirectException == null) {
                firstRedirectException = e;
            }
            Response response = checkNotNull(e.getResponse());
            int status = response.getStatus();
            if (status % 100 == 3 && response.getLocation() != null) {
                lastResponse = Optional.of(response);
                webTarget = client.target(UriBuilder.fromUri(response.getLocation()));
                continue;
            }
            throw e;
        }
    }
    throw firstRedirectException;
}
 
Example 3
Source File: TestCaseRuntime.java    From EDDI with Apache License 2.0 6 votes vote down vote up
private ConversationMemorySnapshot runTestCase(String botId, TestCase testCase) throws Exception {
    IRestBotEngine botEngine = restInterfaceFactory.get(IRestBotEngine.class);

    Response ConversationResponse = botEngine.startConversation(Deployment.Environment.test, botId, "testCaseRunner");
    URI conversationURI = ConversationResponse.getLocation();
    String conversationURIPath = conversationURI.getPath();
    String conversationId = conversationURIPath.substring(conversationURIPath.lastIndexOf("/") + 1);
    ConversationMemorySnapshot expected = testCase.getExpected();
    List<ConversationMemorySnapshot.ConversationStepSnapshot> expectedConversationSteps = expected.getConversationSteps();
    //we skip the first one, since the initial run has already been done at this point (at startConversation)
    for (int i = 1; i < expectedConversationSteps.size(); i++) {
        ConversationMemorySnapshot.ConversationStepSnapshot expectedConversationStep = expectedConversationSteps.get(i);
        String input = getFirstInput(expectedConversationStep);
        if (RuntimeUtilities.isNullOrEmpty(input)) {
            input = " ";
        }
        botEngine.say(Deployment.Environment.test, botId, conversationId,
                true, false,
                Collections.emptyList(), input, new MockAsyncResponse());
        while (botEngine.getConversationState(Deployment.Environment.test, conversationId) == ConversationState.IN_PROGRESS) {
            Thread.sleep(1000);
        }
    }

    return conversationMemoryStore.loadConversationMemorySnapshot(conversationId);
}
 
Example 4
Source File: ApplicationResourceTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(dependsOnMethods = { "testDeployApplication", "testLocatedLocation" })
public void testDeployApplicationFromInterface() throws Exception {
    ApplicationSpec spec = ApplicationSpec.builder()
            .type(BasicApplication.class.getCanonicalName())
            .name("simple-app-interface")
            .locations(ImmutableSet.of("localhost"))
            .build();

    Response response = clientDeploy(spec);
    assertTrue(response.getStatus() / 100 == 2, "response is " + response);

    // Expect app to be running
    URI appUri = response.getLocation();
    waitForApplicationToBeRunning(response.getLocation());
    assertEquals(client().path(appUri).get(ApplicationSummary.class).getSpec().getName(), "simple-app-interface");
}
 
Example 5
Source File: NativeApiV17ServiceImpl.java    From paymentgateway with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String paymentProcess(String payId) throws MipsException {
	try {
		PayReq req = new PayReq(merchantId, payId);
		cryptoService.createSignature(req);
		Response response = nativeApiV17Resource.paymentProcess(req.merchantId, req.payId, req.dttm, URLEncoder.encode(req.signature, "UTF-8"));
		if (response == null || response.getStatus() != 303) {
			throw new MipsException(RespCode.INTERNAL_ERROR, "Expected 303 http response from nativeAPI for paymentProcess operation, got response " 
					+ (response != null ? response.getStatus() : "--") + ", payment not found or expired?"); 
		}
		URI uri = response.getLocation();
		if (uri == null) {
			throw new MipsException(RespCode.INTERNAL_ERROR, "Missing location header in response of paymentProcess operation"); 
		}
		return uri.toString();
	} 
	catch (Exception e) {
		throw new MipsException(RespCode.INTERNAL_ERROR, "nativeAPI call for paymentProcess operation failed: ", e); 
	}
}
 
Example 6
Source File: EntityConfigResourceTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@BeforeClass(alwaysRun = true)
public void setUp() throws Exception {
    // Deploy an application that we'll use to read the configuration of
    final ApplicationSpec simpleSpec = ApplicationSpec.builder().name("simple-app").
              entities(ImmutableSet.of(new EntitySpec("simple-ent", RestMockSimpleEntity.class.getName(), ImmutableMap.of("install.version", "1.0.0")))).
              locations(ImmutableSet.of("localhost")).
              build();

    startServer();
    Response response = clientDeploy(simpleSpec);
    int status = response.getStatus();
    assertTrue(status >= 200 && status <= 299, "expected HTTP Response of 2xx but got " + status);
    applicationUri = response.getLocation();
    log.debug("Built app: application");
    waitForApplicationToBeRunning(applicationUri);
    
    entity = (EntityInternal) Iterables.find(getManagementContext().getEntityManager().getEntities(), EntityPredicates.displayNameEqualTo("simple-ent"));
}
 
Example 7
Source File: BatchResponse.java    From syncope with Apache License 2.0 5 votes vote down vote up
public BatchResponse(
        final String boundary,
        final String jwt,
        final TLSClientParameters tlsClientParameters,
        final Response response) {

    this.boundary = boundary;
    this.jwt = jwt;
    this.tlsClientParameters = tlsClientParameters;
    this.monitor = response.getLocation();
    this.response = response;
}
 
Example 8
Source File: SendIT.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void sendTransactionWithMissingRecipients() {

    final Party sendingParty = partyHelper.getParties().findAny().get();
    final byte[] transactionData = utils.createTransactionData();

    final SendRequest sendRequest = new SendRequest();
    sendRequest.setFrom(sendingParty.getPublicKey());
    sendRequest.setPayload(transactionData);

    final Response response =
            client.target(sendingParty.getQ2TUri())
                    .path(SEND_PATH)
                    .request()
                    .post(Entity.entity(sendRequest, MediaType.APPLICATION_JSON));

    final SendResponse result = response.readEntity(SendResponse.class);
    assertThat(result.getKey()).isNotNull().isNotBlank();

    assertThat(response).isNotNull();
    assertThat(response.getStatus()).isEqualTo(201);

    URI location = response.getLocation();

    final Response checkPersistedTxnResponse = client.target(location).request().get();

    assertThat(checkPersistedTxnResponse.getStatus()).isEqualTo(200);

    ReceiveResponse receiveResponse = checkPersistedTxnResponse.readEntity(ReceiveResponse.class);

    assertThat(receiveResponse.getPayload()).isEqualTo(transactionData);

    assertThat(location.getHost()).isEqualTo(sendingParty.getQ2TUri().getHost());
    assertThat(location.getPort()).isEqualTo(sendingParty.getQ2TUri().getPort());
}
 
Example 9
Source File: CreatedResponseUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the Response object, confirms that it returns a 201 created and parses the ID from the location
 * It always assumes the ID is the last segment of the URI
 *
 * @param response The JAX-RS Response received
 * @return The String ID portion of the URI
 * @throws WebApplicationException if the response is not a 201 Created
 */
public static String getCreatedId(Response response) throws WebApplicationException {
    URI location = response.getLocation();
    if (!response.getStatusInfo().equals(Response.Status.CREATED)) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new WebApplicationException("Create method returned status " +
                statusInfo.getReasonPhrase() + " (Code: " + statusInfo.getStatusCode() + "); " +
                "expected status: Created (201)", response);
    }
    if (location == null) {
        return null;
    }
    String path = location.getPath();
    return path.substring(path.lastIndexOf('/') + 1);
}
 
Example 10
Source File: TestsHelper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static String getCreatedId(Response response) {
    URI location = response.getLocation();
    if (!response.getStatusInfo().equals(Response.Status.CREATED)) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new WebApplicationException("Create method returned status "
                + statusInfo.getReasonPhrase() + " (Code: " + statusInfo.getStatusCode() + "); expected status: Created (201)", response);
    }
    if (location == null) {
        return null;
    }
    String path = location.getPath();
    return path.substring(path.lastIndexOf('/') + 1);
}
 
Example 11
Source File: LocationResourceTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testDisplayNameInConfig() {
    String symbolicName = "test_config_displayName_id";
    String yaml = Joiner.on("\n").join(ImmutableList.of(
            "brooklyn.catalog:",
            "  version: " + locationVersion,
            "  items:",
            "  - id: " + symbolicName,
            "    itemType: location",
            "    item:",
            "      type: byon:(hosts=\"" + byonHostname + "\")",
            "      brooklyn.config:",
            "        displayName: " + configDisplayName));

    Response response = client().path("/catalog")
            .post(yaml);

    assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());

    URI addedCatalogItemUri = response.getLocation();
    log.info("added, at: " + addedCatalogItemUri);

    // Ensure location definition exists
    CatalogLocationSummary locationItem = client().path("/catalog/locations/"+symbolicName + "/" + locationVersion)
            .get(CatalogLocationSummary.class);
    log.info(" item: " + locationItem);
    LocationSummary locationSummary = client().path(URI.create("/locations/"+symbolicName+"/")).get(LocationSummary.class);
    log.info(" summary: " + locationSummary);
    Assert.assertEquals(locationSummary.getConfig().get(LocationConfigKeys.DISPLAY_NAME.getName()), configDisplayName);

    FixedListMachineProvisioningLocation<?> l = (FixedListMachineProvisioningLocation<?>) getManagementContext().getLocationRegistry().getLocationManaged(symbolicName);
    Assert.assertEquals(l.getDisplayName(), configDisplayName);
}
 
Example 12
Source File: ResendAllIT.java    From tessera with Apache License 2.0 4 votes vote down vote up
@Test
public void transactionFromSenderDoesNotContainDataOfOtherParties() throws UnsupportedEncodingException, SQLException {
    //setup (sending in a tx)

    Response sendRawResponse = client.target(partyOne.getQ2TUri())
        .path("/sendraw")
        .request()
        .header("c11n-from", partyOne.getPublicKey())
        .header("c11n-to", partyTwo.getPublicKey() + "," + partyThree.getPublicKey())
        .post(Entity.entity(transactionData, MediaType.APPLICATION_OCTET_STREAM));

    URI location = sendRawResponse.getLocation();
    String hash = sendRawResponse.readEntity(String.class);

    final String encodedHash = URLEncoder.encode(hash, UTF_8.toString());

    //delete it from a recipient node
    final Response deleteReq = client.target(partyTwo.getQ2TUri())
        .path("transaction")
        .path(encodedHash)
        .request()
        .delete();
    assertThat(deleteReq).isNotNull();
    assertThat(deleteReq.getStatus()).isEqualTo(204);

    //check it is deleted
    final Response deleteCheck = client.target(partyTwo.getQ2TUri())
        .path("transaction")
        .path(encodedHash)
        .request()
        .get();

    assertThat(deleteCheck).isNotNull();
    assertThat(deleteCheck.getStatus()).isEqualTo(404);

    //request resend from sender
    final ResendRequest req = new ResendRequest();
    req.setType(ResendRequestType.ALL);
    req.setPublicKey(partyTwo.getPublicKey());

    final Response resendRequest = client.target(partyOne.getP2PUri())
        .path(RESEND_PATH)
        .request()
        .buildPost(Entity.entity(req, MediaType.APPLICATION_JSON_TYPE))
        .invoke();

    assertThat(resendRequest).isNotNull();
    assertThat(resendRequest.getStatus()).isEqualTo(200);

    final String fetch = "SELECT ENCODED_PAYLOAD FROM ENCRYPTED_TRANSACTION WHERE HASH = ?";
    final Connection databaseConnection = PartyHelper.create().findByPublicKey(partyTwo.getPublicKey()).getDatabaseConnection();
    try (PreparedStatement statement = databaseConnection.prepareStatement(fetch)){
        statement.setBytes(1, Base64.getDecoder().decode(hash));
        try (ResultSet rs = statement.executeQuery()){
            assertThat(rs.next()).isTrue();
            final byte[] output = rs.getBytes(1);
            final EncodedPayload payload = ENCODER.decode(output);
            assertThat(payload.getRecipientKeys()).hasSize(0);
            assertThat(payload.getSenderKey().encodeToBase64()).isEqualTo(partyOne.getPublicKey());
            assertThat(payload.getRecipientBoxes()).hasSize(1);
        }
    }
}
 
Example 13
Source File: OIDCFiltersTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testClientCodeRequestFilter() throws Exception {
    // Make an invocation + get back the redirection to the OIDC IdP
    String address = "https://localhost:" + PORT + "/secured/bookstore/books";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), null);

    WebClient.getConfig(client).getRequestContext().put(
            org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    Response response = client.get();

    URI location = response.getLocation();
    // Now make an invocation on the OIDC IdP using another WebClient instance

    WebClient idpClient = WebClient.create(location.toString(), OAuth2TestUtils.setupProviders(),
                                           "bob", "security", null)
        .type("application/json").accept("application/json");
    // Save the Cookie for the second request...
    WebClient.getConfig(idpClient).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Make initial authorization request
    final OAuthAuthorizationData authzData = idpClient.get(OAuthAuthorizationData.class);

    // Get Authorization Code + State
    String authzCodeLocation = OAuth2TestUtils.getLocation(idpClient, authzData, null);
    String state = OAuth2TestUtils.getSubstring(authzCodeLocation, "state");
    assertNotNull(state);
    String code = OAuth2TestUtils.getSubstring(authzCodeLocation, "code");
    assertNotNull(code);

    // Add Referer
    String referer = "https://localhost:" + OIDC_PORT + "/services/authorize";
    client.header("Referer", referer);

    // Now invoke back on the service using the authorization code
    client.query("code", code);
    client.query("state", state);

    Response serviceResponse = client.type("application/xml").post(new Book("book", 123L));
    assertEquals(serviceResponse.getStatus(), 200);

    Book returnedBook = serviceResponse.readEntity(Book.class);
    assertEquals(returnedBook.getName(), "book");
    assertEquals(returnedBook.getId(), 123L);
}
 
Example 14
Source File: SendIT.java    From tessera with Apache License 2.0 4 votes vote down vote up
/** Quorum sends transaction with single public recipient key */
@Test
public void sendToSingleRecipient() {

    Party firstParty = partyHelper.findByAlias("A");
    Party secondParty = partyHelper.findByAlias("B");
    byte[] transactionData = utils.createTransactionData();

    final SendRequest sendRequest = new SendRequest();
    sendRequest.setFrom(firstParty.getPublicKey());
    sendRequest.setTo(secondParty.getPublicKey());
    sendRequest.setPayload(transactionData);

    final Response response =
            client.target(firstParty.getQ2TUri())
                    .path(SEND_PATH)
                    .request()
                    .post(Entity.entity(sendRequest, MediaType.APPLICATION_JSON));

    // validate result
    final SendResponse result = response.readEntity(SendResponse.class);
    assertThat(result.getKey()).isNotNull().isNotBlank();

    assertThat(response).isNotNull();
    assertThat(response.getStatus()).isEqualTo(201);

    URI location = response.getLocation();

    final Response checkPersistedTxnResponse = client.target(location).request().get();

    assertThat(checkPersistedTxnResponse.getStatus()).isEqualTo(200);

    ReceiveResponse receiveResponse = checkPersistedTxnResponse.readEntity(ReceiveResponse.class);

    assertThat(receiveResponse.getPayload())
        .describedAs("The response payload should be equal to the sent txn data")
        .isEqualTo(transactionData);

    utils.findTransaction(result.getKey(), partyHelper.findByAlias("A"), partyHelper.findByAlias("B"))
            .forEach(
                    r -> {
                        assertThat(r.getStatus()).isEqualTo(200);
                    });

    utils.findTransaction(result.getKey(), partyHelper.findByAlias("D"))
            .forEach(
                    r -> {
                        assertThat(r.getStatus()).isEqualTo(404);
                    });
}
 
Example 15
Source File: SendIT.java    From tessera with Apache License 2.0 4 votes vote down vote up
/** Quorum sends transaction with multiple public recipient keys */
@Test
public void firstPartyForwardsToTwoOtherParties() {

    final Party sendingParty = partyHelper.findByAlias("A");

    final Party secondParty = partyHelper.findByAlias("B");
    final Party thirdParty = partyHelper.findByAlias("D");

    final Party excludedParty = partyHelper.findByAlias("C");

    final byte[] transactionData = utils.createTransactionData();

    final SendRequest sendRequest = new SendRequest();
    sendRequest.setFrom(sendingParty.getPublicKey());
    sendRequest.setTo(secondParty.getPublicKey(), thirdParty.getPublicKey());
    sendRequest.setPayload(transactionData);

    final Response response =
            client.target(sendingParty.getQ2TUri())
                    .path(SEND_PATH)
                    .request()
                    .post(Entity.entity(sendRequest, MediaType.APPLICATION_JSON));

    //
    final SendResponse result = response.readEntity(SendResponse.class);
    assertThat(result.getKey()).isNotNull().isNotBlank();

    assertThat(response).isNotNull();
    assertThat(response.getStatus()).isEqualTo(201);

    URI location = response.getLocation();

    final Response checkPersistedTxnResponse = client.target(location).request().get();

    assertThat(checkPersistedTxnResponse.getStatus()).isEqualTo(200);

    ReceiveResponse receiveResponse = checkPersistedTxnResponse.readEntity(ReceiveResponse.class);

    assertThat(receiveResponse.getPayload()).isEqualTo(transactionData);

    utils.findTransaction(result.getKey(), sendingParty, secondParty, thirdParty)
            .forEach(
                    r -> {
                        assertThat(r.getStatus()).isEqualTo(200);
                    });

    utils.findTransaction(result.getKey(), excludedParty)
            .forEach(
                    r -> {
                        assertThat(r.getStatus()).isEqualTo(404);
                    });
}
 
Example 16
Source File: BatchITCase.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Test
public void webClientAsync() throws IOException {
    String boundary = "--batch_" + UUID.randomUUID().toString();

    // request async processing
    Response response = WebClient.create(ADDRESS).path("batch").
            header(HttpHeaders.AUTHORIZATION, "Bearer " + adminClient.getJWT()).
            header(RESTHeaders.PREFER, Preference.RESPOND_ASYNC).
            type(RESTHeaders.multipartMixedWith(boundary.substring(2))).
            post(requestBody(boundary));
    assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatus());
    assertTrue(response.getMediaType().toString().
            startsWith(RESTHeaders.multipartMixedWith(boundary.substring(2))));
    assertEquals(Preference.RESPOND_ASYNC.toString(), response.getHeaderString(RESTHeaders.PREFERENCE_APPLIED));
    URI monitor = response.getLocation();
    assertNotNull(monitor);

    WebClient client = WebClient.create(monitor).
            header(HttpHeaders.AUTHORIZATION, "Bearer " + adminClient.getJWT()).
            type(RESTHeaders.multipartMixedWith(boundary.substring(2)));

    int i = 0;
    do {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }

        response = client.get();

        i++;
    } while (response.getStatus() == Response.Status.ACCEPTED.getStatusCode() && i < MAX_WAIT_SECONDS);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    assertTrue(response.getMediaType().toString().
            startsWith(RESTHeaders.multipartMixedWith(boundary.substring(2))));

    String body = IOUtils.toString((InputStream) response.getEntity(), StandardCharsets.UTF_8);
    LOG.debug("Batch response body:\n{}", body);

    check(BatchPayloadParser.parse(
            new ByteArrayInputStream(body.getBytes()),
            response.getMediaType(),
            new BatchResponseItem()));

    // check results again: removed since they were returned above
    response = WebClient.create(monitor).
            header(HttpHeaders.AUTHORIZATION, "Bearer " + adminClient.getJWT()).
            type(RESTHeaders.multipartMixedWith(boundary.substring(2))).get();
    assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
 
Example 17
Source File: AuthorizeRestWebServiceEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"authorizePath", "userId", "userSecret", "redirectUri"})
@Test(dependsOnMethods = "dynamicClientRegistration")
public void requestAuthorizationTokenCode(final String authorizePath, final String userId, final String userSecret,
                                          final String redirectUri) throws Exception {
    final String state = UUID.randomUUID().toString();

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.CODE);
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String nonce = UUID.randomUUID().toString();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId1, scopes,
            redirectUri, nonce);
    authorizationRequest.setState(state);
    authorizationRequest.getPrompts().add(Prompt.NONE);
    authorizationRequest.setAuthUsername(userId);
    authorizationRequest.setAuthPassword(userSecret);

    Builder request = ResteasyClientBuilder.newClient()
            .target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
    request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
    request.header("Accept", MediaType.TEXT_PLAIN);

    Response response = request.get();
    String entity = response.readEntity(String.class);

    showResponse("requestAuthorizationTokenCode", response, entity);

    assertEquals(response.getStatus(), 302, "Unexpected response code.");
    assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

    if (response.getLocation() != null) {
        try {
            URI uri = new URI(response.getLocation().toString());
            assertNotNull(uri.getFragment(), "Fragment is null");

            Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());

            assertNotNull(params.get(AuthorizeResponseParam.CODE), "The code is null");
            assertNotNull(params.get(AuthorizeResponseParam.ACCESS_TOKEN), "The access token is null");
            assertNotNull(params.get(AuthorizeResponseParam.TOKEN_TYPE), "The token type is null");
            assertNotNull(params.get(AuthorizeResponseParam.STATE), "The state is null");
            assertEquals(params.get(AuthorizeResponseParam.STATE), state);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            fail("Response URI is not well formed");
        }
    }
}
 
Example 18
Source File: Jersey2Test.java    From jerseyoauth2 with MIT License 4 votes vote down vote up
protected Map<String, String> retrieveCode(String authUrl) throws UnsupportedEncodingException {
	Invocation.Builder request = client.target(authUrl).request();
	Response response = request.get();
	URI location = response.getLocation();
	return splitQuery(location.getQuery());
}
 
Example 19
Source File: AuthorizeRestWebServiceEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"authorizePath", "userId", "userSecret", "redirectUri"})
@Test(dependsOnMethods = "dynamicClientRegistration")
public void requestAuthorizationAccessTokenStep1(final String authorizePath, final String userId,
                                                 final String userSecret, final String redirectUri) throws Exception {
    final String state = UUID.randomUUID().toString();

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN);
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String nonce = UUID.randomUUID().toString();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId1, scopes,
            redirectUri, nonce);
    authorizationRequest.setState(state);
    authorizationRequest.getPrompts().add(Prompt.NONE);
    authorizationRequest.setAuthUsername(userId);
    authorizationRequest.setAuthPassword(userSecret);

    Builder request = ResteasyClientBuilder.newClient()
            .target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
    request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
    request.header("Accept", MediaType.TEXT_PLAIN);

    Response response = request.get();
    String entity = response.readEntity(String.class);

    showResponse("requestAuthorizationAccessTokenStep1", response, entity);

    assertEquals(response.getStatus(), 302, "Unexpected response code.");
    assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

    if (response.getLocation() != null) {
        try {
            URI uri = new URI(response.getLocation().toString());
            assertNotNull(uri.getFragment(), "Fragment is null");

            Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());

            assertNotNull(params.get(AuthorizeResponseParam.ACCESS_TOKEN), "The access token is null");
            assertNotNull(params.get(AuthorizeResponseParam.STATE), "The state is null");
            assertNotNull(params.get(AuthorizeResponseParam.TOKEN_TYPE), "The token type is null");
            assertNotNull(params.get(AuthorizeResponseParam.EXPIRES_IN), "The expires in value is null");
            assertNotNull(params.get(AuthorizeResponseParam.SCOPE), "The scope must be null");
            assertNull(params.get("refresh_token"), "The refresh_token must be null");
            assertEquals(params.get(AuthorizeResponseParam.STATE), state);

            accessToken2 = params.get("access_token");
        } catch (URISyntaxException e) {
            e.printStackTrace();
            fail("Response URI is not well formed");
        }
    }
}
 
Example 20
Source File: OpenIDRequestObjectEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri" })
@Test(dependsOnMethods = "dynamicClientRegistration")
public void requestFileMethodFail1(final String authorizePath, final String userId, final String userSecret,
		final String redirectUri) throws Exception {

	final String state = UUID.randomUUID().toString();

	List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN);
	List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
	String nonce = UUID.randomUUID().toString();

	AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes,
			redirectUri, nonce);
	authorizationRequest.setState(state);
	authorizationRequest.getPrompts().add(Prompt.NONE);
	authorizationRequest.setAuthUsername(userId);
	authorizationRequest.setAuthPassword(userSecret);

	authorizationRequest.setRequest("FAKE_REQUEST");
	authorizationRequest.setRequestUri("FAKE_REQUEST_URI");

	Builder request = ResteasyClientBuilder.newClient()
			.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
	request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
	request.header("Accept", MediaType.TEXT_PLAIN);

	Response response = request.get();
	String entity = response.readEntity(String.class);

	showResponse("requestFileMethodFail1", response, entity);

	assertEquals(response.getStatus(), 302, "Unexpected response code.");
	assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

	if (response.getLocation() != null) {
		try {
			URI uri = new URI(response.getLocation().toString());
			assertNotNull(uri.getFragment(), "Fragment is null");

			Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());

			assertNotNull(params.get("error"), "The error value is null");
			assertNotNull(params.get("error_description"), "The errorDescription value is null");
			assertNotNull(params.get(AuthorizeResponseParam.STATE), "The state is null");
			assertEquals(params.get(AuthorizeResponseParam.STATE), state);
		} catch (URISyntaxException e) {
			e.printStackTrace();
			fail("Response URI is not well formed");
		}
	}
}