List of usage examples for javax.servlet.http HttpServletRequest getServletPath
public String getServletPath();
From source file:jp.aegif.alfresco.online_webdav.WebDAVHelper.java
public String getRepositoryPath(HttpServletRequest request) { // Try and get the path String strPath = null;// w w w. j ava 2s .c om try { strPath = WebDAVHelper.decodeURL(request.getRequestURI()); } catch (Exception ex) { } // Find the servlet path and trim from the request path String servletPath = request.getServletPath(); int rootPos = strPath.indexOf(servletPath); if (rootPos != -1) { strPath = strPath.substring(rootPos); } // If we failed to get the path from the request try and get the path from the servlet path if (strPath == null) { strPath = request.getServletPath(); } if (strPath == null || strPath.length() == 0) { // If we still have not got a path then default to the root directory strPath = WebDAV.RootPath; } else if (strPath.startsWith(request.getServletPath())) { // Check if the path starts with the base servlet path int len = request.getServletPath().length(); if (strPath.length() > len) { strPath = strPath.substring(len); } else { strPath = WebDAV.RootPath; } } // Make sure there are no trailing slashes if (strPath.length() > 1 && strPath.endsWith(WebDAV.PathSeperator)) { strPath = strPath.substring(0, strPath.length() - 1); } // Return the path return strPath; }
From source file:lucee.runtime.engine.CFMLEngineImpl.java
@Override public void serviceFile(HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException { req = new HTTPServletRequestWrap(req); CFMLFactory factory = getCFMLFactory(servlet.getServletConfig(), req); ConfigWeb config = factory.getConfig(); PageSource ps = config.getPageSourceExisting(null, null, req.getServletPath(), false, true, true, false); //Resource res = ((ConfigWebImpl)config).getPhysicalResourceExistingX(null, null, req.getServletPath(), false, true, true); if (ps == null) { rsp.sendError(404);/* ww w . ja va2 s .c o m*/ } else { Resource res = ps.getResource(); if (res == null) { rsp.sendError(404); } else { ReqRspUtil.setContentLength(rsp, res.length()); String mt = servlet.getServletContext().getMimeType(req.getServletPath()); if (!StringUtil.isEmpty(mt)) ReqRspUtil.setContentType(rsp, mt); IOUtil.copy(res, rsp.getOutputStream(), true); } } }
From source file:com.cyclopsgroup.waterview.servlet.ServletPageRuntime.java
/** * Default constructor of default web runtime * /*from www .j a va2 s .co m*/ * @param request Http request object * @param response Http response object * @param fileUpload File upload component * @param services ServiceManager object * @throws Exception Throw it out */ ServletPageRuntime(HttpServletRequest request, HttpServletResponse response, FileUpload fileUpload, ServiceManager services) throws Exception { this.response = response; this.request = request; setSessionContext(new HttpSessionContext(request.getSession())); String requestPath = request.getPathInfo(); if (StringUtils.isEmpty(requestPath) || requestPath.equals("/")) { requestPath = "Index.jelly"; } else if (requestPath.charAt(0) == '/') { requestPath = requestPath.substring(1); } setRequestPath(requestPath); setOutput(new PrintWriter(response.getOutputStream())); if (FileUpload.isMultipartContent(request)) { setRequestParameters(new MultipartServletRequestValueParser(request, fileUpload)); } else { setRequestParameters(new ServletRequestValueParser(request)); } setServiceManager(services); StringBuffer sb = new StringBuffer(request.getScheme()); sb.append("://").append(request.getServerName()); if (request.getServerPort() != 80) { sb.append(':').append(request.getServerPort()); } sb.append(request.getContextPath()); setApplicationBaseUrl(sb.toString()); sb.append(request.getServletPath()); setPageBaseUrl(sb.toString()); Context pageContext = new DefaultContext(new HashMap()); pageContext.put("request", request); pageContext.put("response", response); setPageContext(pageContext); }
From source file:edu.mayo.cts2.framework.webapp.rest.controller.AbstractMessageWrappingController.java
/** * Populate directory.//from ww w.ja v a 2 s. com * * @param <T> * the generic type * @param result * the result * @param page * the page * @param httpServletRequest * the http servlet request * @param directoryClazz * the directory clazz * @return the t */ @SuppressWarnings("unchecked") protected <T extends Directory> T populateDirectory(DirectoryResult<?> result, Page page, HttpServletRequest httpServletRequest, Class<T> directoryClazz) { T directory; try { directory = directoryClazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } if (result == null || result.getEntries() == null) { result = new DirectoryResult<Void>(new ArrayList<Void>(), true); } this.setDirectoryEntries(directory, result.getEntries()); boolean atEnd = result.isAtEnd(); boolean isComplete = atEnd && (page.getPage() == 0); String urlRoot = this.serverContext.getServerRootWithAppName(); if (!urlRoot.endsWith("/")) { urlRoot = urlRoot + "/"; } String pathInfo = httpServletRequest.getServletPath(); String url = urlRoot + StringUtils.removeStart(pathInfo, "/"); if (isComplete) { directory.setComplete(CompleteDirectory.COMPLETE); } else { directory.setComplete(CompleteDirectory.PARTIAL); if (!result.isAtEnd()) { directory.setNext(url + getParametersString(httpServletRequest.getParameterMap(), page.getPage() + 1, page.getMaxToReturn())); } if (page.getPage() > 0) { directory.setPrev(url + getParametersString(httpServletRequest.getParameterMap(), page.getPage() - 1, page.getMaxToReturn())); } } directory.setNumEntries((long) result.getEntries().size()); return this.wrapMessage(directory, httpServletRequest); }
From source file:com.infoklinik.rsvp.server.service.OAuthLoginServiceImpl.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/*from w ww. j a v a2 s . c o m*/ switch (req.getServletPath()) { case "/verifyCredential": HttpSession session = req.getSession(); logger.info("Session ID : " + session.getId()); Integer authProvider = (Integer) req.getSession().getAttribute(SESSION_AUTH_PROVIDER); String state = req.getParameter("state"); String code = req.getParameter("code"); String oauth_verifier = req.getParameter("oauth_verifier"); Credential credential = OAuthUtil.getSvrCredential(authProvider, state, code, oauth_verifier); verifySocialUser(credential, req.getSession()); session.setAttribute(SESSION_USER_VERIFIED, Constant.YES); logger.info("verify credential successful"); resp.sendRedirect("oAuthLoginVerified"); break; } } catch (Exception e) { logger.log(Level.SEVERE, "OAuthLoginServiceImpl Exception", e); throw new ServletException(e); } }
From source file:dk.itst.oiosaml.sp.service.SPFilter.java
/** * Check whether the user is authenticated i.e. having session with a valid * assertion. If the user is not authenticated an <AuthnRequest> is sent to * the Login Site./*from ww w .j a v a2s . c o m*/ * * @param request * The servletRequest * @param response * The servletResponse */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (log.isDebugEnabled()) log.debug("OIOSAML-J SP Filter invoked"); if (!(request instanceof HttpServletRequest)) { throw new RuntimeException("Not supported operation..."); } HttpServletRequest servletRequest = ((HttpServletRequest) request); Audit.init(servletRequest); if (!isFilterInitialized()) { try { Configuration conf = SAMLConfiguration.getSystemConfiguration(); setRuntimeConfiguration(conf); } catch (IllegalStateException e) { request.getRequestDispatcher("/saml/configure").forward(request, response); return; } } if (conf.getBoolean(Constants.PROP_DEVEL_MODE, false)) { log.warn("Running in debug mode, skipping regular filter"); develMode.doFilter(servletRequest, (HttpServletResponse) response, chain, conf); return; } if (cleanerRunning.compareAndSet(false, true)) { SessionCleaner.startCleaner(sessionHandlerFactory.getHandler(), ((HttpServletRequest) request).getSession().getMaxInactiveInterval(), 30); } SessionHandler sessionHandler = sessionHandlerFactory.getHandler(); if (servletRequest.getServletPath().equals(conf.getProperty(Constants.PROP_SAML_SERVLET))) { log.debug("Request to SAML servlet, access granted"); chain.doFilter(new SAMLHttpServletRequest(servletRequest, hostname, null), response); return; } final HttpSession session = servletRequest.getSession(); if (log.isDebugEnabled()) log.debug("sessionId....:" + session.getId()); // Is the user logged in? if (sessionHandler.isLoggedIn(session.getId()) && session.getAttribute(Constants.SESSION_USER_ASSERTION) != null) { int actualAssuranceLevel = sessionHandler.getAssertion(session.getId()).getAssuranceLevel(); int assuranceLevel = conf.getInt(Constants.PROP_ASSURANCE_LEVEL); if (actualAssuranceLevel < assuranceLevel) { sessionHandler.logOut(session); log.warn("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); throw new RuntimeException( "Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); } UserAssertion ua = (UserAssertion) session.getAttribute(Constants.SESSION_USER_ASSERTION); if (log.isDebugEnabled()) log.debug("Everything is ok... Assertion: " + ua); Audit.log(Operation.ACCESS, servletRequest.getRequestURI()); try { UserAssertionHolder.set(ua); HttpServletRequestWrapper requestWrap = new SAMLHttpServletRequest(servletRequest, ua, hostname); chain.doFilter(requestWrap, response); return; } finally { UserAssertionHolder.set(null); } } else { session.removeAttribute(Constants.SESSION_USER_ASSERTION); UserAssertionHolder.set(null); String relayState = sessionHandler.saveRequest(Request.fromHttpRequest(servletRequest)); String protocol = conf.getString(Constants.PROP_PROTOCOL, "saml20"); String loginUrl = conf.getString(Constants.PROP_SAML_SERVLET, "/saml"); String protocolUrl = conf.getString(Constants.PROP_PROTOCOL + "." + protocol); if (protocolUrl == null) { throw new RuntimeException( "No protocol url configured for " + Constants.PROP_PROTOCOL + "." + protocol); } loginUrl += protocolUrl; if (log.isDebugEnabled()) log.debug("Redirecting to " + protocol + " login handler at " + loginUrl); RequestDispatcher dispatch = servletRequest.getRequestDispatcher(loginUrl); dispatch.forward(new SAMLHttpServletRequest(servletRequest, hostname, relayState), response); } }
From source file:org.artifactory.webapp.servlet.RepoFilter.java
private void doDownload(HttpServletRequest request, HttpServletResponse response, String method, ArtifactoryRequest artifactoryRequest, ArtifactoryResponse artifactoryResponse) throws IOException { if (redirectLegacyMetadataRequest(request, response, artifactoryRequest)) { return;//from ww w . jav a 2 s . c o m } try { RepoRequests.logToContext("Received request"); getDownloadService().process(artifactoryRequest, artifactoryResponse); } catch (FileExpectedException e) { // If we try to get a file but encounter a folder and the request does not end with a '/' send a redirect // that adds the slash with the request with a 302 status code. In the next request if it is a head request, // then it is ok since the resource was found and avoid an infinite redirect situation, however if it is a // GET, then return a 404 since it is the incorrect resource to get (we mimic was apache servers are doing). // see RTFACT-2738 and RTFACT-3510 if (!request.getServletPath().endsWith("/")) { String dirPath = request.getRequestURL().append("/").toString(); RepoRequests.logToContext("Redirecting to the directory path '%s'", dirPath); response.sendRedirect(dirPath); } else if ("head".equals(method)) { RepoRequests.logToContext("Handling directory HEAD request "); } else { RepoRequests.logToContext("Expected file but received a directory - returning a %s response", HttpServletResponse.SC_NOT_FOUND); artifactoryResponse.sendError(HttpServletResponse.SC_NOT_FOUND, "Expected file response but received a directory response: " + e.getRepoPath(), log); } } catch (CancelException e) { RepoRequests.logToContext("Request has been canceled", e.getMessage(), e.getErrorCode()); artifactoryResponse.sendError(e.getErrorCode(), "Download request has been canceled: " + e.getMessage(), log); log.debug("Download request has been canceled" + e.getMessage(), e); } catch (Exception e) { RepoRequests.logToContext("Error handling request: %s - returning a %s response", e.getMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (!(e instanceof IOException) && !artifactoryResponse.isCommitted()) { // io exception is handled by the download service artifactoryResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not process download request: " + e.getMessage(), log); } log.debug("Could not process download request: " + e.getMessage(), e); } }
From source file:io.datenwelt.cargo.rest.Request.java
public Request(HttpServletRequest servletRequest, List<ContentType> supportedContentTypes, List<ContentEncoding> supportedContentEncodings) throws APIException { this.servletRequest = servletRequest; this.supportedContentTypes = supportedContentTypes; this.supportedContentEncodings = supportedContentEncodings; this.method = servletRequest.getMethod(); this.path = Segment.normalize(servletRequest.getPathInfo()); StringBuffer url = servletRequest.getRequestURL(); String query = servletRequest.getQueryString(); if (query != null && !query.isEmpty()) { url.append("?").append(query); }//from w ww. j a v a 2 s . com // Parse request URI and construct the base URI. try { requestURI = new URI(url.toString()); String basePath = (servletRequest.getContextPath() == null ? "" : servletRequest.getContextPath()) + (servletRequest.getServletPath() == null ? "" : servletRequest.getServletPath()); baseURI = URI.create(new StringBuffer().append(requestURI.getScheme()).append("://") .append(requestURI.getRawAuthority()).append("/").append(basePath).toString()); path = Segment.normalize(requestURI.getPath()); if (path.startsWith(basePath)) { path = path.substring(basePath.length()); } } catch (URISyntaxException ex) { throw new APIException(new InternalServerError(), "Unable to parse request URI from string '" + requestURI + "'. Using defaut value for base URI. Error: " + ex.getMessage(), ex); } // Parse query string. String queryString = servletRequest.getQueryString(); this.queries.addAll(Query.parseQueryString(queryString)); // Parse header values Enumeration headerNames = servletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement().toString(); Enumeration values = servletRequest.getHeaders(name); while (values.hasMoreElements()) { Header header = headers.get(name); if (header == null) { header = new Header(name); headers.put(header.getName(), header); } String value = values.nextElement().toString(); header.add(Header.decode(name, value)); } } // Collect infos about the remote end. remoteAddress = servletRequest.getRemoteAddr(); remoteHost = servletRequest.getRemoteHost(); remotePort = servletRequest.getRemotePort(); }
From source file:fr.univrouen.poste.utils.ConfigInterceptor.java
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // we want to add usual model in modelAndView only when needed, ie with // direct html view : // not for download response (for example) because we don't need it // not for redirect view because we don't need it and we don't want that // they appears in the url if (modelAndView != null && modelAndView.hasView()) { boolean isViewObject = modelAndView.getView() == null; boolean isRedirectView = !isViewObject && modelAndView.getView() instanceof RedirectView; boolean viewNameStartsWithRedirect = isViewObject && modelAndView.getViewName().startsWith(UrlBasedViewResolver.REDIRECT_URL_PREFIX); if (!isRedirectView && !viewNameStartsWithRedirect) { String title = AppliConfig.getCacheTitre(); modelAndView.addObject("title", title); String piedPage = AppliConfig.getCachePiedPage(); modelAndView.addObject("piedPage", piedPage); String imageUrl = AppliConfig.getCacheImageUrl(); modelAndView.addObject("imageUrl", imageUrl); String path = request.getServletPath(); String subTitle = subTitles.get(path); String activeMenu = path.replaceAll("/", ""); if (subTitle == null) { List<String> keys = new Vector<String>(subTitles.keySet()); Collections.reverse(keys); for (String key : keys) { if (path.startsWith(key)) { subTitle = subTitles.get(key); ;// www . j a v a2 s. c o m activeMenu = key.replaceAll("/", ""); break; } } } modelAndView.addObject("subTitle", subTitle); modelAndView.addObject("activeMenu", activeMenu); modelAndView.addObject("candidatCanSignup", AppliConfig.getCacheCandidatCanSignup()); modelAndView.addObject("versionEsupDematEC", AppliVersion.getCacheVersion()); } if (request.getParameter("size") != null) { Integer size = Integer.valueOf(request.getParameter("size")); request.getSession().setAttribute("size_in_session", size); } else if (request.getSession(false) != null && request.getSession().getAttribute("size_in_session") == null) { request.getSession().setAttribute("size_in_session", new Integer(40)); } } }
From source file:org.georchestra.security.Proxy.java
private String buildForwardRequestURL(HttpServletRequest request) { String forwardRequestURI = request.getRequestURI(); String contextPath = request.getServletPath() + request.getContextPath(); if (forwardRequestURI.length() <= contextPath.length()) { forwardRequestURI = "/"; } else {//from w w w . j a va 2 s .c o m forwardRequestURI = forwardRequestURI.substring(contextPath.length()); } forwardRequestURI = forwardRequestURI.replaceAll("//", "/"); return forwardRequestURI; }