Example usage for javax.servlet.http HttpServletRequest getServletPath

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

Introduction

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

Prototype

public String getServletPath();

Source Link

Document

Returns the part of this request's URL that calls the servlet.

Usage

From source file:com.sibvisions.rad.server.security.spring.SecurityManagerEntryPoint.java

/**
 * {@inheritDoc}/*from   w w  w .j  a va2s .  c  o m*/
 */
public void commence(HttpServletRequest pRequest, HttpServletResponse pResponse,
        AuthenticationException pAuthException) throws IOException, ServletException {
    if (pAuthException != null) {
        HttpSession session = pRequest.getSession(false);

        if (session != null) {
            String path = pRequest.getServletPath();

            if (path != null && securedPaths != null) {
                for (int i = 0; i < securedPaths.length; i++) {
                    if (path.equals(securedPaths[i]) || (securedPaths[i].endsWith("*")
                            && path.startsWith(securedPaths[i].substring(0, securedPaths[i].length() - 1)))) {
                        if (delegateForbiddenEntryPoint != null) {
                            delegateForbiddenEntryPoint.commence(pRequest, pResponse, pAuthException);
                        }

                        return;
                    }
                }
            }
        }
    }

    if (delegateEntryPoint != null) {
        delegateEntryPoint.commence(pRequest, pResponse, pAuthException);
    }
}

From source file:uk.co.postoffice.spike.esi.helloworld.ThymeleafMasterLayoutViewResolver.java

private boolean isAjaxRequest(HttpServletRequest request) {
    String requestedWithHeader = request.getHeader("X-Requested-With");
    boolean result = "XMLHttpRequest".equals(requestedWithHeader);

    if (LOG.isTraceEnabled()) {
        LOG.trace("Request URL: [" + request.getServletPath() + "]" + " - " + "X-Requested-With: ["
                + requestedWithHeader + "]" + " - " + "Returning: [" + result + "]");
    }/* w w w  . ja va2  s .c  om*/

    return result;
}

From source file:com.fota.pushMgt.controller.PushFotaCTR.java

@RequestMapping(value = "/pushFota")
public String getPushActionView(HttpServletRequest request, HttpServletResponse response, Model model)
        throws Exception {
    //      if (!request.getServletPath().equals("/commonDeviceQuality/pushMgt/pushFota")) {
    if (!request.getServletPath().equals("/commonFota/pushMgt/pushFota")) {
        response.setStatus(403);/*from w  ww . j  av a  2  s .c  o m*/
        return "redirect:/lresources/errorPage.jsp";
        //         return null;
    }

    return "pushMgt/pushFota";
}

From source file:org.artifactory.webapp.servlet.RepoFilter.java

private boolean isDockerRequest(HttpServletRequest request) {
    String dockerApiPath = "/api/docker";
    String joinedRequestPath = request.getServletPath() + request.getPathInfo();
    return joinedRequestPath.contains(dockerApiPath)
            || request.getRequestURL().toString().contains(dockerApiPath);
}

