Example usage for javax.servlet.http HttpServletRequest getRequestURL

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

Introduction

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

Prototype

public StringBuffer getRequestURL();

Source Link

Document

Reconstructs the URL the client used to make the request.

Usage

From source file:com.intel.rsa.podm.rest.filters.UrlValidationFilter.java

private boolean isUrlValid(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
    if (String.format("%s %s HTTP/1.1\n\r", httpServletRequest.getMethod(), httpServletRequest.getRequestURL())
            .getBytes(StandardCharsets.UTF_8).length > URL_MAX_LENGTH_IN_BYTES) {
        logger.w("Requested URI exceeds maximum URI length which is set to {} octets", URL_MAX_LENGTH_IN_BYTES);
        setErrorResponse(httpServletResponse, ErrorResponse.URI_TOO_LONG);
        return false;
    }/*from  w w w .  j  a va2  s  . c  om*/

    String url = httpServletRequest.getRequestURL().toString();
    UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);
    if (urlValidator.isValid(url) && isUrlDecodingPossible(url)) {
        return true;
    } else {
        setErrorResponse(httpServletResponse, ErrorResponse.MALFORMED_URI);
        return false;
    }
}

From source file:net.ljcomputing.core.controler.GlobalExceptionController.java

/**
 * Handle all exceptions.// w  w w .j av  a  2 s .co  m
 *
 * @param req
 *            the req
 * @param exception
 *            the exception
 * @return the error info
 */
@Order(Ordered.LOWEST_PRECEDENCE)
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody ErrorInfo handleAllExceptions(HttpServletRequest req, Exception exception) {
    logger.error("An error occured during the processing of {}:", req.getRequestURL().toString(), exception);

    return new ErrorInfo(getCurrentTimestamp(), HttpStatus.BAD_REQUEST, req.getRequestURL().toString(),
            exception);
}

From source file:net.sourceforge.subsonic.controller.PodcastController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String url = request.getRequestURL().toString();
    String username = securityService.getCurrentUsername(request);
    List<Playlist> playlists = playlistService.getReadablePlaylistsForUser(username);
    List<Podcast> podcasts = new ArrayList<Podcast>();

    for (Playlist playlist : playlists) {

        List<MediaFile> songs = playlistService.getFilesInPlaylist(playlist.getId());
        if (songs.isEmpty()) {
            continue;
        }/* www. j  a v a 2s.c o m*/
        long length = 0L;
        for (MediaFile song : songs) {
            length += song.getFileSize();
        }
        String publishDate = RSS_DATE_FORMAT.format(playlist.getCreated());

        // Resolve content type.
        String suffix = songs.get(0).getFormat();
        String type = StringUtil.getMimeType(suffix);

        // Rewrite URLs in case we're behind a proxy.
        if (settingsService.isRewriteUrlEnabled()) {
            String referer = request.getHeader("referer");
            url = StringUtil.rewriteUrl(url, referer);
        }

        String enclosureUrl = url.replaceFirst("/podcast.*", "/stream?playlist=" + playlist.getId());
        enclosureUrl = settingsService.rewriteRemoteUrl(enclosureUrl);

        podcasts.add(new Podcast(playlist.getName(), publishDate, enclosureUrl, length, type));
    }

    Map<String, Object> map = new HashMap<String, Object>();

    ModelAndView result = super.handleRequestInternal(request, response);
    map.put("url", url);
    map.put("podcasts", podcasts);

    result.addObject("model", map);
    return result;
}

From source file:org.tec.security.spring.Http401AuthenticationEntryPoint.java

/**
 * {@inheritDoc}//  ww w  .j av a2 s  . co m
 */
@Override()
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    if (mLogger.isDebugEnabled()) {
        mLogger.debug("url requires authentication " + request.getRequestURL().toString());
    }
    //send response code to trip error handler to prompt for login
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication required");
}

From source file:com.stimulus.archiva.presentation.ExportBean.java

