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:fr.paris.lutece.portal.web.admin.AdminPageJspBeanTest.java

public void testGetRemovePage() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter(Parameters.PAGE_ID, Integer.toString(_page.getId()));
    _bean.getRemovePage(request);//from  w w w .ja  v  a2 s.  co m
    AdminMessage message = AdminMessageService.getMessage(request);
    assertNotNull(message);
    assertNotNull(message.getRequestParameters().get(SecurityTokenService.PARAMETER_TOKEN));
    assertEquals(AdminMessage.TYPE_CONFIRMATION, message.getType());
    ReferenceList listLanguages = I18nService.getAdminLocales(Locale.FRANCE);
    for (ReferenceItem lang : listLanguages) {
        assertTrue(message.getText(new Locale(lang.getCode())).contains(_randomPageName));
    }
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_8.PersonController1_8Test.java

@Test
public void shouldRespectStartIndexAndLimit() throws Exception {
    MockHttpServletRequest req = newGetRequest(getURI());
    req.setParameter("q", "Test");
    SimpleObject results = deserialize(handle(req));
    int fullCount = Util.getResultsSize(results);
    assertTrue("This test assumes > 2 matching persons", fullCount > 2);

    req.addParameter(RestConstants.REQUEST_PROPERTY_FOR_LIMIT, "2");
    results = deserialize(handle(req));/*from  w  ww .  j a  va 2s . c o m*/
    int firstCount = Util.getResultsSize(results);
    assertEquals(2, firstCount);

    req.removeParameter(RestConstants.REQUEST_PROPERTY_FOR_LIMIT);
    req.addParameter(RestConstants.REQUEST_PROPERTY_FOR_START_INDEX, "2");
    results = deserialize(handle(req));
    int restCount = Util.getResultsSize(results);
    assertEquals(fullCount, firstCount + restCount);
}

From source file:fr.paris.lutece.portal.web.admin.AdminPageJspBeanTest.java

public void testDoRemovePageWithChild() throws AccessDeniedException {
    String childPageName = _randomPageName + "-child";
    Page childPage = null;/*from w w  w  .ja  va 2  s. c o  m*/
    IPageService pageService = (IPageService) SpringContextService.getBean("pageService");
    try {
        childPage = new Page();
        childPage.setParentPageId(_page.getId());
        childPage.setPageTemplateId(PageTemplateHome.getPageTemplatesList().get(0).getId());
        childPage.setName(childPageName);
        pageService.createPage(childPage);
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.addParameter(Parameters.PAGE_ID, Integer.toString(_page.getId()));
        _bean.doRemovePage(request);
        AdminMessage message = AdminMessageService.getMessage(request);
        assertNotNull(message);
        assertEquals(AdminMessage.TYPE_STOP, message.getType());
        ReferenceList listLanguages = I18nService.getAdminLocales(Locale.FRANCE);
        for (ReferenceItem lang : listLanguages) {
            assertTrue(message.getText(new Locale(lang.getCode())).contains(_randomPageName));
        }
    } finally {
        if (childPage != null) {
            try {
                pageService.removePage(childPage.getId());
            } finally {
            }
        }
    }
}

From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

@Test
public void testLastModified() throws Exception {
    String stage = systemInfo.getStagingProfile();
    systemInfo.setStagingProfile(SystemInfo.STAGE_PRODUCTION);
    try {/*from  ww  w .  j  a  v  a2s.  com*/
        metadataRepository.update(id, new Updater<Metadata>() {
            @Override
            public void apply(@Nonnull Metadata entity) {
                entity.getDataInfo().setChangeDate(new ISODate("2012-01-18T15:04:43"));
            }
        });
        dataManager.indexMetadata(Lists.newArrayList("" + this.id));

        final String formatterName = "full_view";

        MockHttpServletRequest request = new MockHttpServletRequest();
        request.getSession();
        request.addParameter("h2IdentInfo", "true");

        MockHttpServletResponse response = new MockHttpServletResponse();
        formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100,
                new ServletWebRequest(request, response));
        final String lastModified = response.getHeader("Last-Modified");
        assertEquals("no-cache", response.getHeader("Cache-Control"));
        final String viewString = response.getContentAsString();
        assertNotNull(viewString);

        request = new MockHttpServletRequest();
        request.getSession();
        request.setMethod("GET");
        response = new MockHttpServletResponse();

        request.addHeader("If-Modified-Since", lastModified);
        formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100,
                new ServletWebRequest(request, response));
        assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getStatus());
        final ISODate newChangeDate = new ISODate();
        metadataRepository.update(id, new Updater<Metadata>() {
            @Override
            public void apply(@Nonnull Metadata entity) {
                entity.getDataInfo().setChangeDate(newChangeDate);
            }
        });

        dataManager.indexMetadata(Lists.newArrayList("" + this.id));

        request = new MockHttpServletRequest();
        request.getSession();
        request.setMethod("GET");
        response = new MockHttpServletResponse();

        request.addHeader("If-Modified-Since", lastModified);
        formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100,
                new ServletWebRequest(request, response));
        assertEquals(HttpStatus.SC_OK, response.getStatus());
    } finally {
        systemInfo.setStagingProfile(stage);
    }
}

