Example usage for javax.servlet.http HttpServletRequest getServletContext

List of usage examples for javax.servlet.http HttpServletRequest getServletContext

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getServletContext.

Prototype

public ServletContext getServletContext();

Source Link

Document

Gets the servlet context to which this ServletRequest was last dispatched.

Usage

From source file:com.fujitsu.dc.test.unit.core.jersey.filter.DcCoreContainerFilterTest.java

/**
 * ???/???????./*  w  ww  . jav  a2 s  . c o m*/
 * X-FORWARDED-PROTO?X-FORWARDED-HOST?Uri, Base Uri?PROTO, HOST????????
 * @throws URISyntaxException URISyntaxException
 */
@Test
public void testFilterContainerRequest() throws URISyntaxException {
    // 
    DcCoreContainerFilter containerFilter = new DcCoreContainerFilter();
    // ContainerRequiest
    WebApplication wa = mock(WebApplication.class);
    InBoundHeaders headers = new InBoundHeaders();
    // ?
    headers.add(DcCoreUtils.HttpHeaders.X_HTTP_METHOD_OVERRIDE, HttpMethod.OPTIONS);
    // ?
    String authzValue = "Bearer tokenstring";
    String acceptValue = "text/html";
    String contentTypeValue = "application/xml";
    headers.add(DcCoreUtils.HttpHeaders.X_OVERRIDE, HttpHeaders.AUTHORIZATION + ": " + authzValue);
    headers.add(HttpHeaders.ACCEPT, contentTypeValue);
    headers.add(DcCoreUtils.HttpHeaders.X_OVERRIDE, HttpHeaders.ACCEPT + ": " + acceptValue);
    headers.add(HttpHeaders.CONTENT_TYPE, contentTypeValue);

    // X-FORWARDED-* ?
    String scheme = "https";
    String host = "example.org";
    headers.add(DcCoreUtils.HttpHeaders.X_FORWARDED_PROTO, scheme);
    headers.add(DcCoreUtils.HttpHeaders.X_FORWARDED_HOST, host);

    ContainerRequest request = new ContainerRequest(wa, HttpMethod.POST, new URI("http://dc1.example.com/hoge"),
            new URI("http://dc1.example.com/hoge/hoho"), headers, null);

    // HttpServletRequest?mock
    HttpServletRequest mockServletRequest = mock(HttpServletRequest.class);
    when(mockServletRequest.getRequestURL()).thenReturn(new StringBuffer("http://dc1.example.com"));

    ServletContext mockServletContext = mock(ServletContext.class);
    when(mockServletContext.getContextPath()).thenReturn("");
    when(mockServletRequest.getServletContext()).thenReturn(mockServletContext);
    containerFilter.setHttpServletRequest(mockServletRequest);

    // ??
    ContainerRequest filteredRequest = containerFilter.filter(request);

    // ??
    Assert.assertEquals(HttpMethod.OPTIONS, filteredRequest.getMethod());
    Assert.assertEquals(authzValue, filteredRequest.getHeaderValue(HttpHeaders.AUTHORIZATION));
    Assert.assertEquals(acceptValue, filteredRequest.getHeaderValue(HttpHeaders.ACCEPT));

    Assert.assertEquals(contentTypeValue, filteredRequest.getHeaderValue(HttpHeaders.CONTENT_TYPE));
    Assert.assertEquals(scheme, filteredRequest.getRequestUri().getScheme());
    Assert.assertEquals(host, filteredRequest.getRequestUri().getHost());
}

From source file:io.personium.test.unit.core.jersey.filter.PersoniumCoreContainerFilterTest.java

/**
 * ???/???????./*from   w ww.  ja v a  2 s  . c o m*/
 * X-FORWARDED-PROTO?X-FORWARDED-HOST?Uri, Base Uri?PROTO, HOST????????
 * @throws URISyntaxException URISyntaxException
 */
