List of usage examples for javax.servlet.http HttpServletResponse SC_FORBIDDEN
int SC_FORBIDDEN
To view the source code for javax.servlet.http HttpServletResponse SC_FORBIDDEN.
Click Source Link
From source file:org.dasein.cloud.cloudstack.CSMethod.java
public @Nonnull Document get(@Nonnull String url, @Nonnull String command) throws CloudException, InternalException { Logger wire = CSCloud.getLogger(CSMethod.class, "wire"); Logger logger = CSCloud.getLogger(CSMethod.class, "std"); if (logger.isTraceEnabled()) { logger.trace("enter - " + CSMethod.class.getName() + ".get(" + url + ")"); }//from w w w.j av a 2 s . c o m if (wire.isDebugEnabled()) { wire.debug( "[" + (new Date()) + "] -------------------------------------------------------------------"); wire.debug(""); } HttpClient client = null; try { HttpGet get = new HttpGet(url); client = getClient(url); HttpResponse response; get.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); //get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); if (wire.isDebugEnabled()) { wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } try { APITrace.trace(provider, command); response = client.execute(get); } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } int status = response.getStatusLine().getStatusCode(); if (logger.isDebugEnabled()) { logger.debug("get(): HTTP Status " + status); } if (wire.isDebugEnabled()) { Header[] headers = response.getAllHeaders(); wire.debug(response.getStatusLine().toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } try { if (status != HttpServletResponse.SC_OK) { HttpEntity entity = response.getEntity(); String body = (entity == null ? null : EntityUtils.toString(entity)); if (body == null) { CSMethod.ParsedError p = new CSMethod.ParsedError(); p.code = status; p.message = "No error information was provided"; throw new CSException(CloudErrorType.GENERAL, p); } if (body.contains("<html>")) { if (status == HttpServletResponse.SC_FORBIDDEN || status == HttpServletResponse.SC_UNAUTHORIZED) { CSMethod.ParsedError p = new CSMethod.ParsedError(); p.code = status; p.message = body; throw new CSException(CloudErrorType.AUTHENTICATION, p); } else if (status == 430 || status == 431 || status == 432 || status == 436) { return null; } CSMethod.ParsedError p = new CSMethod.ParsedError(); p.code = status; p.message = body; throw new CSException(p); } throw new CSException(parseError(status, body)); } HttpEntity entity = response.getEntity(); return parseResponse(status, EntityUtils.toString(entity)); } catch (NoHttpResponseException e) { throw new CloudException("No answer from endpoint: " + e.getMessage()); } catch (IOException e) { throw new CloudException("IOException getting stream: " + e.getMessage()); } } finally { if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("[" + (new Date()) + "] -------------------------------------------------------------------"); } if (logger.isTraceEnabled()) { logger.trace("exit - " + CSMethod.class.getName() + ".get()"); } if (client != null) { client.getConnectionManager().shutdown(); } } }
From source file:com.sfwl.framework.web.casclient.AbstractTicketValidationFilter.java
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { if (!preFilter(servletRequest, servletResponse, filterChain)) { return;/* w w w . ja va2 s .c om*/ } final HttpServletRequest request = (HttpServletRequest) servletRequest; final HttpServletResponse response = (HttpServletResponse) servletResponse; final String ticket = retrieveTicketFromRequest(request); // URL(js+css+img) if (excepUrlPattern != null && excepUrlPattern.matcher(request.getServletPath()).matches()) { filterChain.doFilter(servletRequest, servletResponse); return; } if (CommonUtils.isNotBlank(ticket)) { logger.debug("Attempting to validate ticket: {}", ticket); try { final Assertion assertion = this.ticketValidator.validate(ticket, constructServiceUrl(request, response)); logger.debug("Successfully authenticated user: {}", assertion.getPrincipal().getName()); request.setAttribute(CONST_CAS_ASSERTION, assertion); if (this.useSession) { request.getSession().setAttribute(CONST_CAS_ASSERTION, assertion); } onSuccessfulValidation(request, response, assertion); if (this.redirectAfterValidation) { logger.debug("Redirecting after successful ticket validation."); response.sendRedirect(constructServiceUrl(request, response)); return; } } catch (final TicketValidationException e) { logger.debug(e.getMessage(), e); onFailedValidation(request, response); if (this.exceptionOnValidationFailure) { throw new ServletException(e); } response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return; } } filterChain.doFilter(request, response); }
From source file:debrepo.teamcity.web.DebDownloadController.java
@Override protected ModelAndView doHandle(HttpServletRequest request, HttpServletResponse response) throws Exception { String uriPath = request.getPathInfo(); if (uriPath.startsWith(DEBREPO_BASE_URL_UNRESTRICTED)) { uriPath = uriPath.substring(4); // "/app" off the front. }//from w w w .ja va 2 s.co m final Map<String, Object> params = new HashMap<String, Object>(); params.put("pluginName", this.myPluginDescriptor.getPluginName()); params.put("pluginVersion", this.myPluginDescriptor.getPluginVersion()); params.put("jspHome", this.myPluginDescriptor.getPluginResourcesPath()); /* /debrepo/{RepoName}/dists/{Distribution}/{Component}/{Arch}/Packages.gz */ Matcher matcher = packagesGzPattern.matcher(uriPath); if (matcher.matches()) { String repoName = matcher.group(1); String distName = matcher.group(2); String component = matcher.group(3); String archName = matcher.group(4); try { checkRepoIsRestricted(repoName); return servePackagesGzFile(request, response, myDebRepositoryManager .findAllByDistComponentArchIncludingAll(repoName, distName, component, archName)); } catch (DebRepositoryPermissionDeniedException ex) { response.sendError(HttpServletResponse.SC_FORBIDDEN); Loggers.SERVER.info( "DebDownloadController:: Returning 403 : Deb Repository is restricted and user is not permissioned on project: " + request.getPathInfo()); return null; } catch (DebRepositoryAccessIsRestrictedException ex) { response.sendRedirect(buildRedirectToRestrictedUrl(request, uriPath)); Loggers.SERVER.info("DebDownloadController:: Returning 302 : Deb Repository is restricted: " + request.getPathInfo()); return null; } catch (NonExistantRepositoryException ex) { response.sendError(HttpServletResponse.SC_NOT_FOUND); Loggers.SERVER.info( "DebDownloadController:: Returning 404 : Not Found: No Deb Repository exists with the name: " + request.getPathInfo()); return null; } } /* /debrepo/{RepoName}/dists/{Distribution}/{Component}/{Arch}/Packages */ matcher = packagesPattern.matcher(uriPath); if (matcher.matches()) { String repoName = matcher.group(1); String distName = matcher.group(2); String component = matcher.group(3); String archName = matcher.group(4); try { checkRepoIsRestricted(repoName); return servePackagesFile(request, response, myDebRepositoryManager .findAllByDistComponentArchIncludingAll(repoName, distName, component, archName)); } catch (DebRepositoryPermissionDeniedException ex) { response.sendError(HttpServletResponse.SC_FORBIDDEN); Loggers.SERVER.info( "DebDownloadController:: Returning 403 : Deb Repository is restricted and user is not permissioned on project: " + request.getPathInfo()); return null; } catch (DebRepositoryAccessIsRestrictedException ex) { response.sendRedirect(buildRedirectToRestrictedUrl(request, uriPath)); Loggers.SERVER.info("DebDownloadController:: Returning 302 : Deb Repository is restricted: " + request.getPathInfo()); return null; } catch (NonExistantRepositoryException ex) { response.sendError(HttpServletResponse.SC_NOT_FOUND); Loggers.SERVER.info( "DebDownloadController:: Returning 404 : Not Found: No Deb Repository exists with the name: " + request.getPathInfo()); return null; } } /* /debrepo/{RepoName}/dists/{Distribution}/{Component}/binary-{Arch}/ */ matcher = browseArchPattern.matcher(uriPath); if (matcher.matches()) { String repoName = matcher.group(1); String distName = matcher.group(2); String component = matcher.group(3); String archName = matcher.group(4); try { checkRepoIsRestricted(repoName); if (myDebRepositoryManager .findAllByDistComponentArchIncludingAll(repoName, distName, component, archName) .size() > 0) { List<LinkItem> breadcrumbItems = new ArrayList<>(); breadcrumbItems.add(LinkItem.builder().text("<b>Index of</b> ").type(LINK_TYPE_REP_DIR_SLASH) .url("").build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text(repoName).type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("dists").type(LINK_TYPE_REPO_DIR).url( request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/dists/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem .builder().text(distName).type(LINK_TYPE_REPO_DIR).url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/dists/" + distName + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text(component).type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/dists/" + distName + "/" + component + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("binary-" + archName).type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/dists/" + distName + "/" + component + "/binary-" + archName + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); params.put("breadcrumbItems", breadcrumbItems); List<LinkItem> linkItems = new ArrayList<>(); linkItems.add(LinkItem.builder().text("Packages").type(LINK_TYPE_REPO_FILE).url("./Packages") .build()); linkItems.add(LinkItem.builder().text("Packages.gz").type(LINK_TYPE_REPO_FILE) .url("./Packages.gz").build()); params.put("linkItems", linkItems); params.put("directoryTitle", repoName); params.put("currentPathLevel", "binary-" + archName); return new ModelAndView( myPluginDescriptor.getPluginResourcesPath("debRepository/directoryListing.jsp"), params); } } catch (DebRepositoryPermissionDeniedException ex) { response.sendError(HttpServletResponse.SC_FORBIDDEN); Loggers.SERVER.info( "DebDownloadController:: Returning 403 : Deb Repository is restricted and user is not permissioned on project: " + request.getPathInfo()); return null; } catch (DebRepositoryAccessIsRestrictedException ex) { response.sendRedirect(buildRedirectToRestrictedUrl(request, uriPath)); Loggers.SERVER.info("DebDownloadController:: Returning 302 : Deb Repository is restricted: " + request.getPathInfo()); return null; } catch (NonExistantRepositoryException ex) { response.sendError(HttpServletResponse.SC_NOT_FOUND); Loggers.SERVER.info( "DebDownloadController:: Returning 404 : Not Found: No Deb Repository exists with the name: " + request.getPathInfo()); return null; } } /* /debrepo/{RepoName}/dists/{Distribution}/{Component}/ */ matcher = browseComponentPattern.matcher(uriPath); if (matcher.matches()) { String repoName = matcher.group(1); String distName = matcher.group(2); String component = matcher.group(3); try { checkRepoIsRestricted(repoName); List<LinkItem> linkItems = new ArrayList<>(); for (String arch : myDebRepositoryManager.findUniqueArchByDistAndComponent(repoName, distName, component)) { linkItems.add(LinkItem.builder().text("binary-" + arch).type(LINK_TYPE_REPO_DIR) .url("./binary-" + arch + "/").build()); } params.put("linkItems", linkItems); params.put("alertInfo", "deb " + StringUtils.getDebRepoUrlWithUserPassExample(myServer.getRootUrl(), repoName, myDebRepositoryManager.isRestrictedRepository(repoName)) + " " + distName + " " + component); params.put("directoryTitle", repoName); params.put("currentPathLevel", component); List<LinkItem> breadcrumbItems = new ArrayList<>(); breadcrumbItems.add( LinkItem.builder().text("<b>Index of</b> ").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text(repoName).type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("dists").type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/dists/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem .builder().text(distName).type(LINK_TYPE_REPO_DIR).url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/dists/" + distName + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text(component).type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/dists/" + distName + "/" + component + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); params.put("breadcrumbItems", breadcrumbItems); return new ModelAndView( myPluginDescriptor.getPluginResourcesPath("debRepository/directoryListing.jsp"), params); } catch (DebRepositoryPermissionDeniedException ex) { response.sendError(HttpServletResponse.SC_FORBIDDEN); Loggers.SERVER.info( "DebDownloadController:: Returning 403 : Deb Repository is restricted and user is not permissioned on project: " + request.getPathInfo()); return null; } catch (DebRepositoryAccessIsRestrictedException ex) { response.sendRedirect(buildRedirectToRestrictedUrl(request, uriPath)); Loggers.SERVER.info("DebDownloadController:: Returning 302 : Deb Repository is restricted: " + request.getPathInfo()); return null; } catch (NonExistantRepositoryException ex) { response.sendError(HttpServletResponse.SC_NOT_FOUND); Loggers.SERVER.info( "DebDownloadController:: Returning 404 : Not Found: No Deb Repository exists with the name: " + request.getPathInfo()); return null; } } /* /debrepo/{RepoName}/dists/{Distribution}/ */ matcher = browseDistPattern.matcher(uriPath); if (matcher.matches()) { String repoName = matcher.group(1); String distName = matcher.group(2); try { checkRepoIsRestricted(repoName); List<LinkItem> linkItems = new ArrayList<>(); for (String component : myDebRepositoryManager.findUniqueComponentByDist(repoName, distName)) { linkItems.add(LinkItem.builder().text(component).type(LINK_TYPE_REPO_DIR) .url("./" + component + "/").build()); } params.put("linkItems", linkItems); params.put("directoryTitle", repoName); params.put("currentPathLevel", distName); List<LinkItem> breadcrumbItems = new ArrayList<>(); breadcrumbItems.add( LinkItem.builder().text("<b>Index of</b> ").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text(repoName).type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("dists").type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/dists/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem .builder().text(distName).type(LINK_TYPE_REPO_DIR).url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/dists/" + distName + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); params.put("breadcrumbItems", breadcrumbItems); return new ModelAndView( myPluginDescriptor.getPluginResourcesPath("debRepository/directoryListing.jsp"), params); } catch (DebRepositoryPermissionDeniedException ex) { response.sendError(HttpServletResponse.SC_FORBIDDEN); Loggers.SERVER.info( "DebDownloadController:: Returning 403 : Deb Repository is restricted and user is not permissioned on project: " + request.getPathInfo()); return null; } catch (DebRepositoryAccessIsRestrictedException ex) { response.sendRedirect(buildRedirectToRestrictedUrl(request, uriPath)); Loggers.SERVER.info("DebDownloadController:: Returning 302 : Deb Repository is restricted: " + request.getPathInfo()); return null; } catch (NonExistantRepositoryException ex) { response.sendError(HttpServletResponse.SC_NOT_FOUND); Loggers.SERVER.info( "DebDownloadController:: Returning 404 : Not Found: No Deb Repository exists with the name: " + request.getPathInfo()); return null; } } /* /debrepo/{RepoName}/dists/ */ matcher = browseRepoDistPattern.matcher(uriPath); if (matcher.matches()) { String repoName = matcher.group(1); try { checkRepoIsRestricted(repoName); List<LinkItem> linkItems = new ArrayList<>(); for (String dist : myDebRepositoryManager.findUniqueDist(repoName)) { linkItems.add( LinkItem.builder().text(dist).type(LINK_TYPE_REPO_DIR).url("./" + dist + "/").build()); } params.put("linkItems", linkItems); params.put("directoryTitle", repoName); params.put("currentPathLevel", "dist"); List<LinkItem> breadcrumbItems = new ArrayList<>(); breadcrumbItems.add( LinkItem.builder().text("<b>Index of</b> ").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text(repoName).type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("dists").type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/dists/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); params.put("breadcrumbItems", breadcrumbItems); return new ModelAndView( myPluginDescriptor.getPluginResourcesPath("debRepository/directoryListing.jsp"), params); } catch (DebRepositoryPermissionDeniedException ex) { response.sendError(HttpServletResponse.SC_FORBIDDEN); Loggers.SERVER.info( "DebDownloadController:: Returning 403 : Deb Repository is restricted and user is not permissioned on project: " + request.getPathInfo()); return null; } catch (DebRepositoryAccessIsRestrictedException ex) { response.sendRedirect(buildRedirectToRestrictedUrl(request, uriPath)); Loggers.SERVER.info("DebDownloadController:: Returning 302 : Deb Repository is restricted: " + request.getPathInfo()); return null; } catch (NonExistantRepositoryException ex) { response.sendError(HttpServletResponse.SC_NOT_FOUND); Loggers.SERVER.info( "DebDownloadController:: Returning 404 : Not Found: No Deb Repository exists with the name: " + request.getPathInfo()); return null; } } /* /debrepo/{RepoName}/pool/{Component}/{packageName}/ */ matcher = browsePoolPackagePat.matcher(uriPath); if (matcher.matches()) { String repoName = matcher.group(1); String component = matcher.group(2); String packageName = matcher.group(3); try { checkRepoIsRestricted(repoName); List<LinkItem> linkItems = new ArrayList<>(); List<? extends DebPackage> debs = myDebRepositoryManager .getUniquePackagesByComponentAndPackageName(repoName, component, packageName); Collections.sort(debs, new DebPackageComparator()); for (DebPackage deb : debs) { linkItems.add(LinkItem.builder().text(deb.getFilename()).type(LINK_TYPE_REPO_FILE) .url("../../../" + deb.getUri()).build()); } params.put("linkItems", linkItems); params.put("directoryTitle", repoName); params.put("currentPathLevel", packageName); List<LinkItem> breadcrumbItems = new ArrayList<>(); breadcrumbItems.add( LinkItem.builder().text("<b>Index of</b> ").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text(repoName).type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("pool").type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/pool/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem .builder().text(component).type(LINK_TYPE_REPO_DIR).url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/pool/" + component + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text(packageName).type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/pool/" + component + "/" + packageName + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); params.put("breadcrumbItems", breadcrumbItems); return new ModelAndView( myPluginDescriptor.getPluginResourcesPath("debRepository/directoryListing.jsp"), params); } catch (DebRepositoryPermissionDeniedException ex) { response.sendError(HttpServletResponse.SC_FORBIDDEN); Loggers.SERVER.info( "DebDownloadController:: Returning 403 : Deb Repository is restricted and user is not permissioned on project: " + request.getPathInfo()); return null; } catch (DebRepositoryAccessIsRestrictedException ex) { response.sendRedirect(buildRedirectToRestrictedUrl(request, uriPath)); Loggers.SERVER.info("DebDownloadController:: Returning 302 : Deb Repository is restricted: " + request.getPathInfo()); return null; } catch (NonExistantRepositoryException ex) { response.sendError(HttpServletResponse.SC_NOT_FOUND); Loggers.SERVER.info( "DebDownloadController:: Returning 404 : Not Found: No Deb Repository exists with the name: " + request.getPathInfo()); Loggers.SERVER.debug(ex); return null; } } /* /debrepo/{RepoName}/pool/{Component}/ */ matcher = browsePoolComponentPat.matcher(uriPath); if (matcher.matches()) { String repoName = matcher.group(1); String component = matcher.group(2); try { checkRepoIsRestricted(repoName); List<LinkItem> linkItems = new ArrayList<>(); for (String packageName : myDebRepositoryManager.findUniquePackageNameByComponent(repoName, component)) { linkItems.add(LinkItem.builder().text(packageName).type(LINK_TYPE_REPO_FILE) .url("./" + packageName + "/").build()); } params.put("linkItems", linkItems); params.put("directoryTitle", repoName); params.put("currentPathLevel", component); List<LinkItem> breadcrumbItems = new ArrayList<>(); breadcrumbItems.add( LinkItem.builder().text("<b>Index of</b> ").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text(repoName).type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("pool").type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/pool/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem .builder().text(component).type(LINK_TYPE_REPO_DIR).url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/pool/" + component + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); params.put("breadcrumbItems", breadcrumbItems); return new ModelAndView( myPluginDescriptor.getPluginResourcesPath("debRepository/directoryListing.jsp"), params); } catch (DebRepositoryPermissionDeniedException ex) { response.sendError(HttpServletResponse.SC_FORBIDDEN); Loggers.SERVER.info( "DebDownloadController:: Returning 403 : Deb Repository is restricted and user is not permissioned on project: " + request.getPathInfo()); return null; } catch (DebRepositoryAccessIsRestrictedException ex) { response.sendRedirect(buildRedirectToRestrictedUrl(request, uriPath)); Loggers.SERVER.info("DebDownloadController:: Returning 302 : Deb Repository is restricted: " + request.getPathInfo()); return null; } catch (NonExistantRepositoryException ex) { response.sendError(HttpServletResponse.SC_NOT_FOUND); Loggers.SERVER.info( "DebDownloadController:: Returning 404 : Not Found: No Deb Repository exists with the name: " + request.getPathInfo()); Loggers.SERVER.debug(ex); return null; } } /* /debrepo/{RepoName}/pool/ */ matcher = browsePoolPattern.matcher(uriPath); if (matcher.matches()) { String repoName = matcher.group(1); try { checkRepoIsRestricted(repoName); List<LinkItem> linkItems = new ArrayList<>(); for (String component : myDebRepositoryManager.findUniqueComponent(repoName)) { linkItems.add(LinkItem.builder().text(component).type(LINK_TYPE_REPO_FILE) .url("./" + component + "/").build()); } params.put("linkItems", linkItems); params.put("directoryTitle", repoName); params.put("currentPathLevel", "pool"); List<LinkItem> breadcrumbItems = new ArrayList<>(); breadcrumbItems.add( LinkItem.builder().text("<b>Index of</b> ").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text(repoName).type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("pool").type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/pool/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); params.put("breadcrumbItems", breadcrumbItems); return new ModelAndView( myPluginDescriptor.getPluginResourcesPath("debRepository/directoryListing.jsp"), params); } catch (DebRepositoryPermissionDeniedException ex) { response.sendError(HttpServletResponse.SC_FORBIDDEN); Loggers.SERVER.info( "DebDownloadController:: Returning 403 : Deb Repository is restricted and user is not permissioned on project: " + request.getPathInfo()); return null; } catch (DebRepositoryAccessIsRestrictedException ex) { response.sendRedirect(buildRedirectToRestrictedUrl(request, uriPath)); Loggers.SERVER.info("DebDownloadController:: Returning 302 : Deb Repository is restricted: " + request.getPathInfo()); return null; } catch (NonExistantRepositoryException ex) { response.sendError(HttpServletResponse.SC_NOT_FOUND); Loggers.SERVER.info( "DebDownloadController:: Returning 404 : Not Found: No Deb Repository exists with the name: " + request.getPathInfo()); Loggers.SERVER.debug(ex); return null; } } /* /debrepo/{RepoName}/pool/{Component}/{packageName} */ matcher = packageFilenamePattern.matcher(uriPath); if (matcher.matches()) { String repoName = matcher.group(1); String uri = matcher.group(3); try { checkRepoIsRestricted(repoName); uri = uriPath.substring(getDebRepoUrlPart().length() + 1 + repoName.length() + 1); DebPackage debPackage = myDebRepositoryManager.findByUri(repoName, uri); SBuild build = this.myServer.findBuildInstanceById(debPackage.getBuildId()); return servePackage(request, response, new File(build.getArtifactsDirectory() + File.separator + debPackage.getFilename())); } catch (DebPackageNotFoundInStoreException ex) { response.sendError(HttpServletResponse.SC_NOT_FOUND); Loggers.SERVER .info("DebDownloadController:: Returning 404 : Not Found: No Deb file found in repository: " + request.getPathInfo()); Loggers.SERVER.debug(ex); return null; } catch (DebRepositoryPermissionDeniedException ex) { response.sendError(HttpServletResponse.SC_FORBIDDEN); Loggers.SERVER.info( "DebDownloadController:: Returning 403 : Deb Repository is restricted and user is not permissioned on project: " + request.getPathInfo()); return null; } catch (DebRepositoryAccessIsRestrictedException ex) { response.sendRedirect(buildRedirectToRestrictedUrl(request, uriPath)); Loggers.SERVER.info("DebDownloadController:: Returning 302 : Deb Repository is restricted: " + request.getPathInfo()); return null; } catch (NonExistantRepositoryException ex) { response.sendError(HttpServletResponse.SC_NOT_FOUND); Loggers.SERVER.info( "DebDownloadController:: Returning 404 : Not Found: No Deb Repository exists with the name: " + request.getPathInfo()); Loggers.SERVER.debug(ex); return null; } } /* /debrepo/{RepoName}/ */ matcher = infoPattern.matcher(uriPath); if (matcher.matches()) { String repoName = matcher.group(1); try { checkRepoIsRestricted(repoName); List<LinkItem> linkItems = new ArrayList<>(); linkItems.add(LinkItem.builder().text("dists").type(LINK_TYPE_REPO_DIR).url("./dists/").build()); linkItems.add(LinkItem.builder().text("pool").type(LINK_TYPE_REPO_DIR).url("./pool/").build()); params.put("linkItems", linkItems); params.put("directoryTitle", repoName); List<LinkItem> breadcrumbItems = new ArrayList<>(); breadcrumbItems.add( LinkItem.builder().text("<b>Index of</b> ").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); breadcrumbItems.add(LinkItem.builder().text(repoName).type(LINK_TYPE_REPO_DIR) .url(request.getServletPath() + getDebRepoUrlPartWithContext() + "/" + repoName + "/") .build()); breadcrumbItems.add(LinkItem.builder().text("/").type(LINK_TYPE_REP_DIR_SLASH).url("").build()); params.put("breadcrumbItems", breadcrumbItems); Loggers.SERVER.info("DebDownloadController:: Returning 200: " + request.getPathInfo() + " Comparing to " + infoPattern + " Class: " + this.getClass().getName()); return new ModelAndView( myPluginDescriptor.getPluginResourcesPath("debRepository/directoryListing.jsp"), params); } catch (DebRepositoryPermissionDeniedException ex) { response.sendError(HttpServletResponse.SC_FORBIDDEN); Loggers.SERVER.info( "DebDownloadController:: Returning 403 : Deb Repository is restricted and user is not permissioned on project: " + request.getPathInfo()); return null; } catch (DebRepositoryAccessIsRestrictedException ex) { response.sendRedirect(buildRedirectToRestrictedUrl(request, uriPath)); Loggers.SERVER.info("DebDownloadController:: Returning 302 : Deb Repository is restricted: " + request.getPathInfo()); return null; } catch (NonExistantRepositoryException ex) { response.sendError(HttpServletResponse.SC_NOT_FOUND); Loggers.SERVER.info( "DebDownloadController:: Returning 404 : Not Found: No Deb Repository exists with the name: " + request.getPathInfo()); Loggers.SERVER.debug(ex); return null; } } response.sendError(HttpServletResponse.SC_NOT_FOUND); Loggers.SERVER.info("DebDownloadController:: Returning 404 : All regex tried: " + request.getPathInfo() + " Comparing to " + infoPattern + " Class: " + this.getClass().getName()); return null; }
From source file:org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticationFilter.java
@Override protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { boolean requestCompleted = false; UserGroupInformation ugi = null;//from w w w . j a v a 2s.c om AuthenticationToken authToken = (AuthenticationToken) request.getUserPrincipal(); if (authToken != null && authToken != AuthenticationToken.ANONYMOUS) { // if the request was authenticated because of a delegation token, // then we ignore proxyuser (this is the same as the RPC behavior). ugi = (UserGroupInformation) request .getAttribute(DelegationTokenAuthenticationHandler.DELEGATION_TOKEN_UGI_ATTRIBUTE); if (ugi == null) { String realUser = request.getUserPrincipal().getName(); ugi = UserGroupInformation.createRemoteUser(realUser, handlerAuthMethod); String doAsUser = getDoAs(request); if (doAsUser != null) { ugi = UserGroupInformation.createProxyUser(doAsUser, ugi); try { ProxyUsers.authorize(ugi, request.getRemoteAddr()); } catch (AuthorizationException ex) { HttpExceptionUtils.createServletExceptionResponse(response, HttpServletResponse.SC_FORBIDDEN, ex); requestCompleted = true; } } } UGI_TL.set(ugi); } if (!requestCompleted) { final UserGroupInformation ugiF = ugi; try { request = new HttpServletRequestWrapper(request) { @Override public String getAuthType() { return (ugiF != null) ? handlerAuthMethod.toString() : null; } @Override public String getRemoteUser() { return (ugiF != null) ? ugiF.getShortUserName() : null; } @Override public Principal getUserPrincipal() { return (ugiF != null) ? new Principal() { @Override public String getName() { return ugiF.getUserName(); } } : null; } }; super.doFilter(filterChain, request, response); } finally { UGI_TL.remove(); } } }
From source file:org.dataconservancy.ui.api.ProjectController.java
/** * Handles the posting of a new project, this will add a new project to the * system. Note: Dates should be in the format dd mm yyyy * * @throws InvalidXmlException//w ww. ja va 2 s . co m * @throws IOException */ @RequestMapping(method = { RequestMethod.POST }) public void handleProjectPostRequest(@RequestHeader(value = "Accept", required = false) String mimeType, @RequestBody byte[] content, HttpServletRequest req, HttpServletResponse resp) throws BizInternalException, BizPolicyException, InvalidXmlException, IOException { // TODO Why doesn't spring do this? if (req.getContentType().contains("application/x-www-form-urlencoded")) { content = URLDecoder.decode(new String(content, "UTF-8"), "UTF-8").getBytes("UTF-8"); } Project project = objectBuilder.buildProject(new ByteArrayInputStream(content)); Person user = getAuthenticatedUser(); if (user == null) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } else if (authorizationService.canCreateProject(user)) { projectBizService.updateProject(project, user); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/xml"); resp.setStatus(HttpStatus.SC_CREATED); Bop bop = new Bop(); bop.addProject(project); objectBuilder.buildBusinessObjectPackage(bop, resp.getOutputStream()); } else { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } }
From source file:org.jetbrains.webdemo.sessions.MyHttpSession.java
private void sendAddProjectResult() { try {//from ww w .j a v a 2 s . c om String content = request.getParameter("content"); if (content != null) { try { currentProject = objectMapper.readValue(content, Project.class); currentProject.name = request.getParameter("args"); //when user calls save as we must change project name ExamplesUtils.addHiddenFilesToProject(currentProject); String publicId = MySqlConnector.getInstance().addProject(sessionInfo.getUserInfo(), currentProject, "USER_PROJECT"); ObjectNode result = new ObjectNode(JsonNodeFactory.instance); result.put("publicId", publicId); Project project = MySqlConnector.getInstance().getProjectContent(publicId); result.put("content", objectMapper.writeValueAsString(project)); writeResponse(result.toString(), HttpServletResponse.SC_OK); } catch (IOException e) { writeResponse("Can't parse file", HttpServletResponse.SC_BAD_REQUEST); } } else { String name = request.getParameter("name"); String publicIds = MySqlConnector.getInstance().addProject(sessionInfo.getUserInfo(), name, "USER_PROJECT"); writeResponse(publicIds, HttpServletResponse.SC_OK); } } catch (NullPointerException e) { writeResponse("Can't get parameters", HttpServletResponse.SC_BAD_REQUEST); } catch (DatabaseOperationException e) { writeResponse(e.getMessage(), HttpServletResponse.SC_FORBIDDEN); } }
From source file:org.openmrs.module.metadatasharing.web.controller.PublishController.java
/** * Mapped to URL "ws/rest/metadatasharing/package/new.form". XML can be requested with either * GET or POST parameters. Parameters this takes are: * <ul>// w w w. j av a 2 s .c o m * <li>key: This must be set to 5b635b8d02812d2e1c97691cd71fc05a</li> * <li>type: Required. This is the fully-qualified class name of the type of object you wish to * export</li> * <li>uuids: This is a comma-separated list of uuids to export (you may specify either uuids, * ids, or both)</li> * <li>ids: This is a comma-separated list of ids to export (you may specify either uuids, ids, * or both)</li> * <li>modifiedSince: When specified, items to be returned should have had created or * modifications after the specified date</li> * </ul> * <br/> * Example: * * <pre> * ws/rest/metadatasharing/package/new.form?key=5b635b8d02812d2e1c97691cd71fc05a&type=org.openmrs.Location&ids=1,2,3&compress=true * </pre> */ @RequestMapping(value = OLD_PACKAGE_PATH + "/new") public void getNewPackage(@RequestParam(required = false) String key, Class<?> type, @RequestParam(required = false) String ids, @RequestParam(required = false) String uuids, @RequestParam(required = false) Date modifiedSince, HttpServletResponse response) throws IOException, SerializationException { if (Boolean.valueOf(Context.getAdministrationService() .getGlobalProperty(MetadataSharingConsts.GP_ENABLE_ON_THE_FLY_PACKAGES, "false").trim())) { String accessKey = Context.getAdministrationService() .getGlobalProperty(MetadataSharingConsts.GP_WEBSERVICES_KEY); if (accessKey != null) accessKey = accessKey.trim(); if (StringUtils.isBlank(accessKey) || OpenmrsUtil.nullSafeEquals(accessKey, key)) { try { Context.addProxyPrivilege(MetadataSharingConsts.MODULE_PRIVILEGE); //The extra privilege is needed because the Concept handler uses Context.getConceptService(). Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPTS); PackageExporter exporter = MetadataSharing.getInstance().newPackageExporter(); if (OpenmrsUtil.compareWithNullAsEarliest(new Date(), modifiedSince) > 0) { if (uuids != null) { String splitUuids[] = uuids.split(","); for (String uuid : splitUuids) { Object item = Handler.getItemByUuid(type, uuid.trim()); if (item != null) { if (modifiedSince == null || OpenmrsUtil.compareWithNullAsEarliest(Handler.getDateChanged(item), modifiedSince) > 0) { exporter.addItem(item); } } } } if (ids != null) { String splitIds[] = ids.split(","); for (String id : splitIds) { Object item = Handler.getItemById(type, Integer.valueOf(id.trim())); if (item != null) { if (modifiedSince == null || OpenmrsUtil.compareWithNullAsEarliest(Handler.getDateChanged(item), modifiedSince) > 0) { exporter.addItem(item); } } } } } exporter.getPackage().setName("Package"); exporter.getPackage().setDescription("Contains " + exporter.getPackage().getItems().size() + " items of type " + type.getSimpleName()); exporter.exportPackage(); response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=\"metadata.zip\""); MetadataZipper zipper = new MetadataZipper(); zipper.zipPackage(response.getOutputStream(), exporter.getExportedPackage().getSerializedPackage()); } finally { Context.removeProxyPrivilege(MetadataSharingConsts.MODULE_PRIVILEGE); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPTS); } } else { //TODO limit failed number of attempts by IP address sendErrorResponseAfterDelay(response, HttpServletResponse.SC_UNAUTHORIZED, "Invalid key"); } } else { sendErrorResponseAfterDelay(response, HttpServletResponse.SC_FORBIDDEN, "The remote system doesn't provide the requested service"); } }
From source file:de.innovationgate.wgpublisher.WGPRequestPath.java
protected WGPRequestPath(HttpServletRequest request, HttpServletResponse response, WGPDispatcher dispatcher) throws HttpErrorException, WGException, IOException, URIException { this.core = dispatcher.getCore(); this.queryString = request.getQueryString(); this.completeURL = buildCompleteURL(request); this.publisherURL = WGPDispatcher.getPublisherURL(request); // Extract the base part of the path - Redirect to start.jsp if no path information given this.basePath = this.getBasePath(request, dispatcher); if (this.basePath.equals("") || this.basePath.equals("/")) { if (core.getWgaConfiguration().getDefaultDatabase() == null) { this.pathType = TYPE_REDIRECT; this.resourcePath = this.publisherURL + this.core.getStartPageURL(); return; } else {/* w w w .j a v a 2 s . co m*/ this.basePath = "/" + core.getWgaConfiguration().getDefaultDatabase(); } } // Tokenize Path int tildeTokenPos = -1; java.util.StringTokenizer pathTokens = new StringTokenizer(this.basePath, "/"); String token; while (pathTokens.hasMoreTokens()) { token = pathTokens.nextToken(); this.pathElements.add(token); if (token.charAt(0) == '~') { tildeTokenPos = this.pathElements.size() - 1; } } if (this.pathElements.size() < 1) { this.pathType = TYPE_INVALID; return; } // Resolve database this.databaseKey = ((String) this.pathElements.get(0)).toLowerCase(); ; this.database = (WGDatabase) core.getContentdbs().get(this.databaseKey); // if no database under this key, try to recognize a special path command if (this.database == null) { determineSpecialPathCommand(); if (this.database == null) { return; } } // Check if we need to enforce secure app mode URL secureURL = enforceSecureAppMode(database, request); if (secureURL != null) { pathType = TYPE_REDIRECT; resourcePath = secureURL.toString(); return; } // check if db is accessed via right protocol, host and port - Must be before login so it may get redirected to some certauth port URL currentURL = new URL(request.getRequestURL().toString()); URL redirectURL = enforceRedirectionRules(database, currentURL); // currentURL differs from redirectURL - redirect necessary if (redirectURL != null && !dispatcher.isBrowserInterface(request.getSession())) { pathType = TYPE_REDIRECT; resourcePath = redirectURL.toString(); return; } // Handle special db commands "login" and "logout". The only one not requiring to login to the database if (this.pathElements.size() == 2) { if ("login".equals(this.pathElements.get(1))) { this.pathType = TYPE_REDIRECT; String sourceURL = (request.getParameter("redirect") != null ? dispatcher.getCore().getURLEncoder().decode(request.getParameter("redirect")) : WGPDispatcher.getPublisherURL(request) + "/" + this.databaseKey); this.resourcePath = dispatcher.getLoginURL(request, database, sourceURL); this.appendQueryString = false; return; } else if ("logout".equals(this.pathElements.get(1))) { this.pathType = TYPE_LOGOUT; if (request.getParameter("redirect") != null) { this.resourcePath = request.getParameter("redirect"); this.appendQueryString = false; } else { this.resourcePath = WGPDispatcher.getPublisherURL(request) + "/" + this.databaseKey; } return; } } // Open the database try { if (pathType == TYPE_STATICTML && "admintml".equals(getPathCommand()) && dispatcher.isAdminLoggedIn(request)) { this.masterLogin = true; } // Prepare HTTP credentials if available String credentials = request.getHeader("Authorization"); if (credentials != null && credentials.trim().toLowerCase().startsWith("basic")) { DBLoginInfo loginInfo = DBLoginInfo.createFromHttpCredentials(credentials); if (loginInfo != null) { // Look if ANY media key uses HTTP login. Only if so we accept this login if (isHttpLoginUsed(database)) { request.setAttribute(REQATTRIB_HTTPLOGIN, loginInfo); } } } this.database = core.openContentDB(database, request, this.masterLogin); } catch (WGUnavailableException e) { throw new HttpErrorException(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "The website is currently unavailable: " + e.getMessage(), getDatabaseKey()); } catch (de.innovationgate.wgpublisher.AuthenticationException e) { throw new HttpErrorException(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage(), null); } catch (AccessException e) { throw new HttpErrorException(HttpServletResponse.SC_FORBIDDEN, e.getMessage(), null); } if (!database.isSessionOpen()) { handleLoginFailure(request, response, dispatcher); this.proceedRequest = false; return; } // If request is static/admin tml we are done here if (pathType == TYPE_STATICTML) { return; } // If only database given, go to home page if (this.pathElements.size() == 1) { this.pathType = TYPE_GOTO_HOMEPAGE; setPermanentRedirect(core.getWgaConfiguration().isUsePermanentRedirect()); return; } // Process tilde tokens if (tildeTokenPos != -1) { String tildeToken = (String) this.pathElements.get(tildeTokenPos); // Url to file attachment via ~file-Syntax if (tildeToken.equalsIgnoreCase("~file")) { this.pathType = TYPE_FILE; List<String> preTildeTokenElems = this.pathElements.subList(1, tildeTokenPos); this.containerKey = (String) preTildeTokenElems.get(preTildeTokenElems.size() - 1); this.fileName = WGUtils.serializeCollection( this.pathElements.subList(tildeTokenPos + 1, this.pathElements.size()), "/"); return; } } // Catch special db-related urls String elem1 = ((String) this.pathElements.get(1)).toLowerCase(); int elementsSize = this.pathElements.size(); if (elementsSize >= 3 && (elem1.equals("css"))) { this.pathType = TYPE_CSS; this.cssjsKey = this.database.toLowerCaseMeta( WGUtils.serializeCollection(this.pathElements.subList(2, this.pathElements.size()), "/")); return; } else if (elementsSize >= 3 && (elem1.equals("js"))) { this.pathType = TYPE_JS; this.cssjsKey = this.database.toLowerCaseMeta( WGUtils.serializeCollection(this.pathElements.subList(2, this.pathElements.size()), "/")); return; } else if (elementsSize >= 3 && elem1.equals("file")) { this.pathType = TYPE_FILE; int fileNameIndex = determineFileNameIndex(this.pathElements, 2); this.containerKey = this.database .toLowerCaseMeta(WGUtils.serializeCollection(this.pathElements.subList(2, fileNameIndex), ":")); this.fileName = WGUtils.serializeCollection(this.pathElements.subList(fileNameIndex, elementsSize), "/"); return; } // Find out if we have a title path URL TitlePathManager tpm = (TitlePathManager) database.getAttribute(WGACore.DBATTRIB_TITLEPATHMANAGER); if (tpm != null && tpm.isGenerateTitlePathURLs()) { TitlePathManager.TitlePath url = tpm.parseTitlePathURL(pathElements.subList(1, pathElements.size())); if (url != null) { this.pathType = TYPE_TITLE_PATH; this.titlePathURL = url; this.mediaKey = core.getMediaKey(url.getMediaKey()); if (url.getLanguage() == null) { completePath = false; } } } // Path identified as normal TML request, read media and layout key if (pathType == TYPE_UNKNOWN) { pathType = TYPE_TML; int elementIdx = this.readMediaKey(core, this.pathElements, 1); elementIdx = this.readLayoutKey(core, this.pathElements, elementIdx); if (elementIdx < this.pathElements.size()) { this.contentKey = this.database.toLowerCaseMeta((String) this.pathElements.get(elementIdx)); } if (this.layoutKey == null && this.contentKey == null) { this.pathType = TYPE_INVALID; } } // Retrieve the content if (getPathType() == WGPRequestPath.TYPE_TITLE_PATH) { this.content = getContentByTitlePath(request); if (this.content == null) { pathType = TYPE_UNKNOWN_CONTENT; } // If content was retrieved with struct key we check if the title path is correct. If not we force redirection to the correct version (#00003145) else if (getTitlePathURL().getStructKey() != null) { List<String> correctTitlePath = tpm.buildTitlePath(this.content, mediaKey.getKey(), new RequestLanguageChooser(this.database, request)); if (correctTitlePath == null || !correctTitlePath.equals(getTitlePathURL().getEncodedTitles())) { completePath = false; } } // If title path is configured to include keys but the current tp has no key we force redirection to the version including a key (#00003304). else if (tpm.isIncludeKeys()) { completePath = false; } } else if (getPathType() == TYPE_TML) { if (this.contentKey != null) { URLID contentid = new URLID(this.contentKey, this.database); boolean isBI = WGPDispatcher.isBrowserInterface(request.getSession()) || WGPDispatcher.isAuthoringMode(database.getDbReference(), request.getSession()); this.content = WGPDispatcher.getContentByAnyKey(contentid, database, new RequestLanguageChooser(database, request), isBI); if (this.content != null) { // Look if we really used the parsed content URLID information. if (!contentid.isCompleteFormat()) { completePath = false; } this.requestLanguage = content.getLanguage().getName(); } else { pathType = TYPE_UNKNOWN_CONTENT; } } // Contextless request. If we have no request language we have no complete path and we must determine a language else { if (requestLanguage == null) { completePath = false; LanguageBehaviour langBehaviour = LanguageBehaviourTools.retrieve(database); WGLanguage lang = langBehaviour.requestSelectDatabaseLanguage(database, request); if (lang != null) { this.requestLanguage = lang.getName(); } // Fallback to the database default language else { this.requestLanguage = database.getDefaultLanguage(); } } } } }
From source file:alfio.controller.TicketController.java
@RequestMapping(value = "/event/{eventName}/ticket/{ticketIdentifier}/code.png", method = RequestMethod.GET) public void generateTicketCode(@PathVariable("eventName") String eventName, @PathVariable("ticketIdentifier") String ticketIdentifier, HttpServletResponse response) throws IOException, WriterException { Optional<Triple<Event, TicketReservation, Ticket>> oData = ticketReservationManager .fetchCompleteAndAssigned(eventName, ticketIdentifier); if (!oData.isPresent()) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return;/* w w w .j av a 2 s.c o m*/ } Triple<Event, TicketReservation, Ticket> data = oData.get(); Event event = data.getLeft(); Ticket ticket = data.getRight(); String qrCodeText = ticket.ticketCode(event.getPrivateKey()); response.setContentType("image/png"); response.getOutputStream().write(ImageUtil.createQRCode(qrCodeText)); }
From source file:org.jboss.as.test.integration.security.loginmodules.negotiation.SPNEGOLoginModuleTestCase.java
/** * Correct login, but without permissions. * * @throws Exception//from www. ja v a 2s .c om */ @Test @OperateOnDeployment("WEB") public void testUnsuccessfulAuthz(@ArquillianResource URL webAppURL) throws Exception { final URI servletUri = getServletURI(webAppURL, SimpleSecuredServlet.SERVLET_PATH); LOGGER.trace("Testing correct authentication, but failed authorization " + servletUri); Utils.makeCallWithKerberosAuthn(servletUri, "hnelson", "secret", HttpServletResponse.SC_FORBIDDEN); }