From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

@Test
public void testExecGroovy() throws Exception {
    final String formatterName = configureGroovyTestFormatter();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.getSession();/*from   w  w w  . j a  v a  2 s .c o m*/
    request.addParameter("h2IdentInfo", "true");

    final MockHttpServletResponse response = new MockHttpServletResponse();
    formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100,
            new ServletWebRequest(request, response));
    final String viewString = response.getContentAsString();
    //        com.google.common.io.Files.write(viewString, new File("e:/tmp/view.html"), Constants.CHARSET);

    final Element view = Xml.loadString(viewString, false);
    assertEquals("html", view.getName());
    assertNotNull("body", view.getChild("body"));

    // Check that the "handlers.add 'gmd:abstract', { el ->" correctly applied
    assertElement(view, "body//p[@class = 'abstract']/span[@class='label']", "Abstract", 1);
    assertElement(view, "body//p[@class = 'abstract']/span[@class='value']", "Abstract {uuid}", 1);

    // Check that the "handlers.add ~/...:title/, { el ->" correctly applied
    assertElement(view, "body//p[@class = 'title']/span[@class='label']", "Title", 1);
    assertElement(view, "body//p[@class = 'title']/span[@class='value']", "Title", 1);

    // Check that the "handlers.withPath ~/[^>]+>gmd:identificationInfo>.*extent/, Iso19139Functions.&handleExtent" correctly applied
    assertElement(view, "body//p[@class = 'formatter']", "fromFormatterGroovy", 1);

    // Check that the "handlers.withPath ~/[^>]+>gmd:identificationInfo>.*extent/, Iso19139Functions.&handleExtent" correctly applied
    assertElement(view, "body//p[@class = 'shared']", "fromSharedFunctions", 1);

    // Check that the "handlers.add ~/...:title/, { el ->" correctly applied
    assertElement(view, "body//p[@class = 'code']/span[@class='label']", "Unique resource identifier", 1);
    assertElement(view, "body//p[@class = 'code']/span[@class='value']", "WGS 1984", 1);

    // Check that the handlers.add 'gmd:CI_OnlineResource', { el -> handler is applied
    assertElement(view, "body//p[@class = 'online-resource']/h3", "OnLine resource", 1);
    assertElement(view, "body//p[@class = 'online-resource']/div/strong", "REPOM", 1);
    assertElement(view, "body//p[@class = 'online-resource']/div[@class='desc']", "", 1);
    assertElement(view, "body//p[@class = 'online-resource']/div[@class='linkage']/span[@class='label']",
            "URL:", 1);
    assertElement(view, "body//p[@class = 'online-resource']/div[@class='linkage']/span[@class='value']",
            "http://services.sandre.eaufrance.fr/geo/ouvrage", 1);

    // Check that the handler:
    //   handlers.add select: {el -> el.name() == 'gmd:identificationInfo' && f.param('h2IdentInfo').toBool()},
    //                processChildren: true, { el, childData ->
    // was applied
    assertElement(view, "*//div[@class = 'identificationInfo']/h2", "Data identification", 1);
    List<Element> identificationElements = (List<Element>) Xml.selectNodes(view,
            "*//div[@class = 'identificationInfo']/p");
    assertEquals(viewString, 4, identificationElements.size());
    assertEquals(viewString, "abstract", identificationElements.get(0).getAttributeValue("class"));
    assertEquals(viewString, "shared", identificationElements.get(1).getAttributeValue("class"));
    assertEquals(viewString, "block", identificationElements.get(2).getAttributeValue("class"));
    assertEquals(viewString, "block", identificationElements.get(3).getAttributeValue("class"));
    assertEquals(viewString, "block", identificationElements.get(3).getAttributeValue("class"));

    // Verify that handler
    // handlers.add name: 'codelist handler', select: isoHandlers.matchers.isCodeListEl, isoHandlers.isoCodeListEl
    // is handled
    assertElement(view, "body//span[@class = 'fileId']", this.uuid, 1);
    assertElement(view, "body//span[@class = 'creatorTranslated']", "Creator", 1);

    assertElement(view, "body//span[@class = 'extents']", "2", 1);

    assertNull(Xml.selectElement(view, "body//h1[text() = 'Reference System Information']"));
}

From source file:com.tasktop.c2c.server.common.service.tests.ajp.AjpProtocolTest.java

