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:org.apache.syncope.ext.saml2lsp.agent.Logout.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    String samlResponse = request.getParameter(SSOConstants.SAML_RESPONSE);
    String relayState = request.getParameter(SSOConstants.RELAY_STATE);
    if (samlResponse == null) { // prepare logout response
        SyncopeClientFactoryBean clientFactory = (SyncopeClientFactoryBean) request.getServletContext()
                .getAttribute(Constants.SYNCOPE_CLIENT_FACTORY);
        try {/*from w  w w  . j  av a 2s  .  c om*/
            String accessToken = (String) request.getSession().getAttribute(Constants.SAML2SPJWT);
            if (StringUtils.isBlank(accessToken)) {
                throw new IllegalArgumentException("No access token found ");
            }

            SyncopeClient client = clientFactory.create(accessToken);
            SAML2RequestTO requestTO = client.getService(SAML2SPService.class).createLogoutRequest(
                    StringUtils.substringBefore(request.getRequestURL().toString(), "/saml2sp"));

            prepare(response, requestTO);
        } catch (Exception e) {
            LOG.error("While preparing logout request to IdP", e);

            String errorURL = getServletContext().getInitParameter(Constants.CONTEXT_PARAM_LOGOUT_ERROR_URL);
            if (errorURL == null) {
                request.setAttribute("exception", e);
                request.getRequestDispatcher("logoutError.jsp").forward(request, response);

                e.printStackTrace(response.getWriter());
            } else {
                response.sendRedirect(errorURL + "?errorMessage="
                        + URLEncoder.encode(e.getMessage(), StandardCharsets.UTF_8.name()));
            }
        }
    } else { // process REDIRECT binding logout response
        SAML2ReceivedResponseTO receivedResponse = new SAML2ReceivedResponseTO();
        receivedResponse.setSamlResponse(samlResponse);
        receivedResponse.setRelayState(relayState);

        doLogout(receivedResponse, request, response);
    }
}

From source file:nl.opengeogroep.dbk.DBKAPI.java

/**
 * Processes the request for retrieving the media belonging to a DBK.
 * @param method The part of the url after /api/, containing the file name (and possible subdirectory)
 * @param request The http request//from w  ww  . j a v  a 2s.c  o m
 * @param response The http response
 * @param out The outputstream to which the file must be written.
 * @throws IOException 
 */
