javax.ws.rs.client.Invocation.Builder Java Examples

The following examples show how to use javax.ws.rs.client.Invocation.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: UserInfoRestWebServiceEmbeddedTest.java    From oxAuth with MIT License 6 votes vote down vote up
@Parameters({"userInfoPath"})
@Test
public void requestUserInfoInvalidToken(final String userInfoPath) throws Exception {
    UserInfoRequest userInfoRequest = new UserInfoRequest("INVALID_ACCESS_TOKEN");
    userInfoRequest.setAuthorizationMethod(AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER);

    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + userInfoPath).request();
    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(userInfoRequest.getParameters())));
    String entity = response.readEntity(String.class);

    showResponse("requestUserInfoInvalidToken", response, entity);

    assertEquals(response.getStatus(), 401, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example #2
Source File: FHIRClientImpl.java    From FHIR with Apache License 2.0 6 votes vote down vote up
@Override
public FHIRResponse invoke(String resourceType, String operationName, String resourceId, String versionId, FHIRParameters parameters, FHIRRequestHeader... headers) throws Exception {
    if (resourceType == null) {
        throw new IllegalArgumentException("The 'resourceType' argument is required but was null.");
    }
    if (operationName == null) {
        throw new IllegalArgumentException("The 'operationName' argument is required but was null.");
    }
    if (resourceId == null) {
        throw new IllegalArgumentException("The 'resourceId' argument is required but was null.");
    }
    if (versionId == null) {
        throw new IllegalArgumentException("The 'versionId' argument is required but was null.");
    }
    WebTarget endpoint = getWebTarget();
    endpoint = endpoint.path(resourceType).path(resourceId).path("_history").path(versionId).path(operationName);
    endpoint = addParametersToWebTarget(endpoint, parameters);
    Invocation.Builder builder = endpoint.request(getDefaultMimeType());
    builder = addRequestHeaders(builder, headers);
    Response response = builder.get();
    return new FHIRResponseImpl(response);
}
 
Example #3
Source File: AzureInteractiveLoginStatusCheckerTask.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private String createResourceToken(String refreshToken, String tenantId, String resource) throws InteractiveLoginException {
    Form resourceTokenForm = createResourceTokenForm(refreshToken, resource);
    WebTarget webTarget = ClientBuilder.newClient().target(LOGIN_MICROSOFTONLINE);
    Builder request = webTarget.path(tenantId + "/oauth2/token").queryParam("api-version", "1.0").request();
    request.accept(MediaType.APPLICATION_JSON);
    try (Response response = request.post(Entity.entity(resourceTokenForm, MediaType.APPLICATION_FORM_URLENCODED_TYPE))) {
        if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
            throw new InteractiveLoginException("Obtain access token for " + resource + " failed "
                    + "with tenant ID: " + tenantId + ", status code " + response.getStatus()
                    + ", error message: " + response.readEntity(String.class));
        }
        String responseString = response.readEntity(String.class);
        try {
            return new ObjectMapper().readTree(responseString).get("access_token").asText();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }
}
 
Example #4
Source File: EndSessionRestWebServiceEmbeddedTest.java    From oxAuth with MIT License 6 votes vote down vote up
@Parameters({"endSessionPath"})
@Test(enabled = true) // switched off test : WebApplicationException seems to not translated correctly into response by container and results in 500 error. See org.gluu.oxauth.session.ws.rs.EndSessionRestWebServiceImpl.endSession()
public void requestEndSessionFail1(final String endSessionPath) throws Exception {
    EndSessionRequest endSessionRequest = new EndSessionRequest(null, null, null);

    Builder request = ResteasyClientBuilder.newClient()
            .target(url.toString() + endSessionPath + "?" + endSessionRequest.getQueryString()).request();
    request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);

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

    showResponse("requestEndSessionFail1", response, entity);

    assertEquals(response.getStatus(), 400, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example #5
Source File: HMACFilterAuthenticationProvider.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * For REST Easy {@link ClientRequest}
 *
 * @param req
 * @throws HMACSecurityException
 */
public void provideAuthentication(Builder request, WebTarget target, MultivaluedMap<String, Object> myHeaders, Object data) throws HMACSecurityException {
	Helper.checkNotNull(request, "req");

	String token = validator.generateToken();
	Assert.assertNotNull(token, "token");
	String signature;
	try {
		signature = getSignature(request, target, data, myHeaders, token);
	} catch (Exception e) {
		throw new HMACSecurityException("Problems while signing the request", e);
	}

	request.header(HMACUtils.HMAC_TOKEN_HEADER, token);
	request.header(HMACUtils.HMAC_SIGNATURE_HEADER, signature);
	myHeaders.add(HMACUtils.HMAC_TOKEN_HEADER, token);
	myHeaders.add(HMACUtils.HMAC_SIGNATURE_HEADER, signature);

}
 
Example #6
Source File: RTransactionImpl.java    From jcypher with Apache License 2.0 6 votes vote down vote up
public synchronized Invocation.Builder getInvocationBuilder() {
	Invocation.Builder ret;
	RemoteDBAccess rdba = getRDBAccess();
	if (this.invocationBuilder_open == null) {
		WebTarget serverRootTarget = rdba.getRestClient().target(rdba.getServerRootUri());
		WebTarget transactionalTarget = serverRootTarget.path(transactionalURLPostfix);
		this.invocationBuilder_open = transactionalTarget.request(MediaType.APPLICATION_JSON_TYPE);
		if (rdba.getAuth() != null)
			this.invocationBuilder_open = this.invocationBuilder_open.header(RemoteDBAccess.authHeader, rdba.getAuth());
		ret = this.invocationBuilder_open;
	} else if (this.invocationBuilder_next == null) {
		this.invocationBuilder_next = createNextInvocationBuilder();
		ret = this.invocationBuilder_next;
	} else {
		ret = this.invocationBuilder_next;
	}
	return ret;
}
 
Example #7
Source File: GETServiceBean.java    From OpenIoE with Apache License 2.0 6 votes vote down vote up
@Override
public String get(String server, String path) throws InvalidResponseException {
	String json =  null;
	Client client = null;
	try {
		client = ClientBuilder.newBuilder().build();
		WebTarget webResource = client.target(server);
		webResource = webResource.path(path);
		Builder builder = webResource.request(MediaType.APPLICATION_JSON);
		builder.accept(MediaType.APPLICATION_JSON);
		Response response = builder.get();
		if (response.getStatus() == Status.OK.getStatusCode()) {
			json = response.readEntity(String.class);
		} else {
			throw new InvalidResponseException("Response code is not 200.");
		}
	} catch (Exception ex) {
		throw new InvalidResponseException("GET error when calling server: " + server + " path: " + path + ". " + ex.getMessage());
	} finally {
		if(client != null) {
			client.close();
		}
	}
	return json;
}
 
Example #8
Source File: FHIRClientImpl.java    From FHIR with Apache License 2.0 6 votes vote down vote up
@Override
public FHIRResponse vread(String resourceType, String resourceId, String versionId, FHIRRequestHeader... headers) throws Exception {
    if (resourceType == null) {
        throw new IllegalArgumentException("The 'resourceType' argument is required but was null.");
    }
    if (resourceId == null) {
        throw new IllegalArgumentException("The 'resourceId' argument is required but was null.");
    }
    if (versionId == null) {
        throw new IllegalArgumentException("The 'versionId' argument is required but was null.");
    }
    WebTarget endpoint = getWebTarget();
    Invocation.Builder builder = endpoint.path(resourceType).path(resourceId).path("_history").path(versionId).request(getDefaultMimeType());
    builder = addRequestHeaders(builder, headers);
    Response response = builder.get();
    return new FHIRResponseImpl(response);
}
 
Example #9
Source File: JwkRestWebServiceEmbeddedTest.java    From oxAuth with MIT License 6 votes vote down vote up
@Parameters({"jwksPath"})
@Test
public void requestJwks(final String jwksPath) throws Exception {

    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + jwksPath).request();
    request.header("Accept", MediaType.APPLICATION_JSON);

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

    showResponse("requestJwks", response, entity);

    assertEquals(response.getStatus(), 200, "Unexpected response code.");

    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has(JSON_WEB_KEY_SET), "Unexpected result: keys not found");
        JSONArray keys = jsonObj.getJSONArray(JSON_WEB_KEY_SET);
        assertNotNull(keys, "Unexpected result: keys is null");
        assertTrue(keys.length() > 0, "Unexpected result: keys is empty");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example #10
Source File: MCRWorksPublisher.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/** Publishes the object (its MODS) as a new "work" in the ORCID profile */
MCRWork createWorkFrom(MCRObjectID objectID)
    throws IOException, JDOMException, SAXException {
    WebTarget target = orcid.getWebTarget().path("work");
    Builder builder = buildInvocation(target);

    Document workXML = buildWorkXMLFrom(objectID);
    Entity<InputStream> input = buildRequestEntity(workXML);

    LOGGER.info("post (create) {} at {}", objectID, target.getUri());
    Response response = builder.post(input);
    expect(response, Response.Status.CREATED);

    String putCode = getPutCode(response);
    MCRWork work = new MCRWork(orcid, putCode);
    work.fetchDetails();
    return work;
}
 
Example #11
Source File: TokenRestWebServiceEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Parameters({"tokenPath"})
@Test(dependsOnMethods = "dynamicClientRegistration")
public void refreshingAccessTokenFail(final String tokenPath) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();

    TokenRequest tokenRequest = new TokenRequest(GrantType.REFRESH_TOKEN);
    tokenRequest.setRefreshToken("tGzv3JOkF0XG5Qx2TlKWIA");
    tokenRequest.setScope("email read_stream manage_pages");
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);

    request.header("Authorization", "Basic " + tokenRequest.getEncodedCredentials());
    request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);

    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
    String entity = response.readEntity(String.class);

    showResponse("refreshingAccessTokenFail", response, entity);

    assertEquals(response.getStatus(), 400, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example #12
Source File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Read client to check whether it is using the Token Endpoint Auth Method
 * <code>client_secret_jwt</code>.
 */
@Parameters({"registerPath"})
@Test(dependsOnMethods = "tokenEndpointAuthMethodClientSecretJwtStep1")
public void tokenEndpointAuthMethodClientSecretJwtStep2(final String registerPath) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath + "?"
            + registrationClientUri4.substring(registrationClientUri4.indexOf("?") + 1)).request();
    request.header("Authorization", "Bearer " + registrationAccessToken4);

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

    showResponse("tokenEndpointAuthMethodClientSecretJwtStep2", response, entity);

    assertEquals(response.getStatus(), 200, "Unexpected response code. " + entity);
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has(RegisterResponseParam.CLIENT_ID.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET.toString()));
        assertTrue(jsonObj.has(CLIENT_ID_ISSUED_AT.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET_EXPIRES_AT.toString()));

        // Registered Metadata
        assertTrue(jsonObj.has(TOKEN_ENDPOINT_AUTH_METHOD.toString()));
        assertEquals(jsonObj.getString(TOKEN_ENDPOINT_AUTH_METHOD.toString()),
                AuthenticationMethod.CLIENT_SECRET_JWT.toString());
        assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
        assertTrue(jsonObj.has(RESPONSE_TYPES.toString()));
        assertTrue(jsonObj.has(REDIRECT_URIS.toString()));
        assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
        assertTrue(jsonObj.has(CLIENT_NAME.toString()));
        assertTrue(jsonObj.has(ID_TOKEN_SIGNED_RESPONSE_ALG.toString()));
        assertTrue(jsonObj.has(SCOPE.toString()));
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example #13
Source File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Parameters({ "registerPath", "redirectUris", "clientJwksUri" })
@Test
public void requestParameterMethodRS384X509CertStep1(final String registerPath, final String redirectUris,
		final String jwksUri) throws Exception {
	Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

	String registerRequestContent = null;
	try {
		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);

		RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
				StringUtils.spaceSeparatedToList(redirectUris));
		registerRequest.setJwksUri(jwksUri);
		registerRequest.setResponseTypes(responseTypes);
		registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.RS384);
		registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

		registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
	} catch (JSONException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

	Response response = request.post(Entity.json(registerRequestContent));
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodRS384X509CertStep1", response, entity);

	ResponseAsserter responseAsserter = ResponseAsserter.of(response.getStatus(), entity);
	responseAsserter.assertRegisterResponse();
	clientId5 = responseAsserter.getJson().getJson().getString(RegisterResponseParam.CLIENT_ID.toString());
}
 
