Example usage for javax.servlet.http HttpServletRequest getRequestURI

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

Introduction

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

Prototype

public String getRequestURI();

Source Link

Document

Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.

Usage

From source file:ee.pri.rl.blog.web.filter.BlogPageCachingFilter.java

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

    boolean cacheEnabled = blogService.getSetting(SettingName.PAGE_CACHE_ENABLED).getBoolValue();
    boolean cacheable = cacheEnabled && !(Session.exists() && ((BlogSession) Session.get()).isAuthenticated());
    if (cacheable && request instanceof HttpServletRequest) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        try {/*  w w  w  . j av a  2 s  . c om*/
            String key = "#PAGE" + new URI(httpServletRequest.getRequestURI()).getPath();
            Cache cache = cacheAdministrator.getCache();

            ResponseContent respContent = null;
            try {
                respContent = (ResponseContent) cache.getFromCache(key);
                log.debug("Sending cached page " + key);
                respContent.writeTo(response, false, false);
            } catch (NeedsRefreshException e) {
                log.debug("Page needs refresh");
                CacheHttpServletResponseWrapper cacheResponse = new CacheHttpServletResponseWrapper(
                        (HttpServletResponse) response, false, Long.MAX_VALUE, CacheFilter.LAST_MODIFIED_OFF,
                        CacheFilter.EXPIRES_OFF, 0);

                chain.doFilter(request, cacheResponse);
                cacheResponse.flushBuffer();

                ResponseContent content = cacheResponse.getContent();
                if (cacheResponse.getStatus() == HttpServletResponse.SC_OK) {
                    // Store only pages with status SC_OK
                    cache.putInCache(key, content, new String[] { "pageCache" }, null, null);
                    log.debug("Page " + key + " stored in cache");
                } else {
                    // Cancel update
                    cache.cancelUpdate(key);
                }
            }
        } catch (URISyntaxException e) {
            log.warn("Invalid URI: " + httpServletRequest.getRequestURI());
            chain.doFilter(request, response);
        }
    } else {
        chain.doFilter(request, response);
    }
}

From source file:edu.du.penrose.systems.fedoraApp.web.bus.security.SecurityManager.java

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    // prevent infinite loop.
    if (request.getRequestURI().contains(getForwardPage())) { //TBD major coupling here!
        return true;
    }/* w ww . j  a va  2s.co  m*/

    // handle logout.
    if (request.getRequestURI().contains(logoutPage)) {

        String fedoraUserName = (String) request.getSession()
                .getAttribute(FedoraAppConstants.FEDORA_USERNAME_SESSION_VARIBLE);
        if (fedoraUserName != null) {
            this.logger.info("Logout for user:" + fedoraUserName);
        }
        request.getSession().removeAttribute(FedoraAppConstants.FEDORA_USERNAME_SESSION_VARIBLE);
        request.getSession().removeAttribute("edu.du.penrose.systems.fedora.client.Administrator");
        response.sendRedirect(
                "/" + FedoraAppConstants.getServletContextListener().getWebApplicatonName() + "/" + loginPage); // TBD magic #
        return false;
    }

    //  has user logged in yet? Catch all but the above exceptions.
    Object result = request.getSession().getAttribute("edu.du.penrose.systems.fedora.client.Administrator");
    if (result == null && forceLogin == true) {
        response.sendRedirect(
                "/" + FedoraAppConstants.getServletContextListener().getWebApplicatonName() + getForwardPage());
        return false;
    } else { // have we timed out?
        if (!request.getSession().getAttributeNames().hasMoreElements()) {
            request.getSession().setAttribute(BOGUS_ATTRIBUE_NAME, BOGUS_ATTRIBUTE_VALUE);
            response.sendRedirect("/" + FedoraAppConstants.getServletContextListener().getWebApplicatonName()
                    + getForwardPage());
            return false;
        }
    }

    return true;
}

From source file:com.mtgi.analytics.servlet.ServletRequestBehaviorTrackingAdapter.java

protected String getEventName(HttpServletRequest request) {
    //use the request path as an event name, excluding proto, host, and query string.
    String eventName = request.getRequestURI();
    //optionally use important parameters as part of the event name
    if (nameParameters != null) {
        char sep = '?';
        StringBuffer buf = new StringBuffer(eventName);
        for (String name : this.nameParameters) {
            String[] values = request.getParameterValues(name);
            if (values != null) {
                for (String v : values) {
                    buf.append(sep).append(name).append('=').append(v);
                    sep = '&';
                }/*from w ww.  j a  v a2s .  com*/
            }
        }
        eventName = buf.toString();
    }

    return eventName;
}

From source file:com.example.appengine.autocomplete.ProductNameAutocompleteJSONServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String path = request.getRequestURI();
    if (path.startsWith("/favicon.ico")) {
        return; // ignore the request for favicon.ico
    }//from  ww  w. j a v a2 s.  co  m

    String[] qContents = request.getParameterValues("q");
    if (qContents == null || qContents.length == 0) {
        PrintWriter out = response.getWriter();
        out.println("Invalid usage");
        return;
    }

    String[] queryElements = qContents[0].trim().split("\\s");
    ArrayList<String> inputPrefixes = new ArrayList<String>();
    for (String s : queryElements) {
        if (s.length() >= minimumPrefixSize) {
            if (s.length() > maximumPrefixSize) {
                s = s.substring(0, maximumPrefixSize);
            }
            inputPrefixes.add(s.toLowerCase());
        }
    }
    Collections.sort(inputPrefixes);
    StringBuilder keyBuilder = new StringBuilder();
    for (String prefix : inputPrefixes) {
        keyBuilder.append(prefix + " ");
    }
    String jsonP = null;

    // try to read from cache
    MemcacheService memCache = MemcacheServiceFactory.getMemcacheService();
    memCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
    byte[] key = keyBuilder.toString().trim().getBytes();
    byte[] cacheValue = (byte[]) memCache.get(key);

    if (cacheValue == null) {
        ArrayList<String> suggestions = generateListAutoCompleteSuggestions(inputPrefixes);
        jsonP = outputJSONPFromSuggestions(suggestions);
        memCache.put(key, jsonP.getBytes());
    } else {
        jsonP = new String(cacheValue);
    }

    response.setContentType("application/javascript;charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");

    PrintWriter out = response.getWriter();
    out.print(jsonP);

    //doDebugging(suggestions, response);
}