@Test
public void testFilterContainerRequest() throws URISyntaxException {
    // 
    PersoniumCoreContainerFilter containerFilter = new PersoniumCoreContainerFilter();
    // ContainerRequiest
    WebApplication wa = mock(WebApplication.class);
    InBoundHeaders headers = new InBoundHeaders();
    // ?
    headers.add(PersoniumCoreUtils.HttpHeaders.X_HTTP_METHOD_OVERRIDE, HttpMethod.OPTIONS);
    // ?
    String authzValue = "Bearer tokenstring";
    String acceptValue = "text/html";
    String contentTypeValue = "application/xml";
    headers.add(PersoniumCoreUtils.HttpHeaders.X_OVERRIDE, HttpHeaders.AUTHORIZATION + ": " + authzValue);
    headers.add(HttpHeaders.ACCEPT, contentTypeValue);
    headers.add(PersoniumCoreUtils.HttpHeaders.X_OVERRIDE, HttpHeaders.ACCEPT + ": " + acceptValue);
    headers.add(HttpHeaders.CONTENT_TYPE, contentTypeValue);

    // X-FORWARDED-* ?
    String scheme = "https";
    String host = "example.org";
    headers.add(PersoniumCoreUtils.HttpHeaders.X_FORWARDED_PROTO, scheme);
    headers.add(PersoniumCoreUtils.HttpHeaders.X_FORWARDED_HOST, host);

    ContainerRequest request = new ContainerRequest(wa, HttpMethod.POST, new URI("http://dc1.example.com/hoge"),
            new URI("http://dc1.example.com/hoge/hoho"), headers, null);

    // HttpServletRequest?mock
    HttpServletRequest mockServletRequest = mock(HttpServletRequest.class);
    when(mockServletRequest.getRequestURL()).thenReturn(new StringBuffer("http://dc1.example.com"));

    ServletContext mockServletContext = mock(ServletContext.class);
    when(mockServletContext.getContextPath()).thenReturn("");
    when(mockServletRequest.getServletContext()).thenReturn(mockServletContext);
    containerFilter.setHttpServletRequest(mockServletRequest);

    // ??
    ContainerRequest filteredRequest = containerFilter.filter(request);

    // ??
    Assert.assertEquals(HttpMethod.OPTIONS, filteredRequest.getMethod());
    Assert.assertEquals(authzValue, filteredRequest.getHeaderValue(HttpHeaders.AUTHORIZATION));
    Assert.assertEquals(acceptValue, filteredRequest.getHeaderValue(HttpHeaders.ACCEPT));

    Assert.assertEquals(contentTypeValue, filteredRequest.getHeaderValue(HttpHeaders.CONTENT_TYPE));
    Assert.assertEquals(scheme, filteredRequest.getRequestUri().getScheme());
    Assert.assertEquals(host, filteredRequest.getRequestUri().getHost());
}

From source file:com.ayu.filter.CheckFilter.java

/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */// w  ww  .  ja va  2s.  c  o m
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    String str = req.getHeader("X-FORWARDED-FOR");
    if (str == null) {
        str = request.getRemoteAddr();
    }
    if (req.getServletContext().getAttribute("regService") == null) {
        req.getServletContext().setAttribute("regService", regService);
    }
    if (lruCache.map.isEmpty()) {
        //System.out.println("It is empty");
        lruCache.map.put(str, new Timer(db.time));
        chain.doFilter(request, response);
    }
    if (lruCache.map.containsKey(str)) {
        t = lruCache.map.get(str);
        t.count++;
        lruCache.map.put(str, t);
    } else {
        lruCache.map.put(str, new Timer(db.time));
    }
    /**
    for (Map.Entry<String,Timer> e : lruCache.getAll()){
    if(e.getKey().equals(str))
    {   
       t = e.getValue();
       e.getValue().count++;
       lruCache.map.put(str,t);
               
               
    }
    else
    {
       if(lruCache.map.containsKey(str))
       {
          t1 = lruCache.map.get(str);
          t1.count++;
          lruCache.map.put(str,t1);
       }
       else{
       //lruCache.map.remove(e.getKey());
       lruCache.map.put(str,new Timer());
       }
    }
            
    }**/
    if (t.count > timer) {
        time = System.currentTimeMillis();
        //System.out.println(t.check(time)+"1");   
        if (t.check(time) == true) { //System.out.println("OK");
            if (req.getServletContext().getAttribute(str) == null) {

                req.getServletContext().setAttribute(str, str);
                regService.registerUser(str, new Date().toString(), "DDOS  Attacks", "test");
                regService.camCall(str);
                regService.sendSSLMail("An Attack Has Occured.Please Check your System for DDOS attacks",
                        "clouddefenceids@gmail.com");
                lruCache.map.put(str, new Timer(db.time));
                //System.out.println((String) req.getServletContext().getAttribute("IP"));
                //System.out.println(t.check(time)+"2");   
                res.sendError(HttpServletResponse.SC_FORBIDDEN, "You Are Perceived as a Threat");
            } else {
                /*regService.registerUser(str,new Date().toString());
                lruCache.map.put(str,new Timer(db.time));//This will add to database even if it attacked even once.. So not reqd to save resources as attacker is in DB */
                chain.doFilter(request, response);
            }
        } else if (t.check(time) == false) {
            //System.out.println("Not Ok");
            //System.out.println(t.check(time)+"3");   
            lruCache.map.put(str, new Timer(db.time));
            //System.out.println(new Timer().count);
            chain.doFilter(request, response);
        }

    } else {
        //System.out.println(t.check(time)+"4");   
        // pass the request along the filter chain
        chain.doFilter(request, response);
    }

}

