javax.ws.rs.core.Form Java Examples

The following examples show how to use javax.ws.rs.core.Form. 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: RepositoryFileApi.java    From gitlab4j-api with MIT License 6 votes vote down vote up
/**
 * 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 #2
Source File: RegistrationManager.java    From peer-os with Apache License 2.0 6 votes vote down vote up
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 File: AuthorizationGrantTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: CommandProcessor.java    From peer-os with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: SamlFormOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: TestCalendarService.java    From openmeetings with Apache License 2.0 6 votes vote down vote up
@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 #7
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 #8
Source File: AbstractCdiSingleAppTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: GroupApi.java    From choerodon-starters with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #10
Source File: DefaultFormEntityProviderTest.java    From krazo with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: SaltConnector.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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 #12
Source File: OAuth2Test.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: SakaiLoginLoginTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@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 File: OAuthRequestFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
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 #15
Source File: MergeRequestApi.java    From choerodon-starters with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #16
Source File: KeycloakMicroprofileJwtWithoutJsonTest.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@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 #17
Source File: EndToEndServletTest.java    From dropwizard-pac4j with Apache License 2.0 6 votes vote down vote up
@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 #18
Source File: DeployKeysApi.java    From choerodon-starters with Apache License 2.0 5 votes vote down vote up
/**
 * Enables a deploy key for a project so this can be used. Returns the enabled key when successful.
 * <p>
 * POST /projects/:id/deploy_keys/:key_id/enable
 *
 * @param projectId the ID of the project
 * @param keyId     the ID of the deploy key to enable
 * @return an DeployKey instance with info on the enabled deploy key
 * @throws GitLabApiException if any exception occurs
 */
public DeployKey enableDeployKey(Integer projectId, Integer keyId) throws GitLabApiException {

    if (projectId == null) {
        throw new RuntimeException("projectId cannot be null");
    }

    if (keyId == null) {
        throw new RuntimeException("keyId cannot be null");
    }

    Response response = post(Response.Status.CREATED, (Form) null, "projects", projectId, "deploy_keys", keyId, "enable");
    return (response.readEntity(DeployKey.class));
}
 
Example #19
Source File: AbstractClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected Object checkIfBodyEmpty(Object body, String contentType) {
    //CHECKSTYLE:OFF
    if (body != null
        && (body.getClass() == String.class && ((String)body).isEmpty()
        || body.getClass() == Form.class && ((Form)body).asMap().isEmpty()
        || Map.class.isAssignableFrom(body.getClass()) && ((Map<?, ?>)body).isEmpty()
            && !MediaType.APPLICATION_JSON.equals(contentType)
        || body instanceof byte[] && ((byte[])body).length == 0)) {
        body = null;
    }
    //CHECKSTYLE:ON
    return body;
}
 
Example #20
Source File: AbstractTest.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Test
public void directInjectManagerNoAuth() {
    Form form = new Form();
    form.param("username", "foo");
    form.param("password", "bar");
    final String ok = container.getTarget("/directInjectManager").request()
            .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
    assertThat(ok).isEqualTo("fail");
}
 
Example #21
Source File: BackChannelLogoutHandler.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private void submitBackChannelLogoutRequest(final Client client, final OidcUserSubject subject,
        final IdToken idTokenHint, final String uri) {
    // Application context is expected to contain HttpConduit HTTPS configuration
    final WebClient wc = WebClient.create(uri);
    IdToken idToken = idTokenHint != null ? idTokenHint : subject.getIdToken(); 
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(idToken.getIssuer());
    claims.setSubject(idToken.getSubject());
    claims.setAudience(client.getClientId());
    claims.setIssuedAt(System.currentTimeMillis() / 1000);
    claims.setTokenId(Base64UrlUtility.encode(CryptoUtils.generateSecureRandomBytes(16)));
    claims.setClaim(EVENTS_PROPERTY, 
            Collections.singletonMap(BACK_CHANNEL_LOGOUT_EVENT, Collections.emptyMap()));
    if (idToken.getName() != null) {
        claims.setClaim(IdToken.NAME_CLAIM, idToken.getName());    
    }
    
    final String logoutToken = super.processJwt(new JwtToken(claims));
    executorService.submit(new Runnable() {

        @Override
        public void run() {
            try {
                wc.form(new Form().param(LOGOUT_TOKEN, logoutToken));
            } catch (Exception ex) {
                LOG.info(String.format("Back channel request to %s to log out %s from client %s has failed",
                    uri, subject.getLogin(), client.getClientId()));
                LOG.fine(String.format("%s request failure: %s", uri, ExceptionUtils.getStackTrace(ex)));
            }
        }
    
    });
    
}
 