@Override
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    SearchBean searchBean = (SearchBean) form;

    String outputDir = Config.getFileSystem().getViewPath() + File.separatorChar;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String zipFileName = "export-" + sdf.format(new Date()) + ".zip";
    File zipFile = new File(outputDir + zipFileName);

    String agent = request.getHeader("USER-AGENT");
    if (null != agent && -1 != agent.indexOf("MSIE")) {
        String codedfilename = URLEncoder.encode(zipFileName, "UTF8");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
    } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
        String codedfilename = MimeUtility.encodeText(zipFileName, "UTF8", "B");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
    } else {//from www .  ja  v a  2s . c om
        response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);
    }

    logger.debug("size of searchResult = " + searchBean.getSearchResults().size());
    //MessageBean.viewMessage
    List<File> files = new ArrayList<File>();
    for (SearchResultBean searchResult : searchBean.getSearchResults()) {
        if (searchResult.getSelected()) {
            Email email = MessageService.getMessageByID(searchResult.getVolumeID(), searchResult.getUniqueID(),
                    false);

            HttpServletRequest hsr = ActionContext.getActionContext().getRequest();
            String baseURL = hsr.getRequestURL().substring(0,
                    hsr.getRequestURL().lastIndexOf(hsr.getServletPath()));
            MessageExtraction messageExtraction = MessageService.extractMessage(email, baseURL, true); // can take a while to extract message

            //              MessageBean mbean = new MessageBean();
            //              mbean.setMessageID(searchResult.getUniqueID());
            //              mbean.setVolumeID(searchResult.getVolumeID());
            //              writer.println(searchResult.toString());
            //              writer.println(messageExtraction.getFileName());

            File fileToAdd = new File(outputDir, messageExtraction.getFileName());
            if (!files.contains(fileToAdd)) {
                files.add(fileToAdd);
            }
        }
    }

    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
    try {
        byte[] buf = new byte[1024];
        for (File f : files) {
            ZipEntry ze = new ZipEntry(f.getName());
            logger.debug("Adding file " + f.getName());
            zos.putNextEntry(ze);
            InputStream is = new BufferedInputStream(new FileInputStream(f));
            for (;;) {
                int len = is.read(buf);
                if (len < 0)
                    break;
                zos.write(buf, 0, len);
            }
            is.close();
            Config.getFileSystem().getTempFiles().markForDeletion(f);
        }
    } finally {
        zos.close();
    }
    logger.debug("download zipped emails {fileName='" + zipFileName + "'}");

    String contentType = "application/zip";
    Config.getFileSystem().getTempFiles().markForDeletion(zipFile);
    return new FileStreamInfo(contentType, zipFile);
}

From source file:nl.mok.mastersofcode.spectatorclient.controllers.RoundController.java

@RequestMapping(method = RequestMethod.GET, value = "/{id}")
public ModelAndView testDashboard(final HttpServletRequest request, @PathVariable int id) {
    ModelAndView mav = new ModelAndView();

    mav.addObject("page", new Object() {
        public String uri = "/spec/round";
        public String redirect = request.getRequestURL().toString();
    });/* w w  w.j a  v  a  2 s .  c  o  m*/

    Round round = DataController.getRoundById(id).get();
    mav.addObject("round", round);
    mav.addObject("teams", DataController.getCompetitionById(round.getCompetition()).get().getTeams());
    mav.addObject("currentCompetition", DataController.getCurrentCompetition());
    mav.addObject("currentRound", DataController.getCurrentRound());
    mav.addObject("newsitems", newsitems);

    mav.setViewName("round.twig");

    return mav;
}

From source file:nl.mok.mastersofcode.spectatorclient.controllers.CompetitionController.java

@RequestMapping(method = RequestMethod.GET, value = "/{id}")
public ModelAndView showCompetition(final HttpServletRequest request, @PathVariable int id) {

    ModelAndView mav = new ModelAndView();

    mav.addObject("page", new Object() {
        public String uri = "/spec/competition/" + id;
        public String redirect = request.getRequestURL().toString();
    });/*from   w  w  w.java2  s  .c  o m*/

    mav.addObject("competition", DataController.getCompetitionById(id).orElse(null));
    mav.addObject("currentCompetition", DataController.getCurrentCompetition());
    mav.addObject("currentRound", DataController.getCurrentRound());

    mav.setViewName("competition.twig");

    return mav;
}

From source file:com.wx.spring.interceptor.OAuth2Interceptor.java

/** 
 * ??? false ?afterCompletion(),? /*w ww.ja  v a  2  s  . co m*/
 * true , ?Controller ?, 
 * ?postHandle() ???afterCompletion() 
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    System.out.println("**?: 1?preHandle**");
    String url = request.getRequestURL().toString();

    HttpSession session = request.getSession();
    // ?  

    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Method method = handlerMethod.getMethod();
    OAuthRequired annotation = method.getAnnotation(OAuthRequired.class);
    if (annotation != null) {
        System.out.println("OAuthRequired????");
        Object objUid = session.getAttribute("UserId");
        if (objUid == null) {
            String resultUrl = request.getRequestURL().toString();
            String param = request.getQueryString();
            if (param != null) {
                resultUrl += "?" + param;
            }
            System.out.println("resultUrl=" + resultUrl);
            try {
                resultUrl = java.net.URLEncoder.encode(resultUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //  
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath + "/oauth2.do?resultUrl=" + resultUrl);
            return false;
        }

    }
    return true;
}

From source file:io.kamax.mxisd.controller.directory.v1.UserDirectoryController.java

@RequestMapping(path = "/search", method = RequestMethod.POST)
public String search(HttpServletRequest request) throws IOException {
    String accessToken = getAccessToken(request);
    UserDirectorySearchRequest searchQuery = parser.parse(request, UserDirectorySearchRequest.class);
    URI target = URI.create(request.getRequestURL().toString());
    UserDirectorySearchResult result = mgr.search(target, accessToken, searchQuery.getSearchTerm());
    return gson.toJson(result);
}