From source file:com.test.springmvc.springmvcproject.UploadController.java

@RequestMapping(value = "", method = RequestMethod.POST)
public String addNewBook(final javax.servlet.http.HttpServletRequest request, @Valid BookBean bean,
        BindingResult result, ModelMap map, final HttpSession session) {
    //si erreur, on renvoie direct sur la page
    if (result.hasErrors()) {
        return "upload/newBook";
    }//from  w  w  w  . j  a  va 2 s. c o  m
    final String contextRoot = request.getServletContext().getRealPath("");
    final String contextPath = request.getContextPath();
    final String dossier_uploads = "uploads";
    final String dossier_default = "images";
    final String image_default = "default.png";

    final String uri_couverture_default = contextPath + "/" + dossier_default + "/" + image_default;
    //creation url totale pour la sauvegarde physique
    final String url_to_book = contextRoot + "/" + dossier_uploads + "/" + bean.getAuteur();
    //creation url relative pour sauvegarder l'emplacement des donnees
    final String uri_to_book = contextPath + "/" + dossier_uploads + "/" + bean.getAuteur();

    final String url_finale_livre = url_to_book + "/" + bean.getFichier().getOriginalFilename();
    final String url_relative_livre = uri_to_book + "/" + bean.getFichier().getOriginalFilename();
    //on ajoute l'emplacement final au bean book
    bean.setEmplacement(url_relative_livre);
    //on ajoute le nom du fichier au bean
    bean.setNomLivre(bean.getFichier().getOriginalFilename());

    if (!bean.getCouverture().isEmpty()) {
        final String url_relative_couverture = uri_to_book + "/" + bean.getCouverture().getOriginalFilename();
        bean.setEmplacementCouverture(url_relative_couverture);
    } else {
        bean.setEmplacementCouverture(uri_couverture_default);
    }
    final String url_finale_couverture = url_to_book + "/" + bean.getCouverture().getOriginalFilename();

    final File livre = new File(url_finale_livre);
    final File couverture = new File(url_finale_couverture);
    try {
        livre.getParentFile().mkdirs();
        bean.getFichier().transferTo(livre);
        if (!bean.getCouverture().isEmpty()) {
            bean.getCouverture().transferTo(couverture);
        }

        //recuperation de l'utilisateur
        UtilisateurBean utilisateur = (UtilisateurBean) session.getAttribute("utilisateur");
        //si pas d'utilisateur, on recupere l'anonyme
        if (null == utilisateur) {
            try {
                utilisateur = utilisateurService.get("anonyme@anonyme.com");
            } catch (NoDataFoundException e) {
                result.addError(new FieldError("BookBean", "fichier", "Une erreur interne est apparue."));
            }
        }
        //creation entree en base
        try {
            service.createEntry(bean, utilisateur);
        } catch (BookAlreadyExistsException e) {
            result.addError(new FieldError("BookBean", "fichier", "Livre deja existant"));
            return "upload/newBook";
        }
    } catch (IOException e) {
        result.addError(new FieldError("BookBean", "fichier",
                "Une erreur est survenue lors du transfert." + e.getMessage()));
        return "upload/newBook";
    }

    return "redirect:/index.do";
}

From source file:org.b3log.solo.processor.ArticleProcessorTestCase.java

