Java Code Examples for javax.ws.rs.core.Form#param()

The following examples show how to use javax.ws.rs.core.Form#param() . 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: EtcdV2ProxyImpl.java    From etcd-viewer with Apache License 2.0 6 votes vote down vote up
protected EtcdResponse saveOrUpdateNode(EtcdNode node, Boolean update) {
    if (node.isDir() && update && node.getTtl() == null) {
        LOG.warn("Remove directory TTL is not supported by etcd version 0.4.9");
    }
    Form form = new Form();
    if (node.isDir()) {
        form.param("dir", Boolean.TRUE.toString());
    } else {
        form.param("value", node.getValue());
    }
    if (update) {
        form.param("ttl", node.getTtl() == null ? "" : node.getTtl().toString());
    } else if (node.getTtl() != null) {
        form.param("ttl", node.getTtl().toString());
    }
    // we include prevExist parameter within all requests for safety
    form.param("prevExist", update.toString());

    Invocation invocation = getWebTarget()
            .path("/v2/keys/{key}")
            .resolveTemplate("key", normalizeKey(node.getKey()), false)
            .request(MediaType.APPLICATION_JSON)
            .buildPut(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED));

    return new ExceptionHandlingProcessor<>(EtcdResponse.class).process(invocation);
}
 
Example 2
Source File: CKANCreationClient.java    From aliada-tool with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Implementation of a CKAN Datahub Page Creation REST service client application.
 * POST /ckan-datahub/jobs/
 *
 * @param jobid the job identifier.
 * @since 2.0
 */
public void newJob(final int jobid) {
	//Convert integer to string
	final String s_jobid = "" + jobid;
	final Client client = ClientBuilder.newClient();
	final WebTarget webTarget = client.target(ALIADA_CKANCREATION_URL);

	//Data to be sent via HTTP POST
	final Form form = new Form();
	form.param("jobid", s_jobid);

	//POST (Response in XML format)
	final String acceptType = MediaType.APPLICATION_XML; //If we want the response in XML format
	final Response postResponse = webTarget.path("/jobs").request(acceptType).post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
	LOGGER.info("status =" + postResponse.getStatus());
	LOGGER.info("response data=" + postResponse.readEntity(String.class));
}
 
Example 3
Source File: LinksDiscoveryClient.java    From aliada-tool with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Implementation of a Links Discovery REST service client application.
 * POST /links-discovery/jobs/
 *
 * @param jobid the job identifier.
 * @since 1.0
 */
public void newJob(final int jobid) {
	//Convert integer to string
	final String s_jobid = "" + jobid;
	final Client client = ClientBuilder.newClient();
	final WebTarget webTarget = client.target(ALIADA_LINKSDISCOVERYSERVICE_URL);

	//Data to be sent via HTTP POST
	final Form form = new Form();
	form.param("jobid", s_jobid);

	//POST (Response in XML format)
	final String acceptType = MediaType.APPLICATION_XML; //If we want the response in XML format
	final Response postResponse = webTarget.path("/jobs").request(acceptType).post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
	LOGGER.info("status =" + postResponse.getStatus());
	LOGGER.info("response data=" + postResponse.readEntity(String.class));
}
 
Example 4
Source File: AuthorizationGrantTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testPasswordsCredentialsGrant() throws Exception {
    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "consumer-id", "this-is-a-secret", null);

    // Get Access Token
    client.type("application/x-www-form-urlencoded").accept("application/json");
    client.path("token");

    Form form = new Form();
    form.param("grant_type", "password");
    form.param("username", "alice");
    form.param("password", "security");

    ClientAccessToken accessToken = client.post(form, ClientAccessToken.class);
    assertNotNull(accessToken.getTokenKey());
    assertNotNull(accessToken.getRefreshToken());

    if (isAccessTokenInJWTFormat()) {
        validateAccessToken(accessToken.getTokenKey());
    }
}
 
Example 5
Source File: AbstractTest.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Test
public void directInjectManagerAuth() {
    Form form = new Form();
    form.param("username", "foo");
    form.param("password", "foo");
    final String ok = container.getTarget("/directInjectManager").request()
            .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
    assertThat(ok).isEqualTo("ok");
}
 
Example 6
Source File: AbstractTest.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Test
public void containerSpecificSecurityContext() {
    Form form = new Form();
    form.param("username", "foo");
    form.param("password", "foo");
    final String ok = container.getTarget("/containerSpecific/securitycontext").request()
            .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
    assertThat(ok).isEqualTo("ok");
}
 
Example 7
Source File: AbstractTest.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Test
public void classLevelDirectFail() {
    Form form = new Form();
    form.param("username", "foo");
    form.param("password", "bar");
    final Response direct = container.getTarget("/class/direct").request()
            .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
    assertThat(direct.getStatus()).isEqualTo(401);
}
 
Example 8
Source File: AbstractTest.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Test
public void containerSpecificContext() {
    Form form = new Form();
    form.param("username", "foo");
    form.param("password", "foo");
    final String ok = container.getTarget("/containerSpecific/context").request()
            .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
    assertThat(ok).isEqualTo("ok");
}
 