Example #14
Source File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Read client to check whether it is using the default Token Endpoint Auth
 * Method <code>client_secret_basic</code>.
 */
@Parameters({"registerPath"})
@Test(dependsOnMethods = "omittedTokenEndpointAuthMethodStep1")
public void omittedTokenEndpointAuthMethodStep2(final String registerPath) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath + "?"
            + registrationClientUri1.substring(registrationClientUri1.indexOf("?") + 1)).request();
    request.header("Authorization", "Bearer " + registrationAccessToken1);

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

    showResponse("omittedTokenEndpointAuthMethodStep2", response, entity);

    assertEquals(response.getStatus(), 200, "Unexpected response code. " + entity);
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has(RegisterResponseParam.CLIENT_ID.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET.toString()));
        assertTrue(jsonObj.has(CLIENT_ID_ISSUED_AT.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET_EXPIRES_AT.toString()));

        // Registered Metadata
        assertTrue(jsonObj.has(TOKEN_ENDPOINT_AUTH_METHOD.toString()));
        assertEquals(jsonObj.getString(TOKEN_ENDPOINT_AUTH_METHOD.toString()),
                AuthenticationMethod.CLIENT_SECRET_BASIC.toString());
        assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
        assertTrue(jsonObj.has(RESPONSE_TYPES.toString()));
        assertTrue(jsonObj.has(REDIRECT_URIS.toString()));
        assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
        assertTrue(jsonObj.has(CLIENT_NAME.toString()));
        assertTrue(jsonObj.has(ID_TOKEN_SIGNED_RESPONSE_ALG.toString()));
        assertTrue(jsonObj.has(SCOPE.toString()));
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example #15
Source File: NetworkResourceTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
private Builder getForkSnapshotTarget(String network) {
  return target(CoordConsts.SVC_CFG_WORK_MGR2)
      .path(CoordConstsV2.RSC_NETWORKS)
      .path(network)
      .path(CoordConstsV2.RSC_SNAPSHOTS + ":" + CoordConstsV2.RSC_FORK)
      .request()
      .header(CoordConstsV2.HTTP_HEADER_BATFISH_VERSION, BatfishVersion.getVersionStatic())
      .header(CoordConstsV2.HTTP_HEADER_BATFISH_APIKEY, CoordConsts.DEFAULT_API_KEY);
}
 
