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

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

Introduction

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

Prototype

public void setMethod(@Nullable String method) 

Source Link

Usage

From source file:com.github.jrialland.ajpclient.servlet.TestServletProxy.java

@Test
public void testMultiple() throws Exception {

    final int nTasks = 10;

    for (int i = 0; i < nTasks; i++) {
        final MockHttpServletRequest request = new MockHttpServletRequest();
        request.setMethod("GET");
        request.setRequestURI("/long_request");
        request.setMethod("POST");
        request.addHeader("Content-Type", "application/x-www-form-urlencoded");
        request.setContent("duration=1000".getBytes());
        final MockHttpServletResponse response = new MockHttpServletResponse();
        AjpServletProxy.forHost("localhost", getPort()).forward(request, response);
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
    }//  ww  w  .j  av a 2 s. co  m
}

From source file:edu.internet2.middleware.shibboleth.idp.system.conf1.SAML2ArtifactResolutionTest.java

public void testArtifactResolution() throws Exception {
    String relyingPartyId = "urn:example.org:sp1";
    SAMLArtifactMapEntry artifactEntry = stageArtifact(relyingPartyId);
    String soapMessage = buildRequestMessage(relyingPartyId, artifactEntry.getArtifact());

    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    servletRequest.setMethod("POST");
    servletRequest.setPathInfo("/saml2/SOAP/ArtifactResolution");
    servletRequest.setContent(soapMessage.getBytes());

    MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    ProfileHandlerManager handlerManager = (ProfileHandlerManager) getApplicationContext()
            .getBean("shibboleth.HandlerManager");
    ProfileHandler handler = handlerManager.getProfileHandler(servletRequest);
    assertNotNull(handler);//from  w ww .j a va2 s . co m

    // Process request
    HTTPInTransport profileRequest = new HttpServletRequestAdapter(servletRequest);
    HTTPOutTransport profileResponse = new HttpServletResponseAdapter(servletResponse, false);
    handler.processRequest(profileRequest, profileResponse);

    String response = servletResponse.getContentAsString();
    assertTrue(response.contains("saml2p:ArtifactResponse"));
    assertTrue(response.contains("urn:oasis:names:tc:SAML:2.0:status:Success"));
    assertTrue(response.contains("saml2:Assertion"));
}

From source file:nl.eveoh.sakai.mytimetable.tool.ToolControllerTest.java

@Test
public void testError() throws Exception {
    // Exception should be handled by Sakai
    exception.expect(LocalizableException.class);

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

    Mockito.when(myTimetableService.getUpcomingEvents(Mockito.anyString()))
            .thenThrow(LocalizableException.class);

    toolController.handleRequest(request, response);
    Assert.assertEquals(200, response.getStatus());
}

From source file:org.wallride.job.UpdatePostViewsItemWriter.java

@Override
public void write(List<? extends List> items) throws Exception {
    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext,
            "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet");
    if (context == null) {
        throw new ServiceException("GuestServlet is not ready yet");
    }/*from w w w . jav  a 2s . co m*/

    final RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);

    for (List item : items) {
        UriComponents uriComponents = UriComponentsBuilder.fromUriString((String) item.get(0)).build();
        logger.info("Processing [{}]", uriComponents.toString());

        MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
        request.setMethod("GET");
        request.setRequestURI(uriComponents.getPath());
        request.setQueryString(uriComponents.getQuery());
        MockHttpServletResponse response = new MockHttpServletResponse();

        BlogLanguageRewriteRule rewriteRule = new BlogLanguageRewriteRule(blogService);
        BlogLanguageRewriteMatch rewriteMatch = (BlogLanguageRewriteMatch) rewriteRule.matches(request,
                response);
        try {
            rewriteMatch.execute(request, response);
        } catch (ServletException e) {
            throw new ServiceException(e);
        } catch (IOException e) {
            throw new ServiceException(e);
        }

        request.setRequestURI(rewriteMatch.getMatchingUrl());

        HandlerExecutionChain handler;
        try {
            handler = mapping.getHandler(request);
        } catch (Exception e) {
            throw new ServiceException(e);
        }

        if (!(handler.getHandler() instanceof HandlerMethod)) {
            continue;
        }

        HandlerMethod method = (HandlerMethod) handler.getHandler();
        if (!method.getBeanType().equals(ArticleDescribeController.class)
                && !method.getBeanType().equals(PageDescribeController.class)) {
            continue;
        }

        // Last path mean code of post
        String code = uriComponents.getPathSegments().get(uriComponents.getPathSegments().size() - 1);
        Post post = postRepository.findOneByCodeAndLanguage(code, rewriteMatch.getBlogLanguage().getLanguage());
        if (post == null) {
            logger.debug("Post not found [{}]", code);
            continue;
        }

        logger.info("Update the PageView. Post ID [{}]: {} -> {}", post.getId(), post.getViews(), item.get(1));
        post.setViews(Long.parseLong((String) item.get(1)));
        postRepository.saveAndFlush(post);
    }
}