@Test
// Trying to recreate task 718
public void testGetThenPost() throws Exception {
    final byte[] POST_REQUEST_PAYLOAD = createData(431);

    GenericKeyedObjectPool uniSocketPool = new GenericKeyedObjectPool(new AjpPoolableConnectionFactory());
    uniSocketPool.setLifo(true);//from  ww w  .  j av  a 2  s .c o m
    uniSocketPool.setMaxIdle(1);
    uniSocketPool.setMaxTotal(1);
    uniSocketPool.setMinIdle(1);
    protocol.setSocketPool(uniSocketPool);

    for (int i = 0; i < 10; i++) {
        MockHttpServletRequest getRequest = new MockHttpServletRequest();

        getRequest.setMethod("GET");
        getRequest.setRequestURI("/alm/s/code2cloud/scm/test4.git/info/refs");
        getRequest.setQueryString("service=git-receive-pack");
        getRequest.addParameter("service", "git-receive-pack");
        getRequest.addHeader("Authorization", AUTH_HEADER);
        getRequest.addHeader("Host", "localhost:8888");
        getRequest.addHeader("User-Agent", "git/1.7.3.1");
        getRequest.addHeader("Accept", "*/*");
        getRequest.addHeader("Pragma", "no-cache");
        Payload getPayload = new Payload();
        getPayload.setResponseCode(HttpServletResponse.SC_OK);
        getPayload.setCharacterContent(GET_RESPONSE_PAYLOAD);

        MockHttpServletResponse response = new MockHttpServletResponse();
        TestServlet.setResponsePayload(getPayload);
        protocol.forward(getRequest, response);
        assertRequestIsExpected(getRequest, TestServlet.getLastRequest());
        assertResponseIsExpected(getPayload, response);

        MockHttpServletRequest postRequest = new MockHttpServletRequest();
        postRequest.setMethod("POST");
        postRequest.setRequestURI("/alm/s/code2cloud/scm/test4.git/git-receive-pack");
        postRequest.addHeader("Authorization", AUTH_HEADER);
        postRequest.addHeader("Host", "localhost:8888");
        postRequest.addHeader("Content-Length", "" + POST_REQUEST_PAYLOAD.length);
        postRequest.addHeader("Accept-Encoding", "deflate, gzip");
        postRequest.addHeader("User-Agent", "git/1.7.3.1");
        postRequest.addHeader("Accept", "application/x-git-receive-pack-result");
        postRequest.addHeader("Content-Type", "application/x-git-receive-pack-request");

        postRequest.setContent(POST_REQUEST_PAYLOAD);

        Payload postPayload = new Payload();
        postPayload.setResponseCode(HttpServletResponse.SC_OK);
        postPayload.setCharacterContent(POST_RESPONSE_PAYLOAD);

        response = new MockHttpServletResponse();
        TestServlet.setResponsePayload(postPayload);
        protocol.forward(postRequest, response);
        assertRequestIsExpected(postRequest, TestServlet.getLastRequest());
        assertResponseIsExpected(postPayload, response);
    }

}

From source file:alpha.portal.webapp.controller.CaseFormControllerTest.java

/**
 * Test delete.// ww w  .  ja v  a 2s.c  o m
 * 
 * @throws Exception
 *             the exception
 */
@Test
public void testDelete() throws Exception {
    MockHttpServletRequest request = this.newGet("/caseform");
    request.setParameter("caseId", CaseFormControllerTest.caseId);
    request.setRemoteUser("admin");
    final ModelAndView mv = this.form.showForm(this.filters, request, new MockHttpServletResponse());
    final AlphaCase myCase = (AlphaCase) mv.getModel().get("case");

    request = this.newPost("/caseform");
    request.setRemoteUser("admin");
    request.addParameter("delete", "");

    final BindingResult errors = new DataBinder(myCase).getBindingResult();
    final String view = this.form.deleteCase(myCase, errors, request);
    Assert.assertEquals(this.form.getCancelView(), view);
    Assert.assertNotNull(request.getSession().getAttribute("successMessages"));

    final Locale locale = request.getLocale();
    final ArrayList<Object> msgs = (ArrayList<Object>) request.getSession().getAttribute("successMessages");
    Assert.assertTrue(msgs.contains(this.form.getText("case.deleted", locale)));

    Assert.assertFalse(this.caseManager.exists(CaseFormControllerTest.caseId));
}

From source file:org.hdiv.filter.ValidatorHelperTest.java

/**
 * Validation test with an init parameter.
 *//* w w  w  .  j  ava  2 s.  c  o  m*/
public void testValidateHashOneStartParameter() {

    MockHttpServletRequest request = (MockHttpServletRequest) HDIVUtil.getHttpServletRequest();

    this.dataComposer.beginRequest(this.targetName);
    String pageState = this.dataComposer.endRequest();
    this.dataComposer.endPage();

    request.addParameter("testingInitParameter", "0");
    request.addParameter(hdivParameter, pageState);

    RequestWrapper requestWrapper = new RequestWrapper(request);
    assertTrue(helper.validate(requestWrapper).isValid());
}

From source file:org.hdiv.filter.ValidatorHelperTest.java

/**
 * Validation test with the HDIV parameter only. Validation should be correct.
 *///  w ww .ja v a 2 s  .  c o  m
public void testValidateHashOnlyHDIVParameter() {

    MockHttpServletRequest request = (MockHttpServletRequest) HDIVUtil.getHttpServletRequest();

    this.dataComposer.beginRequest(this.targetName);

    String pageState = this.dataComposer.endRequest();
    this.dataComposer.endPage();

    request.addParameter(hdivParameter, pageState);

    RequestWrapper requestWrapper = new RequestWrapper(request);
    boolean result = helper.validate(requestWrapper).isValid();
    assertTrue(result);
}