Example 9
Source File: ReportClientV5.java    From nessus-java-client with GNU Affero General Public License v3.0 5 votes vote down vote up
public List<Host> getHostsFromReport(String uuid) {
	WebTarget reportTarget = target.path("/report/hosts");
	Form form = prepopulateForm();
	form.param("report", uuid);
	NessusReply reply = sendRequestAndCheckError(reportTarget, form);
	return reply.getContents().getHost();
}
 
Example 10
Source File: AuthorizationGrantTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testImplicitGrant() throws Exception {
    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", null);
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Access Token
    client.type("application/json").accept("application/json");
    client.query("client_id", "consumer-id");
    client.query("redirect_uri", "http://www.blah.apache.org");
    client.query("response_type", "token");
    client.path("authorize-implicit/");

    OAuthAuthorizationData authzData = client.get(OAuthAuthorizationData.class);

    // Now call "decision" to get the access token
    client.path("decision");
    client.type("application/x-www-form-urlencoded");

    Form form = new Form();
    form.param("session_authenticity_token", authzData.getAuthenticityToken());
    form.param("client_id", authzData.getClientId());
    form.param("redirect_uri", authzData.getRedirectUri());
    form.param("oauthDecision", "allow");

    Response response = client.post(form);

    String location = response.getHeaderString("Location");
    String accessToken = OAuth2TestUtils.getSubstring(location, "access_token");
    assertNotNull(accessToken);

    if (isAccessTokenInJWTFormat()) {
        validateAccessToken(accessToken);
    }
}
 
Example 11
Source File: OOBResponseProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void writeTo(OOBAuthorizationResponse obj, Class<?> c, Type t,
                    Annotation[] anns,
                    MediaType mt, MultivaluedMap<String, Object> headers, OutputStream os)
    throws IOException, WebApplicationException {

    Form form = new Form(new MetadataMap<String, String>());
    form.param(OAuth.OAUTH_VERIFIER, obj.getVerifier());
    form.param(OAuth.OAUTH_TOKEN, obj.getRequestToken());
    if (obj.getState() != null) {
        form.param(OAuthConstants.X_OAUTH_STATE, obj.getState());
    }
    formProvider.writeTo(form, Form.class, Form.class, anns, mt, headers, os);
}
 
Example 12
Source File: AuthorizationGrantTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthorizationCodeGrantPOST() throws Exception {
    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", null);
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Make initial authorization request
    client.type("application/x-www-form-urlencoded");

    client.path("authorize/");

    Form form = new Form();
    form.param("client_id", "consumer-id");
    form.param("redirect_uri", "http://www.blah.apache.org");
    form.param("response_type", "code");

    OAuthAuthorizationData authzData = client.post(form, OAuthAuthorizationData.class);
    String location = OAuth2TestUtils.getLocation(client, authzData, null);
    String code =  OAuth2TestUtils.getSubstring(location, "code");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, "consumer-id", "this-is-a-secret", null);

    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
    assertNotNull(accessToken.getTokenKey());

    if (isAccessTokenInJWTFormat()) {
        validateAccessToken(accessToken.getTokenKey());
    }
}
 
Example 13
Source File: AbstractTest.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Test
public void proxiedClassLevelDirectFail() {
    Form form = new Form();
    form.param("username", "foo");
    form.param("password", "bar");
    final Response direct = container.getTarget("/proxied/class/direct").request()
            .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
    assertThat(direct.getStatus()).isEqualTo(401);
}
 
Example 14
Source File: SessionClientV5.java    From nessus-java-client with GNU Affero General Public License v3.0 5 votes vote down vote up
public void login(String username, String password) throws LoginException {
	WebTarget loginTarget = target.path("/login");
	Form form = new Form();
	form.param("login", username);
	form.param("password", password);
	form.param("seq", generateSeqNum());
	NessusReply reply = loginTarget.request(MediaType.APPLICATION_XML_TYPE).post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), NessusReply.class);
	if(!"OK".equalsIgnoreCase(reply.getStatus()))
		throw new LoginException("Error logging in");
	token = reply.getContents().getToken();
	log.info("Login OK.  Token: " + token);
}
 
Example 15
Source File: AbstractTest.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Test
public void directInjectSkipOk() {
    Form form = new Form();
    form.param("username", "foo");
    form.param("password", "foo");
    final String ok = container.getTarget("/directInjectSkip").request()
            .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
    assertThat(ok).isEqualTo("ok");
}
 
