Java Code Examples for javax.ws.rs.core.Form
The following examples show how to use
javax.ws.rs.core.Form. 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: cxf Source File: AuthorizationGrantTest.java License: Apache License 2.0 | 6 votes |
@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 2
Source Project: peer-os Source File: RegistrationManager.java License: Apache License 2.0 | 6 votes |
private void registerPeerPubKey() throws BazaarManagerException { log.info( "Registering peer public key with Bazaar..." ); Form form = new Form( "keytext", readKeyText( configManager.getPeerPublicKey() ) ); RestResult<Object> restResult = restClient.postPlain( "/pks/add", form ); if ( !restResult.isSuccess() ) { throw new BazaarManagerException( "Error registering peer public key with Bazaar: " + restResult.getError() ); } log.info( "Public key successfully registered" ); }
Example 3
Source Project: openmeetings Source File: TestCalendarService.java License: Apache License 2.0 | 6 votes |
@Test public void testCreateWithGuests() throws Exception { String sid = loginNewUser(); AppointmentDTO dto = createEventWithGuests(sid); //try to change MM list JSONObject o1 = AppointmentParamConverter.json(dto) .put("meetingMembers", new JSONArray() .put(new JSONObject().put("user", new JSONObject() .put("id", 1)))); Response resp = getClient(getCalendarUrl()) .path("/") .query("sid", sid) .form(new Form().param("appointment", o1.toString())); assertNotNull(resp, "Valid AppointmentDTO should be returned"); assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus(), "Call should be successful"); dto = resp.readEntity(AppointmentDTO.class); assertNotNull(dto, "Valid DTO should be returned"); assertNotNull(dto.getId(), "DTO id should be valid"); assertEquals(1, dto.getMeetingMembers().size(), "DTO should have 1 attendees"); }
Example 4
Source Project: gitlab4j-api Source File: RepositoryFileApi.java License: MIT License | 6 votes |
/** * Gets the query params based on the API version. * * @param file the RepositoryFile instance with the info for the query params * @param branchName the branch name * @param commitMessage the commit message * @return a Form instance with the correct query params. */ protected Form createForm(RepositoryFile file, String branchName, String commitMessage) { Form form = new Form(); if (isApiVersion(ApiVersion.V3)) { addFormParam(form, "file_path", file.getFilePath(), true); addFormParam(form, "branch_name", branchName, true); } else { addFormParam(form, "branch", branchName, true); } addFormParam(form, "encoding", file.getEncoding(), false); // Cannot use addFormParam() as it does not accept an empty or whitespace only string String content = file.getContent(); if (content == null) { throw new IllegalArgumentException("content cannot be null"); } form.param("content", content); addFormParam(form, "commit_message", commitMessage, true); return (form); }
Example 5
Source Project: choerodon-starters Source File: GroupApi.java License: Apache License 2.0 | 6 votes |
/** * Creates a new project group. Available only for users who can create groups. * <p> * PUT /groups * * @param groupId the ID of the group to update * @param name the name of the group to add * @param path the path for the group * @param description (optional) - The group's description * @param membershipLock (optional, boolean) - Prevent adding new members to project membership within this group * @param shareWithGroupLock (optional, boolean) - Prevent sharing a project with another group within this group * @param visibility (optional) - The group's visibility. Can be private, internal, or public. * @param lfsEnabled (optional) - Enable/disable Large File Storage (LFS) for the projects in this group * @param requestAccessEnabled (optional) - Allow users to request member access. * @param parentId (optional) - The parent group id for creating nested group. * @param sharedRunnersMinutesLimit (optional) - (admin-only) Pipeline minutes quota for this group * @return the updated Group instance * @throws GitLabApiException if any exception occurs */ public Group updateGroup(Integer groupId, String name, String path, String description, Boolean membershipLock, Boolean shareWithGroupLock, Visibility visibility, Boolean lfsEnabled, Boolean requestAccessEnabled, Integer parentId, Integer sharedRunnersMinutesLimit) throws GitLabApiException { Form formData = new GitLabApiForm() .withParam("name", name) .withParam("path", path) .withParam("description", description) .withParam("membership_lock", membershipLock) .withParam("share_with_group_lock", shareWithGroupLock) .withParam("visibility", visibility) .withParam("lfs_enabled", lfsEnabled) .withParam("request_access_enabled", requestAccessEnabled) .withParam("parent_id", parentId) .withParam("shared_runners_minutes_limit", sharedRunnersMinutesLimit); Response response = put(Response.Status.OK, formData.asMap(), "groups", groupId); return (response.readEntity(Group.class)); }
Example 6
Source Project: krazo Source File: DefaultFormEntityProviderTest.java License: Apache License 2.0 | 6 votes |
@Test public void testWithNonBufferedStream() throws IOException { // A file input stream does not support reset // So let's write some content to a temp file and feed it to the form provider File temp = File.createTempFile("tempfile", ".tmp"); try (FileWriter fileWriter = new FileWriter(temp)) { fileWriter.write("foo=bar"); } EasyMock.expect(context.getEntityStream()).andReturn(new FileInputStream(temp)); EasyMock.expect(context.getMediaType()).andReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE); context.setEntityStream(EasyMock.anyObject(InputStream.class)); EasyMock.replay(context); Form form = underTest.getForm(context); assertEquals("bar", form.asMap().get("foo").get(0)); }
Example 7
Source Project: cloudbreak Source File: SaltConnector.java License: Apache License 2.0 | 6 votes |
@Measure(SaltConnector.class) public <T> T wheel(String fun, Collection<String> match, Class<T> clazz) { Form form = new Form(); form = addAuth(form) .param("fun", fun) .param("client", "wheel"); if (match != null && !match.isEmpty()) { form.param("match", String.join(",", match)); } Response response = saltTarget.path(SaltEndpoint.SALT_RUN.getContextPath()).request() .header(SIGN_HEADER, PkiUtil.generateSignature(signatureKey, toJson(form.asMap()).getBytes())) .post(Entity.form(form)); T responseEntity = JaxRSUtil.response(response, clazz); LOGGER.debug("Salt wheel has been executed. fun: {}", fun); return responseEntity; }
Example 8
Source Project: openwebbeans-meecrowave Source File: OAuth2Test.java License: Apache License 2.0 | 6 votes |
@Test public void getPasswordTokenNoClient() { final Client client = ClientBuilder.newClient().register(new OAuthJSONProvider()); try { final ClientAccessToken token = client.target("http://localhost:" + MEECROWAVE.getConfiguration().getHttpPort()) .path("oauth2/token") .request(APPLICATION_JSON_TYPE) .post(entity( new Form() .param("grant_type", "password") .param("username", "test") .param("password", "pwd"), APPLICATION_FORM_URLENCODED_TYPE), ClientAccessToken.class); assertNotNull(token); assertEquals("Bearer", token.getTokenType()); assertNotNull(token.getTokenKey()); assertIsJwt(token.getTokenKey(), "__default"); assertEquals(3600, token.getExpiresIn()); assertNotEquals(0, token.getIssuedAt()); assertNotNull(token.getRefreshToken()); validateJwt(token); } finally { client.close(); } }
Example 9
Source Project: cxf Source File: OAuthRequestFilter.java License: Apache License 2.0 | 6 votes |
protected String getTokenFromFormData(Message message) { String method = (String)message.get(Message.HTTP_REQUEST_METHOD); String type = (String)message.get(Message.CONTENT_TYPE); if (type != null && MediaType.APPLICATION_FORM_URLENCODED.startsWith(type) && method != null && (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT))) { try { FormEncodingProvider<Form> provider = new FormEncodingProvider<>(true); Form form = FormUtils.readForm(provider, message); MultivaluedMap<String, String> formData = form.asMap(); String token = formData.getFirst(OAuthConstants.ACCESS_TOKEN); if (token != null) { FormUtils.restoreForm(provider, form, message); return token; } } catch (Exception ex) { // the exception will be thrown below } } AuthorizationUtils.throwAuthorizationFailure(supportedSchemes, realm); return null; }
Example 10
Source Project: choerodon-starters Source File: MergeRequestApi.java License: Apache License 2.0 | 6 votes |
/** * Merge changes to the merge request. If the MR has any conflicts and can not be merged, * you'll get a 405 and the error message 'Branch cannot be merged'. If merge request is * already merged or closed, you'll get a 406 and the error message 'Method Not Allowed'. * If the sha parameter is passed and does not match the HEAD of the source, you'll get * a 409 and the error message 'SHA does not match HEAD of source branch'. If you don't * have permissions to accept this merge request, you'll get a 401. * <p> * PUT /projects/:id/merge_requests/:merge_request_iid/merge * * @param projectId the ID of a project * @param mergeRequestId the internal ID of the merge request * @param mergeCommitMessage, custom merge commit message, optional * @param shouldRemoveSourceBranch, if true removes the source branch, optional * @param mergeWhenPipelineSucceeds, if true the MR is merged when the pipeline, optional * @return the merged merge request * @throws GitLabApiException if any exception occurs */ public MergeRequest acceptMergeRequest(Integer projectId, Integer mergeRequestId, String mergeCommitMessage, Boolean shouldRemoveSourceBranch, Boolean mergeWhenPipelineSucceeds) throws GitLabApiException { if (projectId == null) { throw new GitLabApiException("projectId cannot be null"); } if (mergeRequestId == null) { throw new GitLabApiException("mergeRequestId cannot be null"); } Form formData = new GitLabApiForm() .withParam("merge_commit_message", mergeCommitMessage) .withParam("should_remove_source_branch", shouldRemoveSourceBranch) .withParam("merge_when_pipeline_succeeds", mergeWhenPipelineSucceeds); Response response = put(Response.Status.OK, formData.asMap(), "projects", projectId, "merge_requests", mergeRequestId, "merge"); return (response.readEntity(MergeRequest.class)); }
Example 11
Source Project: thorntail Source File: KeycloakMicroprofileJwtWithoutJsonTest.java License: Apache License 2.0 | 6 votes |
@Test @RunAsClient public void testResourceIsSecured() { String authResponse = ClientBuilder.newClient() .target("http://localhost:8080/auth/realms/thorntail-cmd-client/protocol/openid-connect/token") .request() .post(Entity.form(new Form() .param("grant_type", "password") .param("client_id", "thorntail-cmd-client-example") .param("username", "user1") .param("password", "password1") ), String.class); String accessToken = getAccessTokenFromResponse(authResponse); String serviceResponse = ClientBuilder.newClient() .target("http://localhost:8080/mpjwt/secured") .request() .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .get(String.class); Assert.assertEquals("Hi user1, this resource is secured", serviceResponse); }
Example 12
Source Project: dropwizard-pac4j Source File: EndToEndServletTest.java License: Apache License 2.0 | 6 votes |
@Test public void grantsAccessToResourcesForm() throws Exception { setup(ConfigOverride.config("pac4j.servlet.security[0].clients", DirectFormClient.class.getSimpleName())); // username == password Form form = new Form(); form.param("username", "rosebud"); form.param("password", "rosebud"); final String dogName = client.target(getUrlPrefix() + "/dogs/pierre") .request(MediaType.APPLICATION_JSON) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class); assertThat(dogName).isEqualTo("pierre"); }
Example 13
Source Project: sakai Source File: SakaiLoginLoginTest.java License: Educational Community License v2.0 | 6 votes |
@Test public void testLogin() { WebClient client = WebClient.create(getFullEndpointAddress()); addClientMocks(client); // client call client.accept("text/plain"); client.path("/" + getOperation()); Form form = new Form(); form.param("id", "admin").param("pw", "admin"); // client result String result = client.post(form, String.class); // test verifications assertNotNull(result); assertEquals(SESSION_ID, result); }
Example 14
Source Project: cxf Source File: AbstractCdiSingleAppTest.java License: Apache License 2.0 | 6 votes |
@Test public void testAddAndQueryOneBook() { final String id = UUID.randomUUID().toString(); Response r = createWebClient(getBasePath() + "/books").post( new Form() .param("id", id) .param("name", "Book 1234")); assertEquals(Response.Status.CREATED.getStatusCode(), r.getStatus()); r = createWebClient(getBasePath() + "/books").path(id).get(); assertEquals(Response.Status.OK.getStatusCode(), r.getStatus()); Book book = r.readEntity(Book.class); assertEquals(id, book.getId()); }
Example 15
Source Project: cxf Source File: SamlFormOutInterceptor.java License: Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") protected Form getRequestForm(Message message) { Object ct = message.get(Message.CONTENT_TYPE); if (ct == null || !MediaType.APPLICATION_FORM_URLENCODED.equalsIgnoreCase(ct.toString())) { return null; } MessageContentsList objs = MessageContentsList.getContentsList(message); if (objs != null && objs.size() == 1) { Object obj = objs.get(0); if (obj instanceof Form) { return (Form)obj; } else if (obj instanceof MultivaluedMap) { return new Form((MultivaluedMap<String, String>)obj); } } return null; }
Example 16
Source Project: peer-os Source File: CommandProcessor.java License: Apache License 2.0 | 6 votes |
void notifyAgent( ResourceHostInfo resourceHostInfo ) { WebClient webClient = null; javax.ws.rs.core.Response response = null; try { webClient = getWebClient( resourceHostInfo ); response = webClient.form( new Form() ); if ( response.getStatus() == javax.ws.rs.core.Response.Status.OK.getStatusCode() || response.getStatus() == javax.ws.rs.core.Response.Status.ACCEPTED.getStatusCode() ) { hostRegistry.updateResourceHostEntryTimestamp( resourceHostInfo.getId() ); } } finally { RestUtil.close( response, webClient ); } }
Example 17
Source Project: cxf Source File: AuthorizationGrantTest.java License: Apache License 2.0 | 6 votes |
@org.junit.Test public void testSAMLAuthorizationGrant() throws Exception { String address = "https://localhost:" + port + "/services/"; WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "consumer-id", "this-is-a-secret", null); // Create the SAML Assertion String assertion = OAuth2TestUtils.createToken(address + "token"); // 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"); ClientAccessToken accessToken = client.post(form, ClientAccessToken.class); assertNotNull(accessToken.getTokenKey()); assertNotNull(accessToken.getRefreshToken()); if (isAccessTokenInJWTFormat()) { validateAccessToken(accessToken.getTokenKey()); } }
Example 18
Source Project: cxf Source File: JAXRSClientServerValidationTest.java License: Apache License 2.0 | 5 votes |
@Test public void testThatResponseValidationForAllBooksFails() { Response r = createWebClient("/bookstore/books").post(new Form().param("id", "1234")); assertEquals(Status.CREATED.getStatusCode(), r.getStatus()); r = createWebClient("/bookstore/books").get(); assertEquals(Status.INTERNAL_SERVER_ERROR.getStatusCode(), r.getStatus()); }
Example 19
Source Project: gitlab4j-api Source File: UserApi.java License: MIT License | 5 votes |
/** * Blocks the specified user. Available only for admin. * * <pre><code>GitLab Endpoint: POST /users/:id/block</code></pre> * * @param userId the ID of the user to block * @throws GitLabApiException if any exception occurs */ public void blockUser(Integer userId) throws GitLabApiException { if (userId == null) { throw new RuntimeException("userId cannot be null"); } if (isApiVersion(ApiVersion.V3)) { put(Response.Status.CREATED, null, "users", userId, "block"); } else { post(Response.Status.CREATED, (Form) null, "users", userId, "block"); } }
Example 20
Source Project: cxf Source File: AuthorizationGrantTest.java License: Apache License 2.0 | 5 votes |
@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 21
Source Project: cxf Source File: FormResource.java License: Apache License 2.0 | 5 votes |
@POST public Response processForm(@FormParam("value") String value, Form form) { String fromForm = form.asMap().getFirst("value"); LOG.info("FromFormParam: " + value); LOG.info("FromForm: " + fromForm); return Response.ok() .header("FromFormParam", value) .header("FromForm", fromForm) .build(); }
Example 22
Source Project: cloudbreak Source File: AzureInteractiveLogin.java License: Apache License 2.0 | 5 votes |
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)); }
Example 23
Source Project: cxf Source File: Saml2BearerAuthHandler.java License: Apache License 2.0 | 5 votes |
private Form readFormData(Message message) { try { return FormUtils.readForm(provider, message); } catch (Exception ex) { throw ExceptionUtils.toNotAuthorizedException(null, null); } }
Example 24
Source Project: cxf Source File: AuthorizationGrantNegativeTest.java License: Apache License 2.0 | 5 votes |
@org.junit.Test public void testJWTNoIssuer() 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 JWT Token String token = OAuth2TestUtils.createToken(null, "consumer-id", "https://localhost:" + port + "/services/token", true, true); // 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:jwt-bearer"); form.param("assertion", token); form.param("client_id", "consumer-id"); Response response = client.post(form); try { response.readEntity(ClientAccessToken.class); fail("Failure expected on no issuer"); } catch (Exception ex) { // expected } }
Example 25
Source Project: krazo Source File: DefaultFormEntityProviderTest.java License: Apache License 2.0 | 5 votes |
@Test public void testReadingForm() throws IOException { EasyMock.expect(context.getEntityStream()).andReturn(new ByteArrayInputStream("foo=bar".getBytes())); EasyMock.expect(context.getMediaType()).andReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE); context.setEntityStream(EasyMock.anyObject(InputStream.class)); EasyMock.replay(context); Form form = underTest.getForm(context); assertEquals("bar", form.asMap().getFirst("foo")); }
Example 26
Source Project: krazo Source File: DefaultFormEntityProviderTest.java License: Apache License 2.0 | 5 votes |
@Test public void testMultipleParamValues() throws IOException { EasyMock.expect(context.getEntityStream()).andReturn(new ByteArrayInputStream("foo=bar&foo=baz".getBytes())); EasyMock.expect(context.getMediaType()).andReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE); context.setEntityStream(EasyMock.anyObject(InputStream.class)); EasyMock.replay(context); Form form = underTest.getForm(context); assertEquals("bar", form.asMap().get("foo").get(0)); assertEquals("baz", form.asMap().get("foo").get(1)); }
Example 27
Source Project: nessus-java-client Source File: SessionClientV6.java License: GNU Affero General Public License v3.0 | 5 votes |
public void login(String username, String password) throws LoginException { WebTarget loginTarget = target.path("/session"); Form form = new Form(); form.param("username", username); form.param("password", password); Login reply = loginTarget.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Login.class); token = reply.getToken(); if(token == null || token.length() == 0) throw new LoginException("Error logging in"); authHeader = COOKIE_HEADER; authParam = "token=" + token; log.info("Login OK. Token: " + token); }
Example 28
Source Project: samza Source File: TestJobsResource.java License: Apache License 2.0 | 5 votes |
@Test public void testPutMissingStatus() throws IOException { Response resp = target(String.format("v1/jobs/%s/%s", MockJobProxy.JOB_INSTANCE_2_NAME, MockJobProxy.JOB_INSTANCE_2_ID)).request() .put(Entity.form(new Form())); assertEquals(400, resp.getStatus()); final Map<String, String> errorMessage = objectMapper.readValue(resp.readEntity(String.class), new TypeReference<Map<String, String>>() { }); assertTrue(errorMessage.get("message").contains("status")); resp.close(); }
Example 29
Source Project: samza Source File: TestJobsResource.java License: Apache License 2.0 | 5 votes |
@Test public void testStartJob() throws IOException { Response resp = target(String.format("v1/jobs/%s/%s", MockJobProxy.JOB_INSTANCE_2_NAME, MockJobProxy.JOB_INSTANCE_2_ID)) .queryParam("status", "started").request().put(Entity.form(new Form())); assertEquals(202, resp.getStatus()); final Job job2 = objectMapper.readValue(resp.readEntity(String.class), Job.class); assertEquals(MockJobProxy.JOB_INSTANCE_2_NAME, job2.getJobName()); assertEquals(MockJobProxy.JOB_INSTANCE_2_ID, job2.getJobId()); assertStatusNotDefault(job2); resp.close(); }
Example 30
Source Project: jax-rs-pac4j Source File: AbstractTest.java License: Apache License 2.0 | 5 votes |
@Test public void directInject() { Form form = new Form(); form.param("username", "foo"); form.param("password", "foo"); final String ok = container.getTarget("/directInject").request() .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class); assertThat(ok).isEqualTo("ok"); }