Example #16
Source File: InvocationBuilderImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public Builder property(String name, Object value) {
    Map<String, Object> contextProps = WebClient.getConfig(webClient).getRequestContext();
    Map<String, Object> filterProps = CastUtils.cast((Map<?, ?>)contextProps.get(PROPERTY_KEY));
    if (filterProps == null) {
        filterProps = new HashMap<>();
        contextProps.put(PROPERTY_KEY, filterProps);
    }
    if (value == null) {
        filterProps.remove(name);
    } else {
        filterProps.put(name, value);
    }
    return this;
}
 
Example #17
Source File: SchemaRegisterResourceTest.java    From hermes with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSchema() {
	Client client = ClientBuilder.newClient();
	WebTarget webTarget = client.target("http://localhost:1248");
	Builder request = webTarget.path("/schema/register").queryParam("id", 142).request();
	String schema = request.get(String.class);
	System.out.println(schema);
	Assert.assertNotNull(schema);
}
 
Example #18
Source File: SchemaRegisterResourceTest.java    From hermes with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegisterSchema() {
	String schemaString = "{\"namespace\": \"com.ctrip.hermes.kafka.avro\", \"type\": \"record\", \"name\": \"AvroVisitEvent\", \"fields\": [ {\"name\": \"ip\", \"type\": \"string\"}, {\"name\": \"url\", \"type\": \"string\"}, {\"name\": \"tz\", \"type\": \"long\", \"java-class\":\"java.util.Date\"} ] }";
	Client client = ClientBuilder.newClient();
	WebTarget webTarget = client.target("http://localhost:1248");
	Builder request = webTarget.path("/schema/register").request();
	Map<String, String> params = new HashMap<String, String>();
	params.put("schema", schemaString);
	params.put("subject", "test-subject-001");
	int id = request.post(Entity.json(params), Integer.class);
	System.out.println(id);
	Assert.assertTrue(id > 0);
}
 