From source file:edu.internet2.middleware.shibboleth.idp.system.conf1.SAML2SSOTestCase.java

protected MockHttpServletRequest buildServletRequest(String relyingPartyId) throws Exception {
    AuthnRequest authnRequest = buildAuthnRequest(relyingPartyId);
    String authnRequestString = getSamlRequestString(authnRequest);

    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    servletRequest.setMethod("POST");
    servletRequest.setPathInfo("/saml2/POST/SSO");
    servletRequest.setParameter("SAMLRequest", Base64.encodeBytes(authnRequestString.getBytes()));

    return servletRequest;
}

From source file:org.jasig.cas.web.support.InspektrThrottledSubmissionByIpAddressAndUsernameHandlerInterceptorAdapterTests.java

@Override
protected MockHttpServletResponse loginUnsuccessfully(final String username, final String fromAddress)
        throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    request.setMethod("POST");
    request.setParameter("username", username);
    request.setRemoteAddr(fromAddress);//from w ww.  j a v  a 2  s  .c  o m
    MockRequestContext context = new MockRequestContext();
    context.setCurrentEvent(new Event("", "error"));
    request.setAttribute("flowRequestContext", context);
    ClientInfoHolder.setClientInfo(new ClientInfo(request));

    getThrottle().preHandle(request, response, null);

    try {
        authenticationManager.authenticate(badCredentials(username));
    } catch (AuthenticationException e) {
        getThrottle().postHandle(request, response, null, null);
        return response;
    }
    fail("Expected AuthenticationException");
    return null;
}

From source file:de.tobiasbruns.content.storage.ContentControllerITCase.java

@Test
public void test12_uploadNewBinaryFile() throws Exception {
    InputStream testStream = TestUtils.loadFile("requests/testimg.jpeg");
    MockMultipartFile mockFile = new MockMultipartFile("file", "testimage.jpeg", "image/jpeg", testStream);

    MockMultipartHttpServletRequestBuilder builder = MockMvcRequestBuilders
            .fileUpload(BASE + "/folder/testimage.jpeg");
    builder.with(new RequestPostProcessor() {
        @Override//from w  w  w . j a  va  2  s.  co  m
        public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
            request.setMethod("PUT");
            return request;
        }
    });

    mockMvc.perform(builder.file(mockFile)).andExpect(status().is2xxSuccessful());
}

From source file:com.github.jrialland.ajpclient.servlet.TestServletProxy.java