private void processMedia(String method, HttpServletRequest request, HttpServletResponse response,
        OutputStream out) throws IOException {
    FileInputStream fis = null;
    File requestedFile = null;
    String basePath = request.getServletContext().getInitParameter("dbk.media.path");
    try {
        String fileArgument = method.substring(method.indexOf(MEDIA) + MEDIA.length());
        String totalPath = basePath + File.separatorChar + fileArgument;

        totalPath = URLDecoder.decode(totalPath, response.getCharacterEncoding());
        requestedFile = new File(totalPath);

        fis = new FileInputStream(requestedFile);
        response.setContentType(request.getServletContext().getMimeType(totalPath));
        Long size = requestedFile.length();
        response.setContentLength(size.intValue());
        IOUtils.copy(fis, out);
    } catch (IOException ex) {
        log.error("Error retrieving media.", ex);
        if (requestedFile != null) {
            log.error("Cannot load media: " + requestedFile.getCanonicalPath() + " from basePath: " + basePath);
        }
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
}

From source file:alfio.util.TemplateManager.java

public String renderServletContextResource(String servletContextResource, Map<String, Object> model,
        HttpServletRequest request, TemplateOutput templateOutput) {
    model.put("request", request);
    model.put(WebSecurityConfig.CSRF_PARAM_NAME, request.getAttribute(CsrfToken.class.getName()));
    return render(new ServletContextResource(request.getServletContext(), servletContextResource), model,
            RequestContextUtils.getLocale(request), templateOutput);
}

From source file:org.apdplat.superword.system.AntiRobotFilter.java

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;

    if (request.getRequestURI().endsWith("/favicon.ico")) {
        chain.doFilter(req, resp);/* w  ww . j a  v a  2  s .c  o m*/
        return;
    }

    if (servletContext == null) {
        servletContext = request.getServletContext();
    }

    HttpServletResponse response = (HttpServletResponse) resp;
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");

    String userAgent = request.getHeader("User-Agent");
    if (StringUtils.isBlank(userAgent) || userAgent.length() < 50 || userAgent.contains("Java")
            || userAgent.contains("bingbot") || userAgent.contains("360Spider")
            || userAgent.contains("HaosouSpider") || userAgent.contains("Googlebot")) {
        invalidCount++;
        response.getWriter().write(
                "Superword is a Java open source project dedicated in the study of English words analysis and auxiliary reading, including but not limited to, spelling similarity, definition similarity, pronunciation similarity, the transformation rules of the spelling, the prefix and the dynamic prefix, the suffix and the dynamic suffix, roots, compound words, text auxiliary reading, web page auxiliary reading, book auxiliary reading, etc..");
        return;
    }

    HttpSession session = request.getSession(true);
    if (session.getAttribute("isHuman") == null) {
        AtomicInteger identifyCount = (AtomicInteger) session.getAttribute("identifyCount");
        if (identifyCount == null) {
            identifyCount = new AtomicInteger();
            session.setAttribute("identifyCount", identifyCount);
        }
        identifyCount.incrementAndGet();
        if (identifyCount.intValue() > 200) {
            response.getWriter().write(
                    "System has detected that you may not be a human, because you can't answer the question correctly.");
            return;
        }

        if (session.getAttribute("forward") == null) {
            session.setAttribute("forward",
                    StringUtils.isBlank(request.getPathInfo()) ? "/" : request.getPathInfo());
        }

        String _token = request.getParameter("token");
        String _word = request.getParameter("word");
        String _answer = request.getParameter("answer");
        if (StringUtils.isNotBlank(_token) && StringUtils.isNotBlank(_word) && StringUtils.isNotBlank(_answer)
                && session.getAttribute("token") != null
                && session.getAttribute("token").toString().equals(_token)
                && session.getAttribute("quizItem") != null) {
            session.setAttribute("token", null);
            QuizItem quizItem = (QuizItem) session.getAttribute("quizItem");
            if (_word.equals(quizItem.getWord().getWord())) {
                quizItem.setAnswer(_answer);
                if (quizItem.isRight()) {
                    String path = session.getAttribute("forward").toString();
                    if (path.contains("identify.quiz")) {
                        path = path.replace("identify.quiz", "");
                    }
                    session.setAttribute("forward", null);
                    session.setAttribute("isHuman", "true");
                    request.getRequestDispatcher(path).forward(request, response);
                    return;
                } else {
                    Set<String> wrongWordsInQuiz = (Set<String>) session.getAttribute("wrong_words_in_quiz");
                    if (wrongWordsInQuiz == null) {
                        wrongWordsInQuiz = new HashSet<>();
                        session.setAttribute("wrong_words_in_quiz", wrongWordsInQuiz);
                    }
                    wrongWordsInQuiz.add(quizItem.getWord().getWord());

                    StringBuilder html = new StringBuilder();
                    html.append(
                            "<h1>The meaning of red color font is your answer, but the right answer is the meaning of blue color font for the word <font color=\"red\">")
                            .append(quizItem.getWord().getWord()).append(":</font></h1>");
                    html.append("<h2><ul>");
                    for (String option : quizItem.getMeanings()) {
                        html.append("<li>");
                        if (option.equals(_answer)) {
                            html.append("<font color=\"red\">").append(option).append("</font>");
                        } else if (option.equals(quizItem.getWord().getMeaning())) {
                            html.append("<font color=\"blue\">").append(option).append("</font>");
                        } else {
                            html.append(option);
                        }
                        html.append("</li>\n");
                    }
                    html.append("</ul></h2>\n<h1><a href=\"").append(servletContext.getContextPath())
                            .append("\">Continue...</a></h1>\n");
                    response.getWriter().write(html.toString());
                    return;
                }
            }
        }

        QuizItem quizItem = QuizItem.buildIdentifyHumanQuiz(12);
        String token = UUID.randomUUID().toString();
        session.setAttribute("quizItem", quizItem);
        session.setAttribute("token", token);
        StringBuilder html = new StringBuilder();
        html.append("<h1>").append("Click the correct meaning for the word <font color=\"red\">")
                .append(quizItem.getWord().getWord()).append(":</font></h1>\n");
        html.append("<h2><ul>");
        for (String option : quizItem.getMeanings()) {
            html.append("<li>").append("<a href=\"").append(servletContext.getContextPath())
                    .append("/identify.quiz?word=").append(quizItem.getWord().getWord()).append("&token=")
                    .append(token).append("&answer=").append(URLEncoder.encode(option, "utf-8")).append("\">")
                    .append(option).append("</a></li>\n");
        }
        html.append("</ul></h2>\n").append(
                "<h1>If you can't answer the question correctly, you won't have the permission to access the web site.")
                .append("</h1>");
        response.getWriter().write(html.toString());
        return;
    }

    String key = getKey(request);
    AtomicInteger count = (AtomicInteger) servletContext.getAttribute(key);
    if (count == null) {
        count = new AtomicInteger();
        servletContext.setAttribute(key, count);
    }

    if (count.incrementAndGet() > limit) {
        response.getWriter().write(
                "System has detected that your IP visit is too frequent and has automatically forbidden your vist. We are sorry to bring inconvenience to you, please understand, please come back tomorrow. Bye Bye!");

        return;
    }

    chain.doFilter(req, resp);
}