/**
 * getArticlesByPage.//from  ww w  .j a va  2  s  . c o m
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void getArticlesByPage() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/articles/1");
    when(request.getMethod()).thenReturn("GET");
    when(request.getAttribute(Keys.TEMAPLTE_DIR_NAME)).thenReturn("next");
    when(request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS)).thenReturn(System.currentTimeMillis());

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    Assert.assertTrue(StringUtils.contains(content, "{\"sc\":true"));
}

From source file:org.b3log.solo.processor.ArticleProcessorTestCase.java

/**
 * getRandomArticles.// w  w w  . java2s .c om
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void getRandomArticles() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/get-random-articles.do");
    when(request.getMethod()).thenReturn("POST");
    when(request.getAttribute(Keys.TEMAPLTE_DIR_NAME)).thenReturn("next");
    when(request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS)).thenReturn(System.currentTimeMillis());

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    Assert.assertTrue(StringUtils.contains(content, "{\"randomArticles"));
}

From source file:org.b3log.solo.processor.ArticleProcessorTestCase.java

/**
 * getTagArticlesByPage.// ww w.j av  a 2 s . c  o  m
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void getTagArticlesByPage() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/articles/tags/Solo/1");
    when(request.getMethod()).thenReturn("GET");
    when(request.getAttribute(Keys.TEMAPLTE_DIR_NAME)).thenReturn("next");
    when(request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS)).thenReturn(System.currentTimeMillis());

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    Assert.assertTrue(StringUtils.contains(content, "{\"sc\":true"));
}

From source file:org.b3log.solo.processor.ArticleProcessorTestCase.java

/**
 * getArchivesArticlesByPage.//from ww  w  .j av a2 s .c  o  m
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void getArchivesArticlesByPage() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn(
            "/articles/archives/" + DateFormatUtils.format(System.currentTimeMillis(), "yyyy/MM") + "/1");
    when(request.getMethod()).thenReturn("GET");
    when(request.getAttribute(Keys.TEMAPLTE_DIR_NAME)).thenReturn("next");
    when(request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS)).thenReturn(System.currentTimeMillis());

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    Assert.assertTrue(StringUtils.contains(content, "{\"sc\":true"));
}

From source file:org.b3log.solo.processor.ArticleProcessorTestCase.java

/**
 * showArchiveArticles./*  w  w  w  . j a v  a  2s . com*/
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void showArchiveArticles() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI())
            .thenReturn("/archives/" + DateFormatUtils.format(System.currentTimeMillis(), "yyyy/MM") + "/1");
    when(request.getMethod()).thenReturn("GET");
    when(request.getAttribute(Keys.TEMAPLTE_DIR_NAME)).thenReturn("next");
    when(request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS)).thenReturn(System.currentTimeMillis());

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    Assert.assertTrue(StringUtils.contains(content, "Solo </title>"));
}

From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java

@Path("download2")
@GET//w  w  w  .j av a2  s .  c o m
public Response downloadFile(@Context HttpServletResponse response, @Context HttpServletRequest request)
        throws IOException {
    final File file = new File(request.getServletContext().getRealPath("index.html"));
    final InputStream responseStream = new FileInputStream(file);
    StreamingOutput output = new StreamingOutput() {
        @Override
        public void write(OutputStream out) throws IOException, WebApplicationException {
            try {
                int length;
                byte[] buffer = new byte[1024 * 10];
                while ((length = responseStream.read(buffer)) != -1) {
                    out.write(buffer, 0, length);
                    out.flush();
                }
            } finally {
                responseStream.close();
                //file.delete();
            }
        }
    };

    String filename = file.getName();
    String userAgent = request.getHeader("User-Agent");
    //IE11 User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
    //IE6~IE10User-Agent:Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.0; Trident/6.0)

    if (userAgent != null
            && (userAgent.toLowerCase().indexOf("msie") > 0 || userAgent.indexOf("like Gecko") > 0)) {
        filename = URLEncoder.encode(filename, "UTF-8");//IE?
    } else {
        //??,????utf-8,????,
        //?????
        filename = new String(filename.replaceAll(" ", "").getBytes(), "ISO8859-1");
        //firefox?
        //firefox?User-Agent: 
        //Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0
    }
    //http://blog.csdn.net/candyguy242/article/details/17449191
    return Response.ok(output)
            .header("Content-Disposition",
                    "attachment; filename=" + filename + ";filename*=UTF-8''"
                            + URLEncoder.encode(file.getName(), "UTF-8").replace("+", "%20"))
            .encoding("UTF-8").build();
}