From source file:controller.uploadProductController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   ww w.j a va  2s .co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    String userPath = request.getServletPath();
    if (userPath.equals("/uploadProduct")) {
        boolean success = true;
        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // sets temporary location to store files
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);

        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // constructs the directory path to store upload file
        // this path is relative to application's directory
        String uploadPath = getServletContext().getInitParameter("upload.location");
        //creates a HashMap of all inputs
        HashMap hashMap = new HashMap();
        String productId = UUID.randomUUID().toString();
        try {
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    File file = new File(item.getName());
                    File file2 = new File(productId + ".jpg");
                    String filePath = uploadPath + File.separator + file.getName();
                    // saves the file on disk
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    File rename = new File(filePath);
                    boolean flag = rename.renameTo(file2);
                } else {
                    hashMap.put(item.getFieldName(), item.getString());
                }
            }
        } catch (FileUploadException ex) {
            Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", ex.getMessage());
            success = false;
        } catch (Exception ex) {
            Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", ex.getMessage());
            success = false;
        }
        String owner = (String) session.getAttribute("customerEmail");
        if (owner == null) {
            owner = "shop";
        }

        String pName = hashMap.get("pName").toString();
        String mNo = hashMap.get("mNo").toString();
        String brand = hashMap.get("brand").toString();
        String description = hashMap.get("description").toString();
        String quantity = hashMap.get("quantity").toString();
        String price = hashMap.get("price").toString();
        String addInfo = hashMap.get("addInfo").toString();
        int categoryId = Integer.parseInt(hashMap.get("category").toString());

        ProductDAO productDAO = new ProductDAOImpl();
        Product product;

        try {
            double priceDouble = Double.parseDouble(price);
            int quantityInt = Integer.parseInt(quantity);
            Category category = (new CategoryDAOImpl()).getCategoryFromID(categoryId);
            if (owner.equals("shop")) {
                product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand,
                        description, addInfo, true, true, owner);
            } else {
                product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand,
                        description, addInfo, false, false, owner);
            }

            if (!(productDAO.addProduct(product, category.getName()))) {
                throw new Exception("update unsuccessful");
            }
        } catch (Exception e) {
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", e.getMessage());
            success = false;
        }

        request.setAttribute("pName", pName);
        request.setAttribute("mNo", mNo);
        request.setAttribute("brand", brand);
        request.setAttribute("description", description);
        request.setAttribute("quantity", quantity);
        request.setAttribute("price", price);
        request.setAttribute("addInfo", addInfo);
        request.setAttribute("categoryId", categoryId);
        request.setAttribute("success", success);
        if (success == true) {
            request.setAttribute("error", false);
            request.setAttribute("errorMessage", null);
        }
        String url;
        if (owner.equals("shop")) {
            url = "/WEB-INF/view/adminAddProducts.jsp";
        } else {
            url = "/WEB-INF/view/clientSideView/addRecycleProduct.jsp";
        }
        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (ServletException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

}