From source file:io.lavagna.web.support.ResourceController.java

/**
 * Dynamically load and concatenate the js present in the configured directories
 *
 * @param request/*from  w w  w . ja  v  a  2 s.  c om*/
 * @param response
 * @throws IOException
 */
@RequestMapping(value = "/resource/app-{version:.+}.js", method = RequestMethod.GET)
public void handleJs(HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (contains(env.getActiveProfiles(), "dev") || jsCache.get() == null) {
        ServletContext context = request.getServletContext();
        response.setContentType("text/javascript");
        BeforeAfter ba = new JS();
        ByteArrayOutputStream allJs = new ByteArrayOutputStream();

        //
        for (String res : Arrays.asList("/js/angular-file-upload-html5-shim.js", //
                "/js/angular.min.js", "/js/angular-sanitize.min.js", //
                //
                "/js/angular-animate.min.js", "/js/angular-aria.min.js", "/js/angular-messages.min.js",
                "/js/angular-material.min.js",
                //
                "/js/angular-ui-router.min.js", //
                "/js/angular-file-upload.min.js", //
                "/js/angular-translate.min.js", //
                "/js/angular-avatar.min.js", //

                //
                "/js/d3.v3.min.js", "/js/cal-heatmap.min.js", //

                "/js/highlight.pack.js", //
                "/js/marked.js", //
                "/js/Sortable.js", //
                "/js/sockjs.min.js", "/js/stomp.min.js", //
                //
                "/js/search-parser.js", //
                "/js/moment.min.js", //
                "/js/Chart.min.js")) {
            output(res, context, allJs, ba);
        }
        //

        //
        addMessages(context, allJs, ba);
        //

        //
        //concatenateResourcesWithExtension(context, "/app/app.js", ".js", allJs, ba);
        output("/app/app.js", context, allJs, ba);
        concatenateResourcesWithExtension(context, "/app/controllers/", ".js", allJs, ba);
        concatenateResourcesWithExtension(context, "/app/components/", ".js", allJs, ba);
        concatenateResourcesWithExtension(context, "/app/directives/", ".js", allJs, ba);
        concatenateResourcesWithExtension(context, "/app/filters/", ".js", allJs, ba);
        concatenateResourcesWithExtension(context, "/app/services/", ".js", allJs, ba);
        //

        jsCache.set(allJs.toByteArray());
    }

    try (OutputStream os = response.getOutputStream()) {
        response.setContentType("text/javascript");
        StreamUtils.copy(jsCache.get(), os);
    }
}

From source file:edu.csudh.goTorosBank.WithdrawServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //File blueCheck = new File("blank-blue-check.jpg");
    File blueCheck = new File(request.getParameter("filename"));
    String pathToWeb = getServletContext().getRealPath("/" + blueCheck);

    ServletContext cntx = request.getServletContext();
    String mime = cntx.getMimeType(pathToWeb);

    response.setContentType(mime);/*  w  ww.j av a2 s  .  com*/
    try {
        File file = new File(pathToWeb);
        response.setContentLength((int) file.length());

        FileInputStream in = new FileInputStream(file);
        OutputStream out = response.getOutputStream();

        // Copy the contents of the file to the output stream
        byte[] buf = new byte[1024];
        int count;
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        out.close();
        in.close();

        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + blueCheck.getName() + "\"");//fileName;
    } catch (Exception e) {
        response.getWriter().write(e.getMessage());
    }

}

From source file:br.com.ifpb.bdnc.projeto.geo.system.MultipartData.java

public String processFile(HttpServletRequest request) throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {/*from www  .j  a  v  a  2 s  .c o  m*/
            FileItemIterator itr = upload.getItemIterator(request);

            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (!item.isFormField()) {
                    String path = request.getServletContext().getRealPath("/");
                    String nameToSave = "profileImage" + Calendar.getInstance().getTimeInMillis()
                            + item.getName();
                    if (saveImage(path + "/userImages", item, nameToSave)) {
                        return folder + "/" + nameToSave;
                    }
                }
            }

        } catch (FileUploadException ex) {
            System.out.println("erro ao obter informaoes sobre o arquivo");
        }

    } else {
        System.out.println("Erro no formulario!");
    }

    return null;
}

From source file:com.mingsoft.basic.servlet.UploadServlet.java