Example #19
Source File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Parameters({ "registerPath", "redirectUris", "clientJwksUri" })
@Test
public void requestParameterMethodRS256Step1(final String registerPath, final String redirectUris,
		final String jwksUri) throws Exception {
	Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

	String registerRequestContent = null;
	try {
		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);

		RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
				StringUtils.spaceSeparatedToList(redirectUris));
		registerRequest.setJwksUri(jwksUri);
		registerRequest.setResponseTypes(responseTypes);
		registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.RS256);
		registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

		registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
	} catch (JSONException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

	Response response = request.post(Entity.json(registerRequestContent));
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodRS256Step1", response, entity);

	ResponseAsserter responseAsserter = ResponseAsserter.of(response.getStatus(), entity);
	responseAsserter.assertRegisterResponse();
	clientId1 = responseAsserter.getJson().getJson().getString(RegisterResponseParam.CLIENT_ID.toString());
}
 
Example #20
Source File: InvocationBuilderImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public Builder acceptLanguage(Locale... lang) {
    for (Locale l : lang) {
        webClient.acceptLanguage(HttpUtils.toHttpLanguage(l));
    }
    return this;
}
 
Example #21
Source File: ApplicationTypeRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Read client to check whether it is using the default Application Type
 * <code>web</code>.
 */
