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

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

Introduction

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

Prototype

@Override
    @Nullable
    public HttpSession getSession() 

Source Link

Usage

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

@Test
public void testExec() throws Exception {
    final ListFormatters.FormatterDataResponse formatters = listService.exec(null, null, schema, false, false);
    for (ListFormatters.FormatterData formatter : formatters.getFormatters()) {
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.getSession();
        request.setPathInfo("/eng/blahblah");
        MockHttpServletResponse response = new MockHttpServletResponse();
        final String srvAppContext = "srvAppContext";
        request.getServletContext().setAttribute(srvAppContext, applicationContext);
        JeevesDelegatingFilterProxy.setApplicationContextAttributeKey(srvAppContext);
        RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

        formatService.exec("eng", "html", "" + id, null, formatter.getId(), "true", false, _100,
                new ServletWebRequest(request, response));

        final String view = response.getContentAsString();
        try {/*from  w ww .j a v  a  2  s .c  om*/
            assertFalse(formatter.getSchema() + "/" + formatter.getId(), view.isEmpty());
        } catch (Throwable e) {
            e.printStackTrace();
            fail(formatter.getSchema() + " > " + formatter.getId());
        }
        try {
            response = new MockHttpServletResponse();
            formatService.exec("eng", "testpdf", "" + id, null, formatter.getId(), "true", false, _100,
                    new ServletWebRequest(request, response));
            //                Files.write(Paths.get("e:/tmp/view.pdf"), response.getContentAsByteArray());
            //                System.exit(0);
        } catch (Throwable t) {
            t.printStackTrace();
            fail(formatter.getSchema() + " > " + formatter.getId());
        }
    }
}

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

@Test
public void testLoggingNullPointerBug() throws Exception {
    final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(Geonet.FORMATTER);
    Level level = logger.getLevel();
    logger.setLevel(Level.ALL);//from  w w w.  ja  v a2s  .c om
    try {
        MockHttpServletRequest webRequest = new MockHttpServletRequest();
        webRequest.getSession();
        final ServletWebRequest request = new ServletWebRequest(webRequest, new MockHttpServletResponse());
        final FormatterParams fparams = new FormatterParams();
        fparams.context = this.serviceContext;
        fparams.webRequest = request;
        // make sure context is cleared
        EnvironmentProxy.setCurrentEnvironment(fparams);

        final String formatterName = "logging-null-pointer";
        final URL testFormatterViewFile = FormatterApiIntegrationTest.class
                .getResource(formatterName + "/view.groovy");
        final Path testFormatter = IO.toPath(testFormatterViewFile.toURI()).getParent();
        final Path formatterDir = this.dataDirectory.getFormatterDir();
        IO.copyDirectoryOrFile(testFormatter, formatterDir.resolve(formatterName), false);
        final String functionsXslName = "functions.xsl";
        Files.deleteIfExists(formatterDir.resolve(functionsXslName));
        IO.copyDirectoryOrFile(testFormatter.getParent().resolve(functionsXslName),
                formatterDir.resolve(functionsXslName), false);

        formatService.exec("eng", "html", "" + id, null, formatterName, null, null, _100, request);

        // no Error is success
    } finally {
        logger.setLevel(level);
    }
}

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 w w w.java  2s  . co  m*/
        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();
    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:org.openmrs.web.controller.patient.PatientDashboardControllerTest.java

/**
 * @see PatientDashboardController#renderDashboard(Integer,ModelMap,HttpServletRequest)
 * @verifies render patient dashboard if given patient id is an existing uuid
 *///from   www .  j a v  a2 s.  c om
// @Test
public void renderDashboard_shouldRenderPatientDashboardIfGivenPatientIdIsAnExistingUuid() throws Exception {

    MockHttpServletRequest request = new MockHttpServletRequest();
    ModelMap map = new ModelMap();

    String view = patientDashboardController.renderDashboard(EXISTING_PATIENT_UUID, map, request);

    assertThat(view, is(PATIENT_DASHBOARD_VIEW));

    assertThat(map, hasKey("patient"));
    Patient patient = (Patient) map.get("patient");
    assertThat(patient.getUuid(), is(EXISTING_PATIENT_UUID));

    assertNull(request.getSession().getAttribute(WebConstants.OPENMRS_ERROR_ATTR));
    assertNull(request.getSession().getAttribute(WebConstants.OPENMRS_ERROR_ARGS));
}

From source file:ch.ralscha.extdirectspring.util.SupportedParametersTest.java