From source file:de.hybris.platform.secureportaladdon.interceptors.SecurePortalBeforeControllerHandler.java

protected boolean isNotLoginRequest(final HttpServletRequest request) {
    return !request.getRequestURI().contains(defaultLoginUri)
            || request.getRequestURI().contains(checkoutLoginUri);
}

From source file:csns.web.filter.DepartmentFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    String contextPath = request.getContextPath();
    String path = request.getRequestURI().substring(contextPath.length());
    Cookie cookie = WebUtils.getCookie(request, "default-dept");

    if (path.startsWith("/department/")) {
        int beginIndex = "/department/".length();
        int endIndex = path.indexOf("/", beginIndex);
        if (endIndex < 0)
            endIndex = path.length();/*from  www. ja v  a 2s . co  m*/
        String dept = path.substring(beginIndex, endIndex);
        request.setAttribute("dept", dept);

        logger.debug(path + " -> " + dept);

        if (cookie == null) {
            cookie = new Cookie("default-dept", dept);
            cookie.setPath("/");
            cookie.setMaxAge(100000000);
            response.addCookie(cookie);
        }
    } else {
        if (cookie != null)
            request.setAttribute("dept", cookie.getValue());
    }

    filterChain.doFilter(request, response);
}

From source file:org.craftercms.search.controller.SearchRestController.java

@ExceptionHandler(Exception.class)
public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    logger.error("RESTful request " + request.getRequestURI() + " failed", e);

    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ExceptionUtils.getRootCauseMessage(e));
}

From source file:com.envision.envservice.filter.LoginFilter.java

/**
 * ?/* w ww.  j av a 2 s . c  om*/
 */
private boolean loginCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
    boolean flag = true;

    HttpSession session = request.getSession(false);
    if (request.getRequestURI().endsWith(Constants.URL_LOGIN)) {
        if (session != null) {
            session.invalidate();
        }
    } else {
        // ?
        if (session != null) {
            UserBo user = (UserBo) session.getAttribute(Constants.SESSION_USER);
            if (user == null) {
                flag = false;

                response.setStatus(HttpStatus.SC_BAD_REQUEST);
                response.setContentType(MediaType.APPLICATION_JSON);
                response.getWriter().print(FailResult.toJson(Code.UNLOGIN, ""));
            }
        } else {
            flag = false;

            response.setStatus(HttpStatus.SC_BAD_REQUEST);
            response.setContentType(MediaType.APPLICATION_JSON);
            response.getWriter().print(FailResult.toJson(Code.SESSION_TIMEOUT, "SESSION"));
        }
    }

    return flag;
}

From source file:forumbox.EditPost.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from  w w  w  .  ja v  a  2s  .c om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String url = request.getRequestURI();
    String[] urlpost = url.split("/");
    String idPost = urlpost[3];

    JSONParser passPost = new JSONParser();
    JSONObject post;
    try {

        if (idPost != null) {
            Object objPost = passPost.parse(new FileReader(
                    "/home/dinalidabarera/NetBeansProjects/NewFolder/forum4/admin01/post/" + idPost + ".json"));

            post = (JSONObject) objPost;
            String postuser = post.get("username").toString();
            String posttitle = post.get("title").toString();
            String postdescription = post.get("description").toString();

            /*   JSONArray array = (JSONArray) post.get("comments");
               ArrayList<String> list;
               list = new ArrayList<>();
               Iterator<String> iterator = array.iterator();
                    
               while (iterator.hasNext()) {
            list.add(iterator.next());
               }
                    
               int listsz = list.size(); */
            /*  String[] comments = new String[listsz];
              for(int i=0;i<listsz;i++){
            comments[i]=list.get(i);
              }*/

            request.setAttribute("title", posttitle);
            request.setAttribute("description", postdescription);
            request.setAttribute("username", postuser);
            // request.setAttribute("comments",comments);
            request.setAttribute("id", idPost);

            request.getRequestDispatcher("/edit.jsp").forward(request, response);

        }

    } catch (Exception e) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println(e);

    }

}

From source file:it.unitn.elisco.servlet.ImageUploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  www . j  a v a 2 s .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(false);
    Person user;

    if (request.getRequestURI().equals("/admin/image_upload")) {
        user = (Person) session.getAttribute("admin");
    } else {
        user = (Person) session.getAttribute("student");
    }
    // Get the image uploaded by the user as a stream
    Part imagePart = request.getPart("image");
    String imageExtension = "." + imagePart.getSubmittedFileName().split("\\.")[1];

    // Write to a temp file
    File tempFile = File.createTempFile("tmp", imageExtension);
    tempFile.deleteOnExit();
    FileOutputStream out = new FileOutputStream(tempFile);
    IOUtils.copy(imagePart.getInputStream(), out);

    // Upload the image to Cloudinary
    ImageUploader uploader = ImageUploader.getInstance();
    String imageId = uploader.uploadImageToCloud(user, tempFile);

    // Get the url for the uploaded image
    String imageUrl = uploader.getURLWithDimensions(imageId, 200, 200);

    // Send JSON response back to ajax
    String json = new Gson().toJson(imageUrl);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}