@Parameters({"registerPath"})
@Test(dependsOnMethods = "omittedApplicationTypeStep1")
public void omittedApplicationTypeStep2(final String registerPath) throws Exception {

    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath + "?"
            + registrationClientUri1.substring(registrationClientUri1.indexOf("?") + 1)).request();
    request.header("Authorization", "Bearer " + registrationAccessToken1);

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

    showResponse("omittedApplicationTypeStep2", response, entity);

    assertEquals(response.getStatus(), 200, "Unexpected response code. " + entity);
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has(RegisterResponseParam.CLIENT_ID.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET.toString()));
        assertTrue(jsonObj.has(CLIENT_ID_ISSUED_AT.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET_EXPIRES_AT.toString()));

        // Registered Metadata
        assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
        assertEquals(jsonObj.getString(APPLICATION_TYPE.toString()), ApplicationType.WEB.toString());
        assertTrue(jsonObj.has(RESPONSE_TYPES.toString()));
        assertNotNull(jsonObj.optJSONArray(RESPONSE_TYPES.toString()));
        assertEquals(jsonObj.getJSONArray(RESPONSE_TYPES.toString()).getString(0), ResponseType.CODE.toString());
        assertTrue(jsonObj.has(REDIRECT_URIS.toString()));
        assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
        assertTrue(jsonObj.has(CLIENT_NAME.toString()));
        assertTrue(jsonObj.has(ID_TOKEN_SIGNED_RESPONSE_ALG.toString()));
        assertTrue(jsonObj.has(SCOPE.toString()));
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example #22
Source File: TestClientRegistrarWebServices.java    From microprofile-opentracing with Apache License 2.0 5 votes vote down vote up
private Response executeSimpleEndpoint(Client client, boolean async)
    throws ExecutionException, InterruptedException {
    Builder requestBuilder = client.target(uri.getBaseUri())
        .path(REST_SERVICE_PATH)
        .path(REST_OK)
        .request();

    Response response = async ? requestBuilder.async().get().get() : requestBuilder.get();
    response.close();
    client.close();
    return Response.status(response.getStatus()).build();
}
 
Example #23
Source File: LoginResourceTest.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
public static Response processRequest(
    String url, String method, String payload, String authHeader) {
  Client client = ClientBuilder.newClient();
  WebTarget target = client.target(url);
  Builder builder = target.request();
  builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
  if (authHeader != null) {
    builder.header(HttpHeaders.AUTHORIZATION, authHeader);
  }
  return (payload != null)
      ? builder.build(method, Entity.json(payload)).invoke()
      : builder.build(method).invoke();
}
 
Example #24
Source File: NotificationTest.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
public Response processRequest(String url, String method, String payload)
    throws GeneralSecurityException, IOException {
  Client client = ClientBuilder.newClient();
  WebTarget target = client.target(url);
  Builder builder = target.request();
  builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
  builder.header(
      HttpHeaders.AUTHORIZATION,
      "Bearer "
          + new JWTVerifier()
              .createJWT("fred", new HashSet<String>(Arrays.asList("orchestrator"))));
  return (payload != null)
      ? builder.build(method, Entity.json(payload)).invoke()
      : builder.build(method).invoke();
}
 
Example #25
Source File: NetworkNodeRoleDimensionResourceTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
private Builder getNodeRoleDimensionTarget(String network, String dimension) {
  return target(CoordConsts.SVC_CFG_WORK_MGR2)
      .path(CoordConstsV2.RSC_NETWORKS)
      .path(network)
      .path(CoordConstsV2.RSC_NODE_ROLES)
      .path(dimension)
      .request()
      .header(CoordConstsV2.HTTP_HEADER_BATFISH_APIKEY, CoordConsts.DEFAULT_API_KEY)
      .header(CoordConstsV2.HTTP_HEADER_BATFISH_VERSION, BatfishVersion.getVersionStatic());
}
 
Example #26
Source File: AuthResourceTest.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
public static Response processRequest(
    String url, String method, String payload, String authHeader) {
  Client client = ClientBuilder.newClient();
  WebTarget target = client.target(url);
  Builder builder = target.request();
  if (payload != null) {
    builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
  }
  if (authHeader != null) {
    builder.header(HttpHeaders.AUTHORIZATION, authHeader);
  }
  return (payload != null)
      ? builder.build(method, Entity.json(payload)).invoke()
      : builder.build(method).invoke();
}
 
