Example usage for org.springframework.mock.web MockHttpServletRequest addParameter

List of usage examples for org.springframework.mock.web MockHttpServletRequest addParameter

Introduction

In this page you can find the example usage for org.springframework.mock.web MockHttpServletRequest addParameter.

Prototype

public void addParameter(String name, String... values) 

Source Link

Document

Add an array of values for the specified HTTP parameter.

Usage

From source file:com.doitnext.http.router.DefaultInvokerTest.java

private HttpServletRequest createHappyMockRequest(HttpMethod method, PathMatch pm)
        throws JsonGenerationException, JsonMappingException, IOException {
    MockHttpServletRequest req = new MockHttpServletRequest();
    req.setMethod(method.name());//from   w  ww. java  2  s  .  com
    if (method == HttpMethod.POST || method == HttpMethod.PUT) {
        TestTeamPojo pojo = createRandomPojo();
        req.setContentType("application/json");
        req.setContent(mapper.writeValueAsBytes(pojo));
    }
    String terminus = pm.getMatchedPath().getTerminus();
    if (!StringUtils.isEmpty(terminus)) {
        req.setQueryString(terminus);
        String parts[] = req.getQueryString().split("&");
        for (String part : parts) {
            if (!StringUtils.isEmpty(part)) {
                String pieces[] = part.split("=");
                if (!StringUtils.isEmpty(pieces[0])) {
                    String key = pieces[0];
                    String value = "";
                    if (pieces.length > 1) {
                        value = pieces[1].trim();
                    }
                    req.addParameter(key, value);
                }
            }
        }
    }
    return req;
}

From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java

