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:com.ideabase.repository.test.webservice.RESTfulControllerTest.java

/**
 * Request for updating an exsiting object.
 * @throws Exception/*from  ww w  . ja  v a2 s  .  com*/
 */
public void testUpdateOperation() throws Exception {
    // Create dummy user object
    final Integer dummyUserId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan");

    // Create fixture data
    final List<Integer> createdItemIdList = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 1);
    // Set dummy user with the deletable list of items
    createdItemIdList.add(dummyUserId);

    try {
        final Subject subject = getSubjectFromASuccessfulRequest();
        // build mock request
        final MockHttpServletRequest request = new MockHttpServletRequest();
        request.setRequestURI("/service/update/item.xml");
        request.setMethod(METHOD_POST);
        request.getSession().setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject);
        request.addParameter("item", fixUpdateRequest(createdItemIdList.get(0)));

        // Build mock response
        final MockHttpServletResponse response = new MockHttpServletResponse();

        // send request
        mRestfulController.handleRequest(request, response);

        // verify response
        final String content = response.getContentAsString();
        assertFalse("Response Content is empty", content.length() == 0);
        LOG.debug("Response - " + content);
        assertTrue("Response state false.", content.indexOf("false") == -1);

        // verify updated object
        final GenericItem item = mRepositoryService.getItem(createdItemIdList.get(0), GenericItem.class);
        LOG.debug("Updated item - " + item);
        assertEquals("New title doesn't match", "hasan-bang", item.getTitle());
    } finally {
        TestCaseRepositoryHelper.fixRemoveAllItems(mRepositoryService);
    }
}

From source file:ejportal.webapp.action.JournalkostenActionTest.java

/**
 * Test save.//from w  w w  . j av a  2  s.  c  o  m
 * 
 * @throws Exception
 *             the exception
 */
public void testSave() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    ServletActionContext.setRequest(request);
    this.action.setJournalkostenId(1L);
    this.action.setJournalId(1L);
    Assert.assertEquals("edit", this.action.edit());
    Assert.assertNotNull(this.action.getJournalkosten());

    // update Journalkosten and save
    this.action.getJournalkosten().setOPreisPO((long) 123.23);
    Assert.assertEquals("success", this.action.save());
    Assert.assertEquals((long) 123.23, (long) this.action.getJournalkosten().getOPreisPO());
    Assert.assertFalse(this.action.hasActionErrors());
    Assert.assertFalse(this.action.hasFieldErrors());
    Assert.assertNotNull(request.getSession().getAttribute("messages"));
}

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

public void testDeleteOperation() throws Exception {
    final List<Integer> createdItems = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 1);
    // create new user object
    final Integer userId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan");
    createdItems.add(userId);//from w w  w  .ja  v  a 2 s. c  o m
    try {
        final Subject subject = getSubjectFromASuccessfulRequest();
        final MockHttpServletRequest request = new MockHttpServletRequest();
        request.setRequestURI("/service/delete/" + createdItems.get(0) + ".xml");
        request.setMethod(METHOD_DELETE);
        request.getSession().setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject);
        final MockHttpServletResponse response = new MockHttpServletResponse();

        // Execute command
        mRestfulController.handleRequest(request, response);

        // Verify impacts
        final String content = response.getContentAsString();
        assertTrue("No response request generated.", content.length() > 0);
        final boolean stateTrue = content.indexOf("true") != -1;
        assertTrue("No response state found", stateTrue);
        assertEquals("Return status 202", RESTfulControllerImpl.STATUS_ACCEPTED_202, 202);
        LOG.debug("Content - " + content);
    } finally {
        TestCaseRepositoryHelper.fixRemoveAllItems(mRepositoryService);
    }
}

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

public void testAddRelatedItem() throws Exception {
    // Create dummy user object
    final Integer dummyUserId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan");

    // authenticate user.
    final Subject subject = getSubjectFromASuccessfulRequest();

    // fix data/*from   w w w  .  j a  v  a 2  s.  co  m*/
    final List<Integer> fixedItems = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 2);

    // relation types
    final String categoryType = "category";

    // request through xml format
    final GenericItem item = new GenericItem();
    item.setId(fixedItems.get(1));
    item.addRelatedItem(categoryType, fixedItems.get(0));

    // prepare request command
    final StringBuilder requestString = new StringBuilder();
    requestString.append("<" + XmlConstants.ELEMENT_REQUEST + ">");
    requestString.append(SerializerFactory.getInstance().serializeObject(SerializerFactory.XML, item));
    requestString.append("</" + XmlConstants.ELEMENT_REQUEST + ">");

    // create request uri
    final String requestUri = "/service/add-related-items/id.xml";
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI(requestUri);
    request.setMethod(METHOD_POST);
    request.addParameter("id", requestString.toString());
    request.getSession().setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject);
    final MockHttpServletResponse response = new MockHttpServletResponse();

    // execute restful service
    mRestfulController.handleRequest(request, response);

    // verify
    final String responseString = response.getContentAsString();
    LOG.debug("Response string - " + responseString);
    assertFalse("No response found", responseString == null || responseString.length() == 0);
    assertFalse("Response state false", responseString.indexOf("false") != -1);

}

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