Example #27
Source File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Register a client with Token Endpoint Auth Method
 * <code>client_secret_basic</code>.
 */
@Parameters({"registerPath", "redirectUris"})
@Test
public void tokenEndpointAuthMethodClientSecretBasicStep1(final String registerPath, final String redirectUris)
        throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

    String registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());

    Response response = request.post(Entity.json(registerRequestContent));
    String entity = response.readEntity(String.class);

    showResponse("tokenEndpointAuthMethodClientSecretBasicStep1", response, entity);

    assertEquals(response.getStatus(), 200, "Unexpected response code. " + entity);
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has(RegisterResponseParam.CLIENT_ID.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET.toString()));
        assertTrue(jsonObj.has(RegisterResponseParam.REGISTRATION_ACCESS_TOKEN.toString()));
        assertTrue(jsonObj.has(REGISTRATION_CLIENT_URI.toString()));
        assertTrue(jsonObj.has(CLIENT_ID_ISSUED_AT.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET_EXPIRES_AT.toString()));

        clientId2 = jsonObj.getString(RegisterResponseParam.CLIENT_ID.toString());
        clientSecret2 = jsonObj.getString(RegisterResponseParam.CLIENT_SECRET.toString());
        registrationAccessToken2 = jsonObj.getString(RegisterResponseParam.REGISTRATION_ACCESS_TOKEN.toString());
        registrationClientUri2 = jsonObj.getString(RegisterResponseParam.REGISTRATION_CLIENT_URI.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example #28
Source File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Register a client with Token Endpoint Auth Method
 * <code>private_key_jwt</code>.
 */
@Parameters({"registerPath", "redirectUris", "clientJwksUri"})
@Test
public void tokenEndpointAuthMethodPrivateKeyJwtStep1(final String registerPath, final String redirectUris,
                                                      final String jwksUri) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    registerRequest.setJwksUri(jwksUri);
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

    String registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());

    Response response = request.post(Entity.json(registerRequestContent));
    String entity = response.readEntity(String.class);

    showResponse("tokenEndpointAuthMethodPrivateKeyJwtStep1", response, entity);

    assertEquals(response.getStatus(), 200, "Unexpected response code. " + entity);
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has(RegisterResponseParam.CLIENT_ID.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET.toString()));
        assertTrue(jsonObj.has(RegisterResponseParam.REGISTRATION_ACCESS_TOKEN.toString()));
        assertTrue(jsonObj.has(REGISTRATION_CLIENT_URI.toString()));
        assertTrue(jsonObj.has(CLIENT_ID_ISSUED_AT.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET_EXPIRES_AT.toString()));

        clientId5 = jsonObj.getString(RegisterResponseParam.CLIENT_ID.toString());
        clientSecret5 = jsonObj.getString(RegisterResponseParam.CLIENT_SECRET.toString());
        registrationAccessToken5 = jsonObj.getString(RegisterResponseParam.REGISTRATION_ACCESS_TOKEN.toString());
        registrationClientUri5 = jsonObj.getString(RegisterResponseParam.REGISTRATION_CLIENT_URI.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example #29
Source File: SnapshotResourceTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
private Builder getTopologyTarget(String network, String snapshot) {
  return target(CoordConsts.SVC_CFG_WORK_MGR2)
      .path(CoordConstsV2.RSC_NETWORKS)
      .path(network)
      .path(CoordConstsV2.RSC_SNAPSHOTS)
      .path(snapshot)
      .path(CoordConstsV2.RSC_TOPOLOGY)
      .request()
      .header(CoordConstsV2.HTTP_HEADER_BATFISH_APIKEY, CoordConsts.DEFAULT_API_KEY)
      .header(CoordConstsV2.HTTP_HEADER_BATFISH_VERSION, BatfishVersion.getVersionStatic());
}
 
Example #30
Source File: AzureInteractiveLogin.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Response getDeviceCode() {
    Client client = ClientBuilder.newClient();
    WebTarget resource = client.target("https://login.microsoftonline.com/common/oauth2");

    Form form = new Form();
    form.param("client_id", XPLAT_CLI_CLIENT_ID);
    form.param("resource", MANAGEMENT_CORE_WINDOWS);
    form.param("mkt", "en-us");

    Builder request = resource.path("devicecode").queryParam("api-version", "1.0").request();
    request.accept(MediaType.APPLICATION_JSON);
    return request.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
}