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:org.openmrs.module.htmlformentry.ObsTagTest.java

@Test
public void dynamicAutocomplete_shouldEditExistingObs() throws Exception {
    new RegressionTestHelper() {

        @Override//from w w  w . j  av  a2  s.co  m
        public String getFormName() {
            return "singleObsFormWithMultiAutocomplete";
        }

        public Patient getPatient() {
            return patient;
        }

        @Override
        public String[] widgetLabels() {
            return new String[] { "Date:", "Location:", "Provider:", "Coded:" };
        }

        @Override
        public void setupRequest(MockHttpServletRequest request, Map<String, String> widgets) {
            request.addParameter(widgets.get("Date:"), dateAsString(new Date()));
            request.addParameter(widgets.get("Location:"), "2");
            request.addParameter(widgets.get("Provider:"), "502");
            request.addParameter(widgets.get("Coded:"), "2"); // in the dynamic autocomplete, the widget value is just the count of the number of entries
            request.addParameter("w8span_0_hid", "1001");
            request.addParameter("w8span_1_hid", "1002");
        }

        @Override
        public boolean doEditEncounter() {
            return true;
        }

        @Override
        public String[] widgetLabelsForEdit() {
            return new String[] { "Coded:" };
        }

        @Override
        public void setupEditRequest(MockHttpServletRequest request, Map<String, String> widgets) {
            request.setParameter(widgets.get("Coded:"), "2"); // in the dynamic autocomplete, the widget value is just the count of the number of entries
            request.setParameter("w8span_0_hid", "1002");
            request.setParameter("w8span_1_hid", "1003");
        }

        @Override
        public void testEditedResults(SubmissionResults results) {

            results.assertNoErrors();
            Encounter encounter = results.getEncounterCreated();

            assertThat(encounter.getAllObs(false).size(), is(2)); // should be two non-voided obs of value 1002 & 1003
            assertThat(encounter.getAllObs(true).size(), is(3)); // should be three obs included the voided obs for 1001

            Set<Integer> valueCoded = new HashSet<Integer>();

            for (Obs obs : encounter.getAllObs(true)) {
                if (obs.isVoided()) {
                    assertThat(obs.getValueCoded().getId(), is(1001));
                } else {
                    valueCoded.add(obs.getValueCoded().getId());
                }
            }

            assertTrue(valueCoded.contains(1002));
            assertTrue(valueCoded.contains(1003));
        }

    }.run();
}

From source file:org.openmrs.module.htmlformentry.ObsTagTest.java

@Test
public void dynamicAutocomplete_shouldEditExistingObsWhenSomeObsAreRemoved() throws Exception {
    new RegressionTestHelper() {

        @Override/*ww  w .ja v  a  2 s .co m*/
        public String getFormName() {
            return "singleObsFormWithMultiAutocomplete";
        }

        public Patient getPatient() {
            return patient;
        }

        @Override
        public String[] widgetLabels() {
            return new String[] { "Date:", "Location:", "Provider:", "Coded:" };
        }

        @Override
        public void setupRequest(MockHttpServletRequest request, Map<String, String> widgets) {
            request.addParameter(widgets.get("Date:"), dateAsString(new Date()));
            request.addParameter(widgets.get("Location:"), "2");
            request.addParameter(widgets.get("Provider:"), "502");
            request.addParameter(widgets.get("Coded:"), "2"); // in the dynamic autocomplete, the widget value is just the count of the number of entries
            request.addParameter("w8span_0_hid", "1001");
            request.addParameter("w8span_1_hid", "1002");
        }

        @Override
        public boolean doEditEncounter() {
            return true;
        }

        @Override
        public String[] widgetLabelsForEdit() {
            return new String[] { "Coded:" };
        }

        @Override
        public void setupEditRequest(MockHttpServletRequest request, Map<String, String> widgets) {
            request.setParameter(widgets.get("Coded:"), "1"); // in the dynamic autocomplete, the widget value is just the count of the number of entries
            request.setParameter("w8span_0_hid", "1003");
            request.removeParameter("w8span_1_hid");
        }

        @Override
        public void testEditedResults(SubmissionResults results) {

            results.assertNoErrors();
            Encounter encounter = results.getEncounterCreated();

            assertThat(encounter.getAllObs(false).size(), is(1)); // should be one non-voided obs of value 1003
            assertThat(encounter.getAllObs(true).size(), is(3)); // should be three obs included the voided obs for 1001 and 1002

            Set<Integer> valueCoded = new HashSet<Integer>();

            for (Obs obs : encounter.getAllObs(true)) {
                if (!obs.isVoided()) {
                    assertThat(obs.getValueCoded().getId(), is(1003));
                } else {
                    valueCoded.add(obs.getValueCoded().getId());
                }
            }

            assertTrue(valueCoded.contains(1002));
            assertTrue(valueCoded.contains(1001));
        }

    }.run();
}

From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java