@Test
public void testResolveParameter() {
    MockHttpServletRequest request = new MockHttpServletRequest("POST", "/action/api-debug.js");
    MockHttpServletResponse response = new MockHttpServletResponse();
    Locale en = Locale.ENGLISH;

    assertThat(SupportedParameters.resolveParameter(String.class, request, response, en)).isNull();
    assertThat(SupportedParameters.resolveParameter(MockHttpServletRequest.class, request, response, en))
            .isSameAs(request);//from  w  w w. jav  a 2s.  co  m
    assertThat(SupportedParameters.resolveParameter(MockHttpSession.class, request, response, en))
            .isSameAs(request.getSession());
    assertThat(SupportedParameters.resolveParameter(Principal.class, request, response, en))
            .isSameAs(request.getUserPrincipal());
    assertThat(SupportedParameters.resolveParameter(MockHttpServletResponse.class, request, response, en))
            .isSameAs(response);
    assertThat(SupportedParameters.resolveParameter(Locale.class, request, response, en)).isSameAs(en);

    SSEWriter sseWriter = new SSEWriter(response);
    assertThat(SupportedParameters.resolveParameter(SSEWriter.class, request, response, en, sseWriter))
            .isSameAs(sseWriter);
}

From source file:org.openmrs.web.controller.patient.PatientDashboardControllerTest.java

/**
 * @see PatientDashboardController#renderDashboard(Integer,ModelMap,HttpServletRequest)
 * @verifies render patient dashboard if given patient id is an existing id
 */// www  .  ja  v a 2 s  .co  m
@Test
public void renderDashboard_shouldRenderPatientDashboardIfGivenPatientIdIsAnExistingId() throws Exception {

    MockHttpServletRequest request = new MockHttpServletRequest();
    ModelMap map = new ModelMap();

    String view = patientDashboardController.renderDashboard(EXISTING_PATIENT_ID, map, request);

    assertThat(view, is(PATIENT_DASHBOARD_VIEW));

    assertThat(map, hasKey("patient"));
    Patient patient = (Patient) map.get("patient");
    assertThat(patient.getPatientId(), is(Integer.valueOf(EXISTING_PATIENT_ID)));

    assertNull(request.getSession().getAttribute(WebConstants.OPENMRS_ERROR_ATTR));
    assertNull(request.getSession().getAttribute(WebConstants.OPENMRS_ERROR_ARGS));
}

From source file:fragment.web.AuthenticationControllerTest.java

@Test
public void testVerifyPhoneVerificationPINForUnlock() throws Exception {
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/login");
    request.getSession().setAttribute("phoneVerificationPin", "496");
    asRoot();/*w  ww .  j ava2s  .c  om*/
    String actualResult = controller.verifyPhoneVerificationPINForUnlock("PIN", request);
    Assert.assertEquals("failed", actualResult);
    request.getSession().setAttribute("phoneVerificationPin", "PIN");
    actualResult = controller.verifyPhoneVerificationPINForUnlock("PIN", request);
    Assert.assertEquals("success", actualResult);
}

From source file:fragment.web.AuthenticationControllerTest.java

@Test
public void testLoginWithIntranetOnlyModeDisabled() throws Exception {
    com.vmops.model.Configuration isIntranetModeEnabled = configurationService
            .locateConfigurationByName(Names.com_citrix_cpbm_use_intranet_only);
    isIntranetModeEnabled.setValue("false");
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/login");
    request.getSession().setAttribute(CaptchaAuthenticationFilter.CAPTCHA_REQUIRED, true);
    controller.login(request, map, request.getSession());
    Assert.assertTrue(map.containsKey("showCaptcha"));
    Assert.assertTrue(Boolean.valueOf(map.get("showCaptcha").toString()));
    Assert.assertTrue(map.containsKey("recaptchaPublicKey"));

}

From source file:fragment.web.AuthenticationControllerTest.java

@Test
public void testLoginWithIntranetOnlyModeEnabled() throws Exception {
    configurationService.clearConfigurationCache(true, "");
    com.vmops.model.Configuration isIntranetModeEnabled = configurationService
            .locateConfigurationByName(Names.com_citrix_cpbm_use_intranet_only);
    isIntranetModeEnabled.setValue("true");
    configurationService.update(isIntranetModeEnabled);
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/login");
    request.getSession().setAttribute(CaptchaAuthenticationFilter.CAPTCHA_REQUIRED, true);
    controller.login(request, map, request.getSession());
    Assert.assertFalse(map.containsKey("showCaptcha"));
    Assert.assertFalse(map.containsKey("recaptchaPublicKey"));

}