From source file:it.attocchi.web.auth.AuthenticationFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    logger.debug("Filtro Autenticazione");

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpSession session = httpRequest.getSession();

    String requestPath = httpRequest.getServletPath();
    logger.debug("requestPath " + requestPath);

    String user_agent = null;//from w w w  .j a  va2s .c  om
    String auth = null;

    String workstation = null;
    String domain = null;
    String username = null;

    try {

        if (requestPath != null
                && (requestPath.endsWith("index.xhtml") || requestPath.endsWith("login.xhtml"))) {
            logger.debug("Richiesta una pagina fra quelle speciali, esco dal filtro");
            chain.doFilter(request, response);
            return;
        } else {

            user_agent = httpRequest.getHeader("user-agent");
            if ((user_agent != null) && (user_agent.indexOf("MSIE") > -1)) {
                logger.debug("USER-AGENT: " + user_agent);

                auth = httpRequest.getHeader("Authorization");
                if (auth == null) {
                    logger.debug("STEP1: SC_UNAUTHORIZED");

                    httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    httpResponse.setHeader("WWW-Authenticate", "NTLM");
                    httpResponse.flushBuffer();
                    return;
                }

                if (auth.startsWith("NTLM ")) {
                    logger.debug("STEP2: NTLM");

                    byte[] msg = org.apache.commons.codec.binary.Base64.decodeBase64(auth.substring(5));
                    // byte[] msg = new
                    // sun.misc.BASE64Decoder().decodeBuffer(auth.substring(5));
                    int off = 0, length, offset;
                    if (msg[8] == 1) {
                        logger.debug("STEP2a: NTLM");

                        byte z = 0;
                        byte[] msg1 = { (byte) 'N', (byte) 'T', (byte) 'L', (byte) 'M', (byte) 'S', (byte) 'S',
                                (byte) 'P', z, (byte) 2, z, z, z, z, z, z, z, (byte) 40, z, z, z, (byte) 1,
                                (byte) 130, z, z, z, (byte) 2, (byte) 2, (byte) 2, z, z, z, z, z, z, z, z, z, z,
                                z, z };
                        // httpResponse.setHeader("WWW-Authenticate",
                        // "NTLM " + new
                        // sun.misc.BASE64Encoder().encodeBuffer(msg1));
                        httpResponse.setHeader("WWW-Authenticate",
                                "NTLM " + org.apache.commons.codec.binary.Base64.encodeBase64String(msg1));
                        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                        return;
                    } else if (msg[8] == 3) {
                        logger.debug("STEP2b: read data");

                        off = 30;
                        length = msg[off + 17] * 256 + msg[off + 16];
                        offset = msg[off + 19] * 256 + msg[off + 18];
                        workstation = new String(msg, offset, length);

                        length = msg[off + 1] * 256 + msg[off];
                        offset = msg[off + 3] * 256 + msg[off + 2];
                        domain = new String(msg, offset, length);

                        length = msg[off + 9] * 256 + msg[off + 8];
                        offset = msg[off + 11] * 256 + msg[off + 10];
                        username = new String(msg, offset, length);

                        char a = 0;
                        char b = 32;
                        // logger.debug("Username:" +
                        // username.trim().replace(a, b).replaceAll("",
                        // ""));
                        username = username.trim().replace(a, b).replaceAll(" ", "");
                        workstation = workstation.trim().replace(a, b).replaceAll(" ", "");
                        domain = domain.trim().replace(a, b).replaceAll(" ", "");

                        logger.debug("Username: " + username);
                        logger.debug("RemoteHost: " + workstation);
                        logger.debug("Domain: " + domain);

                    }
                }
            } // if IE
            else {
                chain.doFilter(request, response);
            }

            String winUser = username; // domain + "\\" + username;

        }
    } catch (RuntimeException e) {
        logger.error("Errore nel Filtro Autenticazione");
        logger.error(e);

        chain.doFilter(request, response);
        httpResponse.sendError(httpResponse.SC_UNAUTHORIZED);

        httpResponse.sendRedirect(httpRequest.getContextPath() + "/index.jsp");
    }

    logger.debug("Fine Filtro Autenticazione");
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.AdminServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String target = null;// ww w  .  java  2 s  . c  o m
    response.sendRedirect(request.getContextPath() + request.getServletPath() + "/"
            + Long.toString(System.currentTimeMillis(), 36) + (target != null ? ("#" + target) : ""));
}

From source file:co.com.rempe.impresiones.negocio.servlets.SubirArchivosServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    Respuesta respuesta = new Respuesta();
    try {/*from  www  . ja  va2  s  .  co m*/
        String url = request.getServletPath();
        EDireccion direccion = EDireccion.getDireccion(url);
        switch (direccion) {
        case SUBIR_ARCHIVO:
            respuesta = subirArchivo(request);
            break;
        case ELIMINAR_ARCHIVO:
            respuesta = eliminarArchivo(request);
            break;
        }
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        String json = new Gson().toJson(respuesta);
        out.print(json);
        out.close();
    }
}

From source file:org.owasp.webgoat.controller.StartLesson.java

@RequestMapping(value = { "*.lesson" }, produces = "text/html")
public ModelAndView lessonPage(HttpServletRequest request) {
    // I will set here the thymeleaf fragment location based on the resource requested.
    ModelAndView model = new ModelAndView();
    SecurityContext context = SecurityContextHolder.getContext(); //TODO this should work with the security roles of Spring
    GrantedAuthority authority = context.getAuthentication().getAuthorities().iterator().next();
    String path = request.getServletPath(); // we now got /a/b/c/AccessControlMatrix.lesson
    String lessonName = path.substring(path.lastIndexOf('/') + 1, path.indexOf(".lesson"));
    List<AbstractLesson> lessons = course.getLessons();
    Optional<AbstractLesson> lesson = lessons.stream().filter(l -> l.getId().equals(lessonName)).findFirst();
    ws.setCurrentLesson(lesson.get());/*from ww w.  j  a v  a 2 s  .  co m*/
    model.setViewName("lesson_content");
    model.addObject("lesson", lesson.get());
    return model;
}