@Test
public void doTestPost() throws Exception {

    final String cookie = slurp(TestServletProxy.class.getResource("cookie.txt").openStream());

    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setRequestURI("/test_post");
    request.addHeader("Host", "test.samplesite.com");

    request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    request.addHeader("Accept-Encoding", "gzip, deflate");
    request.addHeader("Accept-Language", "fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3");
    request.addHeader("Connection", "keep-alive");
    request.addHeader("Cookie", cookie);

    request.addHeader("Referer",
            "https://test.samplesite.com/fr/group/control_panel/manage?p_auth=1bo6fC5N&p_p_id=dbSettingsPortlet_WAR_eloportalservicesportlet&p_p_lifecycle=1&p_p_state=maximized&p_p_mode=view&doAsGroupId=10157&refererPlid=10160&_dbSettingsPortlet_WAR_eloportalservicesportlet_action=showUpdate&_dbSettingsPortlet_WAR_eloportalservicesportlet_client=TMG");
    request.addHeader("User-Agent",
            "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:32.0) Gecko/20100101 Firefox/32.0");
    request.addHeader("Content-Type", "application/x-www-form-urlencoded");
    request.setContent(//  w w  w. j  a v  a  2  s  .  c om
            "_dbSettingsPortlet_WAR_eloportalservicesportlet_client=xxx&_dbSettingsPortlet_WAR_eloportalservicesportlet_url=jdbc%3Ajtds%3Asqlserver%3A%2F%2Fxxx.xxx.xxx.xxx%2FBD_FR533&_dbSettingsPortlet_WAR_eloportalservicesportlet_user=sa&_dbSettingsPortlet_WAR_eloportalservicesportlet_password=123abcd+&_dbSettingsPortlet_WAR_eloportalservicesportlet_poolmax=5"
                    .getBytes());

    final MockHttpServletResponse response = new MockHttpServletResponse();
    AjpServletProxy.forHost("localhost", getPort()).forward(request, response);
    if (response.getStatus() != 200) {
        System.out.println(response.getContentAsString());
        Assert.fail(response.getErrorMessage());
    }

    Assert.assertEquals("5", response.getContentAsString());
}

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

@Test
public void testIsMultipart() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setRequestURI("/demo/controller/router");

    request.addHeader("Host", "eds.rasc.ch");
    request.addHeader("Connection", "keep-alive");
    request.addHeader("Content-Length", "8277");
    request.addHeader("Cache-Control", "max-age=0");
    request.addHeader("Origin", "http://eds.rasc.ch");
    request.addHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.75 Safari/537.1");
    request.addHeader("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryux6D0mMa2PlsY016");

    assertThat(ExtDirectSpringUtil.isMultipart(request)).isTrue();

    request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setRequestURI("/demo/controller/router");

    request.addHeader("Host", "eds.rasc.ch");
    request.addHeader("Connection", "keep-alive");
    request.addHeader("Content-Length", "165");
    request.addHeader("Origin", "http://eds.rasc.ch");
    request.addHeader("X-Requested-With", "XMLHttpRequest");
    request.addHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.75 Safari/537.1");
    request.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

    assertThat(ExtDirectSpringUtil.isMultipart(request)).isFalse();

    request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/demo/controller/router");
    request.addHeader("Host", "eds.rasc.ch");
    request.addHeader("Connection", "keep-alive");
    request.addHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.75 Safari/537.1");

    assertThat(ExtDirectSpringUtil.isMultipart(request)).isFalse();

}

From source file:org.n52.sos.service.it.MockHttpClient.java

private MockHttpServletRequest build() {
    try {/*from   w w  w.ja  v  a  2 s  .  c  om*/
        final MockHttpServletRequest req = new MockHttpServletRequest(context);
        req.setMethod(method);
        for (String header : headers.keySet()) {
            for (String value : headers.get(header)) {
                req.addHeader(header, value);
            }
        }
        final StringBuilder queryString = new StringBuilder();
        if (query != null && !query.isEmpty()) {
            boolean first = true;
            for (String key : query.keySet()) {
                final Set<String> values = query.get(key);
                req.addParameter(key, values.toArray(new String[values.size()]));
                if (first) {
                    queryString.append("?");
                    first = false;
                } else {
                    queryString.append("&");
                }
                queryString.append(key).append("=");
                Iterator<String> i = values.iterator();
                queryString.append(i.next());
                while (i.hasNext()) {
                    queryString.append(",").append(i.next());
                }
            }
            req.setQueryString(queryString.toString());
        }
        req.setRequestURI(path + queryString.toString());
        if (path == null) {
            path = "/";
        }
        req.setPathInfo(path);
        if (content != null) {
            req.setContent(content.getBytes(MockHttpExecutor.ENCODING));
        }
        return req;
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    }
}