/**
 * ?post//  w  w w  .j a va  2 s. com
 * @param req HttpServletRequest
 * @param res HttpServletResponse 
 * @throws ServletException ?
 * @throws IOException ?
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html;charset=utf-8");
    PrintWriter out = res.getWriter();
    String uploadPath = this.getServletContext().getRealPath(File.separator); // 
    String isRename = "";// ???? true:???
    String _tempPath = req.getServletContext().getRealPath(File.separator) + "temp";//
    FileUtil.createFolder(_tempPath);
    File tempPath = new File(_tempPath); // 

    int maxSize = 1000000; // ??,?? 1000000/1024=0.9M
    //String allowedFile = ".jpg,.gif,.png,.zip"; // ?
    String deniedFile = ".exe,.com,.cgi,.asp"; // ??

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    // ?????
    factory.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    // ?SizeThreshold?
    factory.setRepository(tempPath);

    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum size before a FileUploadException will be thrown

    try {
        List fileItems = upload.parseRequest(req);

        Iterator iter = fileItems.iterator();

        // ????
        String regExp = ".+\\\\(.+)$";

        // 
        String[] errorType = deniedFile.split(",");
        Pattern p = Pattern.compile(regExp);
        String outPath = ""; //??
        while (iter.hasNext()) {

            FileItem item = (FileItem) iter.next();
            if (item.getFieldName().equals("uploadPath")) {
                outPath += item.getString();
                uploadPath += outPath;
            } else if (item.getFieldName().equals("isRename")) {
                isRename = item.getString();
            } else if (item.getFieldName().equals("maxSize")) {
                maxSize = Integer.parseInt(item.getString()) * 1048576;
            } else if (item.getFieldName().equals("allowedFile")) {
                //               allowedFile = item.getString();
            } else if (item.getFieldName().equals("deniedFile")) {
                deniedFile = item.getString();
            } else if (!item.isFormField()) { // ???
                String name = item.getName();
                long size = item.getSize();
                if ((name == null || name.equals("")) && size == 0)
                    continue;
                try {
                    // ?? 1000000/1024=0.9M
                    upload.setSizeMax(maxSize);

                    // ?
                    // ?
                    String fileName = System.currentTimeMillis() + name.substring(name.indexOf("."));
                    String savePath = uploadPath + File.separator;
                    FileUtil.createFolder(savePath);
                    // ???
                    if (StringUtil.isBlank(isRename) || Boolean.parseBoolean(isRename)) {
                        savePath += fileName;
                        outPath += fileName;
                    } else {
                        savePath += name;
                        outPath += name;
                    }
                    item.write(new File(savePath));
                    out.print(outPath.trim());
                    logger.debug("upload file ok return path " + outPath);
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    this.logger.debug(e);
                }

            }
        }
    } catch (FileUploadException e) {
        this.logger.debug(e);
    }
}

From source file:com.portal.controller.AdminController.java

@RequestMapping(value = "/employes/create", method = RequestMethod.POST)
public String submitCreateEmployee(HttpServletRequest request,
        @ModelAttribute("employeedto") EmployeeDTO employeedto,
        @RequestParam(value = "avatarFile", required = false) MultipartFile avatar) throws Exception {

    Employee employee = new Employee();

    if (!avatar.isEmpty() && avatar.getContentType().equals("image/jpeg")) {
        portalService.saveFile(// w  ww .  j  av  a  2 s.co m
                request.getServletContext().getRealPath("/template/img/") + "/" + avatar.getOriginalFilename(),
                avatar);
        employee.setAvatar(avatar.getOriginalFilename());
    }

    if (employeedto.getName() == null || employeedto.getName().trim().length() == 0
            || employeedto.getPosition() == 0 || employeedto.getDepartment() == 0) {
        return "redirect:/admin/employes";
    }

    employee.setName(employeedto.getName());
    employee.setDepartment(portalService.getDepartment(employeedto.getDepartment()));
    employee.setPosition(portalService.getPosition(employeedto.getPosition()));
    employee.setPhone(employeedto.getPhone());
    employee.setEmail(employeedto.getEmail());
    employee.setDescription(employeedto.getDescription());

    portalService.saveEmployee(employee);
    return "redirect:/admin/employes";
}

From source file:cn.itcast.bbs.controller.BbsServlet.java

private void exit(HttpServletRequest request, HttpServletResponse response) throws IOException {
    //?//from w w w.  ja  v  a  2 s .c om
    List<String> usernameList = (List<String>) request.getServletContext().getAttribute("usernameList");
    for (String str : usernameList) {
        System.out.println(str);
    }
    //?sessionuser
    User user = (User) request.getSession().getAttribute("user");
    //
    usernameList.remove(user.getUsername());
    //
    request.getSession().removeAttribute("user");
    request.getSession().invalidate();
    response.sendRedirect(request.getContextPath());
}