@Test
public void getServiceAccessTokenHeaderEmptyTest() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();
    Authenticate.unmock();/*w  ww . ja  va  2 s .  c  o m*/
    String clientSecret = "";

    req.addHeader(HttpHeaders.AUTHORIZATION,
            "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8)));
    req.addParameter(GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS);
    req.setMethod("POST");
    req.setPathInfo("/access_token");

    try {
        oauthServlet.service(req, res);
        Assert.assertEquals("must return BAD_REQUEST", 400, res.getStatus());

    } catch (ServletException | IOException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:org.jmesa.facade.TableFacadeTest.java

@Test
public void getLimitWithState() {

    Collection<President> items = PresidentDao.getPresidents();
    MockHttpServletRequest request = new MockHttpServletRequest();

    TableFacade facade = TableFacadeFactory.createTableFacade("pres", request);
    facade.setItems(items);/*from w w  w  .  j  av a  2 s.  co  m*/

    HtmlTable table = new HtmlTable();
    HtmlRow row = new HtmlRow();
    row.addColumn(new HtmlColumn("name.firstName"));
    row.addColumn(new HtmlColumn("name.lastName"));
    row.addColumn(new HtmlColumn("term"));
    row.addColumn(new HtmlColumn("career"));
    table.setRow(row);
    facade.setTable(table);

    facade.setStateAttr("restore");

    Limit limit = facade.getLimit();
    assertNotNull(limit);
    assertNotNull(limit.getRowSelect());
    assertNotNull(request.getSession().getAttribute("pres_LIMIT"));

    TableFacade facadeWithState = TableFacadeFactory.createTableFacade("pres", request);

    facadeWithState.setStateAttr("restore");
    request.addParameter("restore", "true");

    limit = facadeWithState.getLimit();
    assertNotNull(limit);
}

From source file:ar.com.zauber.commons.spring.test.impl.TamperdataHttpServletRequestFactory.java

/** hace el trabajo sucio 
 * @throws UnsupportedEncodingException */
private HttpServletRequest parse(final XMLStreamReader reader)
        throws XMLStreamException, UnsupportedEncodingException {
    final MockHttpServletRequest ret = new MockHttpServletRequest();
    ret.setMethod("POST");
    String header = null;//from  w  w w .  j  a  v a 2s.c o m
    String postHeader = null;
    int event;
    while ((event = reader.next()) != XMLStreamConstants.END_DOCUMENT) {
        if (event == XMLStreamConstants.START_ELEMENT) {
            final String name = reader.getLocalName();
            if (name.equals("tdRequestHeader") || name.equals("tdPostHeader")) {
                header = reader.getAttributeValue(0);
            } else if (name.equals("tdPostElements")) {
                ret.setMethod("POST");
            } else if (name.equals("tdPostElement")) {
                postHeader = reader.getAttributeValue(0);
            }
        } else if (event == XMLStreamConstants.CHARACTERS) {
            String text = reader.getText();
            if (text.length() > 1 && Character.isWhitespace(text.charAt(0))) {
                text = text.substring(1);
            }
            if (text.length() > 1 && Character.isWhitespace(text.charAt(text.length() - 1))) {
                text = text.substring(0, text.length() - 1);
            }

            final String value = URLDecoder.decode(URLDecoder.decode(text, encoding), encoding);
            if (header != null) {
                ret.addHeader(header, value);
            } else if (postHeader != null) {
                ret.addParameter(postHeader, value);
            }
            header = null;
            postHeader = null;
        } else {
            header = null;
            postHeader = null;
        }
    }
    reader.close();
    return ret;
}

From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java

@Test
public void getServiceAccessTokenHeaderTest() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();
    Authenticate.unmock();//from w ww .  j  a  v  a  2  s . c  o  m
    String clientSecret = serviceApplication.getExternalId() + ":" + serviceApplication.getSecret();
    req.addHeader(HttpHeaders.AUTHORIZATION,
            "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8)));
    req.addParameter(GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS);
    req.setMethod("POST");
    req.setPathInfo("/access_token");

    try {
        oauthServlet.service(req, res);

        Assert.assertEquals("must return status OK", 200, res.getStatus());

        String tokenJson = res.getContentAsString();

        final JsonObject token = new JsonParser().parse(tokenJson).getAsJsonObject();

        Assert.assertTrue("response must be a valid json and have access_token field",
                token.has(ACCESS_TOKEN) && token.get(ACCESS_TOKEN).getAsString().length() > 0);

    } catch (ServletException | IOException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java

@Test
public void testServiceApplicationWithUnexistingScope() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();
    Authenticate.unmock();/*  ww w  . j a  v a 2s  .co  m*/

    User user = createUser("testServiceApplicationWithUnexistingScope", "John", "Doe", "John Doe",
            "john.doe@fenixedu.org");

    ServiceApplication serviceApplication = new ServiceApplication();
    serviceApplication.setAuthor(user);

    req.addParameter("client_id", serviceApplication.getExternalId());
    req.addParameter("client_secret", serviceApplication.getSecret());
    req.addParameter("grant_type", "client_credentials");
    req.setMethod("POST");
    req.setPathInfo("/access_token");

    try {
        oauthServlet.service(req, res);

        Assert.assertEquals("must return status OK", 200, res.getStatus());

        String tokenJson = res.getContentAsString();

        final String serviceAccessToken = new JsonParser().parse(tokenJson).getAsJsonObject()
                .get("access_token").getAsString();

        Response response = target("bennu-oauth").path("test").path("service-only-with-unexisting-scope")
                .queryParam("access_token", serviceAccessToken).request().get();

        Assert.assertNotEquals("request must fail since scope does not exist", 200, response.getStatus());

    } catch (ServletException | IOException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:org.openmrs.web.controller.ConceptFormControllerTest.java

/**
 * Test to make sure a new patient form can save a person relationship
 * //from  w  w w . j  av  a  2s  .co m
 * @throws Exception
 */
@Test
public void shouldNotDeleteConceptsWhenConceptsAreLocked() throws Exception {
    // this dataset should lock the concepts
    executeDataSet("org/openmrs/web/include/ConceptFormControllerTest.xml");

    ConceptService cs = Context.getConceptService();

    // set up the controller
    ConceptFormController controller = (ConceptFormController) applicationContext.getBean("conceptForm");
    controller.setApplicationContext(applicationContext);
    controller.setSuccessView("index.htm");
    controller.setFormView("concept.form");

    // set up the request and do an initial "get" as if the user loaded the
    // page for the first time
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/dictionary/concept.form?conceptId=3");
    request.setSession(new MockHttpSession(null));
    HttpServletResponse response = new MockHttpServletResponse();
    controller.handleRequest(request, response);

    // set this to be a page submission
    request.setMethod("POST");

    request.addParameter("action", "Delete Concept"); // so that the form is processed

    // send the parameters to the controller
    ModelAndView mav = controller.handleRequest(request, response);

    Assert.assertNotSame("The purge attempt should have failed!", "index.htm", mav.getViewName());
    Assert.assertNotNull(cs.getConcept(3));

}

From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java

@Test
public void testServiceApplicationOAuthAccessProvider() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();
    Authenticate.unmock();//from  w  ww.jav a  2s  .  c o m

    User user = createUser("testServiceApplicationOAuthAccessProvider", "John", "Doe", "John Doe",
            "john.doe@fenixedu.org");

    ServiceApplication serviceApplication = new ServiceApplication();
    serviceApplication.setAuthor(user1);
    serviceApplication.addScopes(serviceApplicationOAuthAccessProvider);
    serviceApplication.addScopes(loggedScope);

    req.addParameter("client_id", serviceApplication.getExternalId());
    req.addParameter("client_secret", serviceApplication.getSecret());
    req.addParameter("grant_type", "client_credentials");
    req.setMethod("POST");
    req.setPathInfo("/access_token");

    try {
        oauthServlet.service(req, res);

        Assert.assertEquals("must return status OK", 200, res.getStatus());

        String tokenJson = res.getContentAsString();

        final String serviceAccessToken = new JsonParser().parse(tokenJson).getAsJsonObject()
                .get("access_token").getAsString();

        String result = target("oauth").path("provider").path(serviceApplication.getExternalId())
                .path(user.getUsername()).queryParam("access_token", serviceAccessToken).request()
                .post(null, String.class);

        Authenticate.unmock();

        final String userAccessToken = new JsonParser().parse(result).getAsJsonObject().get("access_token")
                .getAsString();

        result = target("bennu-oauth").path("test").path("test-scope-with-logged-user")
                .queryParam("access_token", userAccessToken).request().get(String.class);

        Assert.assertEquals("this is an endpoint with TEST scope: testServiceApplicationOAuthAccessProvider",
                result);

        Authenticate.mock(user);

        JsonArray authorizations = target("bennu-oauth").path("authorizations").request().get(JsonElement.class)
                .getAsJsonArray();

        Assert.assertEquals("no authorizations because it is a service application", 0, authorizations.size());

    } catch (ServletException | IOException e) {
        Assert.fail(e.getMessage());
    } finally {
        serviceApplication.removeScope(serviceApplicationOAuthAccessProvider);
        serviceApplication.removeScope(loggedScope);
    }

}