public void testDeleteRelatedItem() throws Exception {
    // Create dummy user object
    final Integer dummyUserId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan");

    // authenticate user.
    final Subject subject = getSubjectFromASuccessfulRequest();

    // fix data/*ww  w  .ja  v a2  s. com*/
    final List<Integer> fixedItems = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 2);

    // relation types
    final String categoryType = "category";

    // add related items
    mRepositoryService.addRelatedItem(categoryType, fixedItems.get(0), fixedItems.get(1));
    // verify
    final List<Integer> relatedItems = mRepositoryService.getRelatedItems(fixedItems.get(0), categoryType, 0,
            Integer.MAX_VALUE);
    assertTrue("No related item found", relatedItems != null && !relatedItems.isEmpty());

    // request through xml format
    final GenericItem item = new GenericItem();
    item.setId(fixedItems.get(0));
    item.addRelatedItem(categoryType, fixedItems.get(1));

    // prepare request command
    final StringBuilder requestString = new StringBuilder();
    requestString.append("<" + XmlConstants.ELEMENT_REQUEST + ">");
    requestString.append(SerializerFactory.getInstance().serializeObject(SerializerFactory.XML, item));
    requestString.append("</" + XmlConstants.ELEMENT_REQUEST + ">");

    // create request uri
    final String requestUri = "/service/delete-related-items/id.xml";
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI(requestUri);
    request.setMethod(METHOD_POST);
    request.addParameter("id", requestString.toString());
    request.getSession().setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject);
    final MockHttpServletResponse response = new MockHttpServletResponse();

    // execute restful service
    mRestfulController.handleRequest(request, response);

    // verify
    final String responseString = response.getContentAsString();
    LOG.debug("Response string - " + responseString);
    assertFalse("No response found", responseString == null || responseString.length() == 0);
    assertFalse("Response state false", responseString.indexOf("false") != -1);

    // verify related items
    final List<Integer> relatedItems2 = mRepositoryService.getRelatedItems(fixedItems.get(0), categoryType, 0,
            Integer.MAX_VALUE);
    assertFalse("Related item found", relatedItems2 != null && !relatedItems2.isEmpty());
}

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

public void testListOfRelatedItems() throws Exception {
    // Create dummy user object
    final Integer dummyUserId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan");

    // authenticate user.
    final Subject subject = getSubjectFromASuccessfulRequest();

    // create fixed items
    final List<Integer> fixedItems = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 11);

    // update object relation
    final Integer baseItemId = fixedItems.get(0);

    // attach related items
    final String relationType = "category";
    mRepositoryService.addRelatedItems(relationType, baseItemId, fixedItems.subList(1, fixedItems.size()));

    // send restful request
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI(/*  ww  w .  j av a  2s  . co  m*/
            "/service/find-related-items/" + relationType + "&" + String.valueOf(baseItemId) + ".xml");
    request.setParameter(WebConstants.PARAM_MAX, 4 + "");
    request.setMethod(METHOD_POST);
    request.getSession().setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject);
    final MockHttpServletResponse response = new MockHttpServletResponse();

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

    final String responseString = response.getContentAsString();
    LOG.debug("Response content - " + responseString);

    assertFalse("No response found", responseString == null || responseString.length() == 0);
    assertFalse("Response state false", responseString.indexOf("false") != -1);
}

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

/**
 * Test delete./*w  ww.  j a 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:fi.okm.mpass.idp.authn.impl.SocialUserOpenIdConnectStartServletTest.java

/**
 * Run servlet with prerequisities met.//from   w w  w.  ja v a  2  s .  c o m
 * @throws Exception
 */
@Test
public void testSuccess() throws Exception {
    MockHttpServletRequest httpRequest = new MockHttpServletRequest();
    httpRequest.setParameter(ExternalAuthentication.CONVERSATION_KEY, conversationKey);
    final ProfileRequestContext<?, ?> ctx = new ProfileRequestContext<>();
    final AuthenticationContext authnCtx = ctx.getSubcontext(AuthenticationContext.class, true);
    final AuthenticationFlowDescriptor flow = new AuthenticationFlowDescriptor();
    flow.setId("mock");
    authnCtx.setAttemptedFlow(flow);
    final SocialUserOpenIdConnectContext suOidcCtx = authnCtx
            .getSubcontext(SocialUserOpenIdConnectContext.class, true);
    final String redirectUri = "https://mock.example.org";
    suOidcCtx.setAuthenticationRequestURI(new URI(redirectUri));
    httpRequest.getSession().setAttribute(ExternalAuthentication.CONVERSATION_KEY + conversationKey,
            new ExternalAuthenticationImpl(ctx));
    final MockHttpServletResponse httpResponse = new MockHttpServletResponse();
    Assert.assertFalse(runService(servlet, httpRequest, httpResponse));
    Assert.assertEquals(httpResponse.getRedirectedUrl(), redirectUri);
    Assert.assertNotNull(
            httpRequest.getSession().getAttribute(SocialUserOpenIdConnectStartServlet.SESSION_ATTR_SUCTX));
    Assert.assertTrue(httpRequest.getSession().getAttribute(
            SocialUserOpenIdConnectStartServlet.SESSION_ATTR_SUCTX) instanceof SocialUserOpenIdConnectContext);
}

From source file:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTests.java

@Test
public void buildRequestSessionIsNew() throws Exception {
    MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

    assertThat(actualRequest.getSession().isNew(), equalTo(true));
}

From source file:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTests.java

@Test
public void buildRequestSessionIsNewFalse() throws Exception {
    String sessionId = "session-id";
    webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);

    MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

    assertThat(actualRequest.getSession().isNew(), equalTo(false));
}