public void testRegisterUser() throws Exception {
    final User user = new User();
    user.setUser("hasankhan");
    user.setPassword("nhmthk");
    user.setCreatedOn(new Timestamp(System.currentTimeMillis()));
    user.setLastUpdatedOn(new Timestamp(System.currentTimeMillis()));
    user.setRole(User.FIELD_ROLE_ADMIN, true);
    user.setRole(User.FIELD_ROLE_READ, true);
    user.setRole(User.FIELD_ROLE_WRITE, true);

    final MockHttpServletRequest request = new MockHttpServletRequest();
    final String serviceUri = "/service/register/admin.xml";
    request.setRequestURI(serviceUri);/*from   w  ww  .jav a  2s  .c  o m*/
    final String serializedContent = SerializerFactory.getInstance().serializeObject(SerializerFactory.XML,
            user);
    String requestString = "<" + XmlConstants.ELEMENT_REQUEST + ">";
    requestString += serializedContent;
    requestString += "</" + XmlConstants.ELEMENT_REQUEST + ">";
    request.addParameter("admin", requestString);

    LOG.debug("Request - " + requestString);
    final MockHttpServletResponse response = new MockHttpServletResponse();

    // execute controller
    mRestfulController.handleRequest(request, response);

    final String responseContent = response.getContentAsString();
    assertTrue("No content found", responseContent.length() > 0);
    LOG.debug("content - " + responseContent);
}

From source file:fi.okm.mpass.idp.authn.impl.SocialUserAuthServletTest.java

protected MockHttpServletRequest initHttpRequest() {
    String conversationKey = "mockKey";
    String startKey = "mockStartKey";
    MockHttpServletRequest httpRequest = new MockHttpServletRequest();
    MockHttpSession httpSession = new MockHttpSession();
    httpSession.setAttribute("ext_auth_start_key", startKey);
    ProfileRequestContext<?, ?> profileContext = new ProfileRequestContext<Object, Object>();
    final AuthenticationContext authnContext = profileContext.getSubcontext(AuthenticationContext.class, true);
    authnContext.setAttemptedFlow(new AuthenticationFlowDescriptor());
    final ExternalAuthenticationContext extAuthnContext = authnContext
            .getSubcontext(ExternalAuthenticationContext.class, true);
    extAuthnContext.setFlowExecutionUrl("http://localhost.example.org/mock");
    httpSession.setAttribute(ExternalAuthentication.CONVERSATION_KEY + startKey,
            new ExternalAuthenticationImpl(profileContext));
    httpSession.setAttribute(ExternalAuthentication.CONVERSATION_KEY + conversationKey,
            new ExternalAuthenticationImpl(profileContext));
    httpRequest.setSession(httpSession);
    httpRequest.addParameter(ExternalAuthentication.CONVERSATION_KEY, conversationKey);
    return httpRequest;
}

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

@Test
public void getServiceAccessTokenWithWrongGrantTypeTest() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();

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

    try {/*from w w w .j av  a 2  s.  c  om*/
        oauthServlet.service(req, res);

        Assert.assertEquals("must return status BAD_REQUEST", 400, res.getStatus());

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

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

@Test
public void getServiceAccessTokenWithWrongClientSecretTest() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();

    req.addParameter("client_id", serviceApplication.getExternalId());
    req.addParameter("client_secret",
            BaseEncoding.base64().encode((serviceApplication.getExternalId() + ":lasdlkasldksladkalskdsal")
                    .getBytes(StandardCharsets.UTF_8)));
    req.addParameter("grant_type", "client_credentials");
    req.setMethod("POST");
    req.setPathInfo("/access_token");

    try {/*from  www . j  a  v  a2  s  . c om*/
        oauthServlet.service(req, res);

        Assert.assertEquals("must return status BAD_REQUEST", 400, res.getStatus());

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

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

@Test
public void getServiceAccessTokenTest() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();

    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 {/*from  w w  w.  j  a va  2 s .  com*/
        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 testServiceOnlyEndpoint() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();

    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 {//from w  w  w. j  ava 2  s. com
        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();
        final String accessToken = token.get(ACCESS_TOKEN).getAsString();

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

        String result = target("bennu-oauth").path("test").path("service-only-without-scope")
                .queryParam(ACCESS_TOKEN, accessToken).request().get(String.class);
        Assert.assertEquals("this is an endpoint with serviceOnly", result);

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

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

@Test
public void testServiceOnlyWithScopeEndpoint() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();

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

    try {//ww w.j av a2  s. c o  m
        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();
        final String accessToken = token.get(ACCESS_TOKEN).getAsString();

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

        String result = target("bennu-oauth").path("test").path("service-only-with-scope")
                .queryParam(ACCESS_TOKEN, accessToken).request().get(String.class);
        Assert.assertEquals("this is an endpoint with SERVICE scope, serviceOnly", result);

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

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

@Test
public void testServiceOnlyEndpointWithScopeMustFail() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();

    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 {/*from  ww  w.  jav  a2s  .  c  om*/
        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();
        final String accessToken = token.get(ACCESS_TOKEN).getAsString();

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

        Response result = target("bennu-oauth").path("test").path("service-only-with-scope")
                .queryParam(ACCESS_TOKEN, accessToken).request().get(Response.class);

        Assert.assertNotEquals("request must fail", 200, result.getStatus());

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