Example #22
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 #23
Source File: FormUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static String formToString(Form form) {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        FormUtils.writeMapToOutputStream(form.asMap(), bos, StandardCharsets.UTF_8.name(), false);
        return bos.toString(StandardCharsets.UTF_8.name());
    } catch (Exception ex) {
        // will not happen
    }
    return "";
}
 
Example #24
Source File: AbstractTest.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Test
public void directOkComplexContentType() {
    Form form = new Form();
    form.param("username", "foo");
    form.param("password", "foo");
    final String ok = container.getTarget("/direct").request().post(
            Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE.withCharset("UTF-8")), String.class);
    assertThat(ok).isEqualTo("ok");
}
 
Example #25
Source File: MarkdownApi.java    From gitlab4j-api with MIT License 5 votes vote down vote up
/**
 * Render an arbitrary Markdown document.
 *
 * <pre><code>GitLab Endpoint: POST /api/v4/markdown</code></pre>
 *
 * @param text text to be transformed
 * @return a Markdown instance with transformed info
 * @throws GitLabApiException if any exception occurs
 * @since GitLab 11.0
 */
public Markdown getMarkdown(String text) throws GitLabApiException {

    if (!isApiVersion(ApiVersion.V4)) {
        throw new GitLabApiException("Api version must be v4");
    }

    Form formData = new GitLabApiForm().withParam("text", text, true);
    Response response = post(Response.Status.OK, formData.asMap(), "markdown");
    return (response.readEntity(Markdown.class));
}
 
Example #26
Source File: JAXRSClientServerValidationTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatResponseValidationForBookPassesWhenNoConstraintsAreDefined()  {
    Response r = createWebClient("/bookstore/booksResponseNoValidation/1234").get();
    assertEquals(Status.OK.getStatusCode(), r.getStatus());

    r = createWebClient("/bookstore/books").post(new Form().param("id", "1234"));
    assertEquals(Status.CREATED.getStatusCode(), r.getStatus());

    r = createWebClient("/bookstore/booksResponseNoValidation/1234").get();
    assertEquals(Status.OK.getStatusCode(), r.getStatus());
}
 
Example #27
Source File: JAXRSClientServerValidationTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@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 #28
Source File: JAXRSSoapBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBookWebClientForm2() throws Exception {

    String baseAddress = "http://localhost:" + PORT
        + "/test/services/rest/bookstore/books/679/subresource3";
    WebClient wc = WebClient.create(baseAddress);
    Form f = new Form(new MetadataMap<String, String>());
    f.param("id", "679").param("name", "CXF in Action - ")
        .param("name", "679");
    Book b = readBook((InputStream)wc.accept("application/xml")
                      .form(f).getEntity());
    assertEquals(679, b.getId());
    assertEquals("CXF in Action - 679", b.getName());
}
 
Example #29
Source File: FormUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void restoreForm(FormEncodingProvider<Form> provider,
                               Form form,
                               Message message)
    throws Exception {
    CachedOutputStream os = new CachedOutputStream();
    writeForm(provider, form, os);
    message.setContent(InputStream.class, os.getInputStream());
}
 
Example #30
Source File: OauthApi.java    From choerodon-starters with Apache License 2.0 5 votes vote down vote up
public AccessToken oauthLogin(String hostUrl, String username, String email, String password) throws GitLabApiException, IOException {
    if ((username == null || username.trim().length() == 0) && (email == null || email.trim().length() == 0)) {
        throw new IllegalArgumentException("both username and email cannot be empty or null");
    }
    Form formData = new Form();
    addFormParam(formData, "email", email, false);
    addFormParam(formData, "password", password, true);
    addFormParam(formData, "username", username, false);
    addFormParam(formData, "grant_type", "password");
    StringBuilder url = new StringBuilder();
    url.append(hostUrl.endsWith("/") ? hostUrl.replaceAll("/$", "") : hostUrl);
    url.append("/oauth/token");
    Response response = post(Response.Status.OK, formData, new URL(url.toString()));
    return (response.readEntity(AccessToken.class));
}