Example 16
Source File: AuthorizationGrantNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSAMLHolderOfKey() throws Exception {
    URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());

    // Create the SAML Assertion
    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
    samlCallbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
    samlCallbackHandler.setAudience(address + "token");

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);

    SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
    samlAssertion.signAssertion(
        samlCallback.getIssuerKeyName(),
        samlCallback.getIssuerKeyPassword(),
        samlCallback.getIssuerCrypto(),
        samlCallback.isSendKeyValue(),
        samlCallback.getCanonicalizationAlgorithm(),
        samlCallback.getSignatureAlgorithm()
    );
    String assertion = samlAssertion.assertionToString();

    // Get Access Token
    client.type("application/x-www-form-urlencoded").accept("application/json");
    client.path("token");

    Form form = new Form();
    form.param("grant_type", "urn:ietf:params:oauth:grant-type:saml2-bearer");
    form.param("assertion", Base64UrlUtility.encode(assertion));
    form.param("client_id", "consumer-id");

    try {
        Response response = client.post(form);
        response.readEntity(ClientAccessToken.class);
        fail("Failure expected on an incorrect subject confirmation method");
    } catch (Exception ex) {
        // expected
    }
}
 
Example 17
Source File: SessionClientV5.java    From nessus-java-client with GNU Affero General Public License v3.0 4 votes vote down vote up
protected Form prepopulateForm() {
	Form form = new Form();
	form.param("seq", generateSeqNum());
	form.param("token", token);
	return form;
}
 
Example 18
Source File: OIDCNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testUserInfoRefreshToken() throws Exception {
    URL busFile = UserInfoTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client, "openid");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
    assertNotNull(accessToken.getTokenKey());
    String oldAccessToken = accessToken.getTokenKey();
    assertTrue(accessToken.getApprovedScope().contains("openid"));

    String idToken = accessToken.getParameters().get("id_token");
    assertNotNull(idToken);

    // Refresh the access token
    client.type("application/x-www-form-urlencoded").accept("application/json");

    Form form = new Form();
    form.param("grant_type", "refresh_token");
    form.param("refresh_token", accessToken.getRefreshToken());
    form.param("client_id", "consumer-id");
    form.param("scope", "openid");
    Response response = client.post(form);

    accessToken = response.readEntity(ClientAccessToken.class);
    assertNotNull(accessToken.getTokenKey());
    assertNotNull(accessToken.getRefreshToken());
    accessToken.getParameters().get("id_token");
    assertNotNull(idToken);
    String newAccessToken = accessToken.getTokenKey();

    // Now test the UserInfoService.

    // The old Access Token should fail
    String userInfoAddress = "https://localhost:" + port + "/ui/plain/userinfo";
    WebClient userInfoClient = WebClient.create(userInfoAddress, OAuth2TestUtils.setupProviders(),
                                                busFile.toString());
    userInfoClient.accept("application/json");
    userInfoClient.header("Authorization", "Bearer " + oldAccessToken);

    Response serviceResponse = userInfoClient.get();
    assertEquals(serviceResponse.getStatus(), 401);

    // The refreshed Access Token should work
    userInfoClient.replaceHeader("Authorization", "Bearer " + newAccessToken);
    serviceResponse = userInfoClient.get();
    assertEquals(serviceResponse.getStatus(), 200);

    UserInfo userInfo = serviceResponse.readEntity(UserInfo.class);
    assertNotNull(userInfo);

    assertEquals("alice", userInfo.getSubject());
    assertEquals("consumer-id", userInfo.getAudience());
}
 
Example 19
Source File: AuthorizationGrantNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testRepeatAuthorizationCode() throws Exception {
    URL busFile = AuthorizationGrantTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client);
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    client.type("application/x-www-form-urlencoded").accept("application/json");
    client.path("token");

    // First invocation
    Form form = new Form();
    form.param("grant_type", "authorization_code");
    form.param("code", code);
    form.param("client_id", "consumer-id");
    Response response = client.post(form);
    ClientAccessToken token = response.readEntity(ClientAccessToken.class);
    assertNotNull(token.getTokenKey());

    // Now try to get a second token
    response = client.post(form);
    try {
        response.readEntity(ClientAccessToken.class);
        fail("Failure expected on trying to get a second access token");
    } catch (ResponseProcessingException ex) {
        //expected
    }
}
 
Example 20
Source File: OIDCFlowTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testAuthorizationCodeFlowPOST() throws Exception {
    URL busFile = OIDCFlowTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());

    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Make initial authorization request
    client.type("application/x-www-form-urlencoded");

    client.path("authorize/");

    Form form = new Form();
    form.param("client_id", "consumer-id");
    form.param("scope", "openid");
    form.param("redirect_uri", "http://www.blah.apache.org");
    form.param("response_type", "code");
    Response response = client.post(form);

    OAuthAuthorizationData authzData = response.readEntity(OAuthAuthorizationData.class);
    String location = OAuth2TestUtils.getLocation(client, authzData, null);
    String code =  OAuth2TestUtils.getSubstring(location, "code");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, "consumer-id", "this-is-a-secret", busFile.toString());

    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
    assertNotNull(accessToken.getTokenKey());
    assertTrue(accessToken.getApprovedScope().contains("openid"));

    String idToken = accessToken.getParameters().get("id_token");
    assertNotNull(idToken);
    validateIdToken(idToken, null);

    if (isAccessTokenInJWTFormat()) {
        validateAccessToken(accessToken.getTokenKey());
    }
}