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

The following examples show how to use javax.ws.rs.client.Invocation.Builder. These examples are extracted from open source projects. 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: FHIR   Source File: FHIRClientImpl.java    License: 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 2
Source Project: jcypher   Source File: RTransactionImpl.java    License: 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 3
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 Project: FHIR   Source File: FHIRClientImpl.java    License: 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 5
Source Project: oxAuth   Source File: EndSessionRestWebServiceEmbeddedTest.java    License: 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 6
/**
 * 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 7
Source Project: mycore   Source File: MCRWorksPublisher.java    License: 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 8
Source Project: oxAuth   Source File: UserInfoRestWebServiceEmbeddedTest.java    License: 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 9
Source Project: OpenIoE   Source File: GETServiceBean.java    License: 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 10
Source Project: oxAuth   Source File: JwkRestWebServiceEmbeddedTest.java    License: 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 11
Source Project: FHIR   Source File: FHIRClientImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FHIRResponse search(String resourceType, FHIRParameters parameters, FHIRRequestHeader... headers) throws Exception {
    if (resourceType == null) {
        throw new IllegalArgumentException("The 'resourceType' argument is required but was null.");
    }
    WebTarget endpoint = getWebTarget();
    endpoint = endpoint.path(resourceType);
    endpoint = addParametersToWebTarget(endpoint, parameters);
    Invocation.Builder builder = endpoint.request(getDefaultMimeType());
    builder = addRequestHeaders(builder, headers);
    Response response = builder.get();
    return new FHIRResponseImpl(response);
}
 
Example 12
Source Project: FHIR   Source File: FHIRClientImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FHIRResponse _search(String resourceType, FHIRParameters parameters, FHIRRequestHeader... headers) throws Exception {
    if (resourceType == null) {
        throw new IllegalArgumentException("The 'resourceType' argument is required but was null.");
    }
    WebTarget endpoint = getWebTarget();
    endpoint = endpoint.path(resourceType).path("_search");
    Form form = buildForm(parameters);
    Entity<Form> entity = Entity.form(form);
    Invocation.Builder builder = endpoint.request(getDefaultMimeType());
    builder = addRequestHeaders(builder, headers);
    Response response = builder.post(entity);
    return new FHIRResponseImpl(response);
}
 
Example 13
Source Project: jcypher   Source File: RemoteDBAccess.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized Invocation.Builder getInvocationBuilder() {
	if (this.invocationBuilder == null) {
		this.invocationBuilder = getTransactionalTarget().request(MediaType.APPLICATION_JSON_TYPE);
		if (this.auth != null)
			this.invocationBuilder = this.invocationBuilder.header(authHeader, this.auth);
	}
	return this.invocationBuilder;
}
 
Example 14
Source Project: oxAuth   Source File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    License: 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 15
Source Project: oxAuth   Source File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    License: 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 16
Source Project: FHIR   Source File: FHIRClientImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FHIRResponse invoke(String resourceType, String operationName, Resource resource, 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.");
    }
    WebTarget endpoint = getWebTarget();
    Entity<Parameters> entity = Entity.entity((Parameters)resource, getDefaultMimeType());
    Invocation.Builder builder = endpoint.path(resourceType).path(operationName).request();
    builder = addRequestHeaders(builder, headers);
    Response response = builder.post(entity);
    return new FHIRResponseImpl(response);
}
 
Example 17
Source Project: batfish   Source File: SnapshotNodeRolesResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
private Builder getNodeRolesTarget(String network, String snapshot, boolean inferred) {
  return target(CoordConsts.SVC_CFG_WORK_MGR2)
      .path(CoordConstsV2.RSC_NETWORKS)
      .path(network)
      .path(CoordConstsV2.RSC_SNAPSHOTS)
      .path(snapshot)
      .path(inferred ? CoordConstsV2.RSC_INFERRED_NODE_ROLES : CoordConstsV2.RSC_NODE_ROLES)
      .request()
      .header(CoordConstsV2.HTTP_HEADER_BATFISH_APIKEY, CoordConsts.DEFAULT_API_KEY)
      .header(CoordConstsV2.HTTP_HEADER_BATFISH_VERSION, BatfishVersion.getVersionStatic());
}
 
Example 18
Source Project: oxAuth   Source File: ResponseTypesRestrictionEmbeddedTest.java    License: MIT License 5 votes vote down vote up
/**
 * Authorization request with the other Response types combination should
 * fail.
 */
@Test(dependsOnMethods = "omittedResponseTypesStep3b", dataProvider = "omittedResponseTypesStep4DataProvider")
public void omittedResponseTypesStep4(final String authorizePath, final String userId, final String userSecret,
                                      final String redirectUri, final List<ResponseType> responseTypes) throws Exception {
    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("af0ifjsldkj");
    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("omittedResponseTypesStep4", response, entity);

    if (response.getStatus() == 400) {
        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);
        }
    } else {
        fail("Unexpected response code: " + response.getStatus());
    }
}
 
Example 19
Source Project: boost   Source File: TestUtils.java    License: 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 20
Source Project: cloudbreak   Source File: PrincipalCreator.java    License: Apache License 2.0 5 votes vote down vote up
private void checkTheExistenceOnGraph(String accessToken, String objectId, String tenantId, Client client) {
    WebTarget resource = client.target(GRAPH_WINDOWS + tenantId);
    Builder request = resource.path("servicePrincipals/" + objectId).queryParam("api-version", GRAPH_API_VERSION).request();
    request.accept(MediaType.APPLICATION_JSON);
    request.header("Authorization", "Bearer " + accessToken);
    try (Response response = request.get()) {
        if (response.getStatus() != HttpStatus.SC_OK) {
            throw new RetryException("Principal with objectId (" + objectId + ") hasn't been created yet");
        }
    }
}
 
Example 21
Source Project: cxf   Source File: InvocationBuilderImpl.java    License: 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 22
/**
 * 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 23
Source Project: hermes   Source File: SchemaRegisterResourceTest.java    License: 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 24
Source Project: hermes   Source File: SchemaRegisterResourceTest.java    License: 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 25
Source Project: oxAuth   Source File: ApplicationTypeRestrictionEmbeddedTest.java    License: 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 26
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 27
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 28
Source Project: sample-acmegifts   Source File: NotificationTest.java    License: 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 29
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 30
Source Project: sample-acmegifts   Source File: AuthResourceTest.java    License: 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();
}