List of usage examples for javax.servlet.http HttpServletRequest getPathInfo
public String getPathInfo();
From source file:net.sourceforge.vulcan.web.ProjectFileServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String pathInfo = request.getPathInfo(); if (isBlank(pathInfo)) { response.sendRedirect(request.getContextPath()); return;/*w ww. java2 s .co m*/ } final PathInfo projPathInfo = getProjectNameAndBuildNumber(pathInfo); if (isBlank(projPathInfo.projectName)) { response.sendRedirect(request.getContextPath()); return; } final ProjectConfigDto projectConfig; try { projectConfig = projectManager.getProjectConfig(projPathInfo.projectName); } catch (NoSuchProjectException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final String requestURI = request.getRequestURI(); if (projPathInfo.buildNumber < 0) { redirectWithBuildNumber(response, projPathInfo, requestURI); return; } final ProjectStatusDto buildOutcome = buildManager.getStatusByBuildNumber(projPathInfo.projectName, projPathInfo.buildNumber); if (buildOutcome == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "No such build " + projPathInfo.buildNumber + " for project Project."); return; } final String workDir; if (StringUtils.isNotBlank(buildOutcome.getWorkDir())) { workDir = buildOutcome.getWorkDir(); } else { workDir = projectConfig.getWorkDir(); } final File file = getFile(workDir, pathInfo, true); if (!file.exists()) { if (shouldFallback(request, workDir, file)) { response.sendRedirect(getFallbackParentPath(request, workDir)); return; } response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } else if (!file.canRead()) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } else if (file.isDirectory()) { if (!pathInfo.endsWith("/")) { response.sendRedirect(requestURI + "/"); return; } final File[] files = getDirectoryListing(file); request.setAttribute(Keys.DIR_PATH, pathInfo); request.setAttribute(Keys.FILE_LIST, files); request.getRequestDispatcher(Keys.FILE_LIST_VIEW).forward(request, response); return; } setContentType(request, response, pathInfo); final Date lastModifiedDate = new Date(file.lastModified()); if (!checkModifiedSinceHeader(request, lastModifiedDate)) { response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } response.setStatus(HttpServletResponse.SC_OK); setLastModifiedDate(response, lastModifiedDate); response.setContentLength((int) file.length()); final FileInputStream fis = new FileInputStream(file); final ServletOutputStream os = response.getOutputStream(); sendFile(fis, os); }
From source file:com.ibm.util.merge.web.rest.servlet.RequestData.java
public RequestData(HttpServletRequest request) { method = request.getMethod();//w w w . ja v a 2 s. c o m byte[] bytes = readRequestBody(request); requestBody = bytes; contentType = request.getContentType(); preferredLocale = request.getLocale(); List<Locale> tlocales = getAllRequestLocales(request); locales = new ArrayList<>(tlocales); params = request.getParameterMap(); pathInfo = request.getPathInfo(); queryString = request.getQueryString(); Map<String, List<String>> headerValues = readHeaderValues(request); headers = headerValues; requestUrl = request.getRequestURL().toString(); }
From source file:net.hedtech.banner.filters.ZKPageFilter2.java
private String extractRequestPath(HttpServletRequest request) { String servletPath = request.getServletPath(); String pathInfo = request.getPathInfo(); String query = request.getQueryString(); return (servletPath == null ? "" : servletPath) + (pathInfo == null ? "" : pathInfo) + (query == null ? "" : ("?" + query)); }
From source file:com.jd.survey.web.settings.SectorsController.java
@Secured({ "ROLE_ADMIN" }) @RequestMapping(method = RequestMethod.PUT, produces = "text/html") public String update(@RequestParam(value = "_proceed", required = false) String proceed, @Valid Sector sector, BindingResult bindingResult, Principal principal, Model uiModel, HttpServletRequest httpServletRequest) { log.info("update(): handles PUT"); try {// w w w. j ava 2s. c o m User user = userService.user_findByLogin(principal.getName()); if (!user.isAdmin()) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); return "accessDenied"; } if (proceed != null) { if (bindingResult.hasErrors()) { populateEditForm(uiModel, sector, user); return "admin/sectors/update"; } if (surveySettingsService.dataset_findByName(sector.getName()) != null && !surveySettingsService .dataset_findByName(sector.getName()).getId().equals(sector.getId())) { bindingResult.rejectValue("name", "field_unique"); populateEditForm(uiModel, sector, user); return "admin/sectors/update"; } uiModel.asMap().clear(); sector = surveySettingsService.sector_merge(sector); return "redirect:/admin/sectors/" + encodeUrlPathSegment(sector.getId().toString(), httpServletRequest); } else { return "redirect:/admin/sectors"; } } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
From source file:com.buglabs.bug.ws.program.ProgramServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = req.getPathInfo(); if (path == null) { log.log(LogService.LOG_WARNING, "Error: null program path."); resp.sendError(665, "Error: invalid program path."); return;//from w w w .j av a2 s.c o m } String[] toks = path.split("/"); String jarName = toks[toks.length - 1]; File bundleDir = new File(incomingBundleDir); if (!bundleDir.exists()) { log.log(LogService.LOG_ERROR, "Unable to save bundle; can't create file."); resp.sendError(0, "Unable to save bundle; can't create file."); } Bundle existingBundle = findBundleByName(jarName); if (existingBundle != null) { try { uninstallBundle(existingBundle); } catch (BundleException e) { log.log(LogService.LOG_ERROR, "Unable to uninstall existing bundle. Aborting install.", e); } } File jarFile = new File(bundleDir.getAbsolutePath() + File.separator + jarName + ".jar"); FileOutputStream fos = new FileOutputStream(jarFile); IOUtils.copy(req.getInputStream(), fos); fos.flush(); fos.close(); //Tell knapsack to start the bundle. jarFile.setExecutable(true); initService.updateBundles(); resp.getWriter().println(HTTP_OK_RESPONSE); req.getInputStream().close(); }
From source file:com.imaginary.home.cloud.api.RestApi.java
private String[] getPath(@Nonnull HttpServletRequest req) { String p = req.getPathInfo().toLowerCase(); while (p.startsWith("/") && !p.equals("/")) { p = p.substring(1);// www. j av a 2 s . c om } while (p.endsWith("/") && !p.equals("/")) { p = p.substring(p.length() - 1); } String[] parts = p.split("/"); if (parts.length < 1) { if (p.equals("") || p.equals("/")) { parts = new String[0]; } else { parts = new String[] { p }; } } return parts; }
From source file:com.palantir.stash.stashbot.servlet.BuildStatusReportingServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try {//from w w w. j av a2s . c o m // Look at JenkinsManager class if you change this: // final two arguments could be empty... final String URL_FORMAT = "BASE_URL/REPO_ID_OR_SLUG/PULLREQUEST_ID]"; final String pathInfo = req.getPathInfo(); final String[] parts = pathInfo.split("/"); // need at *least* 3 parts to be correct if (parts.length < 3) { throw new IllegalArgumentException("The format of the URL is " + URL_FORMAT); } // Last part is always the PR String pullRequestPart = parts[parts.length - 1]; // First part is always empty because string starts with '/', last is pr, the rest is the slug String slugOrId = StringUtils.join(Arrays.copyOfRange(parts, 1, parts.length - 1), "/"); Repository repo; try { int repoId = Integer.valueOf(slugOrId); repo = rs.getById(repoId); if (repo == null) { throw new IllegalArgumentException("Unable to find repository for repo id " + repoId); } } catch (NumberFormatException e) { // we have a slug, try to get a repo ID from that // slug should look like this: projects/PROJECT_KEY/repos/REPO_SLUG/pull-requests String[] newParts = slugOrId.split("/"); if (newParts.length != 5) { throw new IllegalArgumentException( "The format of the REPO_ID_OR_SLUG is an ID, or projects/PROJECT_KEY/repos/REPO_SLUG/pull-requests"); } Project p = ps.getByKey(newParts[1]); if (p == null) { throw new IllegalArgumentException("Unable to find project for project key" + newParts[1]); } repo = rs.getBySlug(p.getKey(), newParts[3]); if (repo == null) { throw new IllegalArgumentException("Unable to find repository for project key" + newParts[1] + " and repo slug " + newParts[3]); } } final long pullRequestId; final PullRequest pullRequest; try { pullRequestId = Long.parseLong(pullRequestPart); } catch (NumberFormatException e) { throw new IllegalArgumentException("Unable to parse pull request id " + parts[7], e); } pullRequest = prs.getById(repo.getId(), pullRequestId); if (pullRequest == null) { throw new IllegalArgumentException("Unable to find pull request for repo id " + repo.getId().toString() + " pr id " + pullRequestId); } PullRequestMergeability canMerge = prs.canMerge(repo.getId(), pullRequestId); JSONObject output = new JSONObject(); output.put("repoId", repo.getId()); output.put("prId", pullRequestId); output.put("url", nb.repo(repo).pullRequest(pullRequest.getId()).buildAbsolute()); output.put("canMerge", canMerge.canMerge()); if (!canMerge.canMerge()) { JSONArray vetoes = new JSONArray(); for (PullRequestMergeVeto prmv : canMerge.getVetos()) { JSONObject prmvjs = new JSONObject(); prmvjs.put("summary", prmv.getSummaryMessage()); prmvjs.put("details", prmv.getDetailedMessage()); vetoes.put(prmvjs); } // You might expect a conflict would be included in the list of merge blockers. You'd be mistaken. if (canMerge.isConflicted()) { JSONObject prmvjs = new JSONObject(); prmvjs.put("summary", "This pull request is unmergeable due to conflicts."); prmvjs.put("details", "You will need to resolve conflicts to be able to merge."); vetoes.put(prmvjs); } output.put("vetoes", vetoes); } log.debug("Serving build status: " + output.toString()); printOutput(output, req, res); } catch (Exception e) { res.reset(); res.setStatus(500); res.setContentType("application/json"); Writer w = res.getWriter(); try { w.append(new JSONObject().put("error", e.getMessage()).toString()); } catch (JSONException e1) { throw new RuntimeException("Errorception!", e1); } w.close(); } }
From source file:ch.entwine.weblounge.kernel.site.SiteServlet.java
/** * Depending on whether a call to a jsp is made or not, delegates to the * jasper servlet with a controlled context class loader or tries to load the * requested file from the bundle as a static resource. * //from www .j a v a 2 s .c o m * @see HttpServlet#service(HttpServletRequest, HttpServletResponse) */ @Override public void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { String filename = FilenameUtils.getName(request.getPathInfo()); // Don't allow listing the root directory? if (StringUtils.isBlank(filename)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } // Check the requested format. In case of a JSP, this can either be // processed (default) or raw, in which case the file contents are // returned rather than Jasper's output of it. Format format = Format.Processed; String f = request.getParameter(PARAM_FORMAT); if (StringUtils.isNotBlank(f)) { try { format = Format.valueOf(StringUtils.capitalize(f.toLowerCase())); } catch (IllegalArgumentException e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } } if (Format.Processed.equals(format) && filename.endsWith(".jsp")) { serviceJavaServerPage(request, response); } else { serviceResource(request, response); } }
From source file:org.gooru.insights.api.security.MethodAuthorizationAspect.java
private boolean isValidUser(JSONObject jsonObject, HttpServletRequest request) { try {/*w w w.j av a 2 s . co m*/ String userUidFromSession = jsonObject.getString(ApiConstants.PARTY_UId); String userIdFromRequest = RequestUtils.getUserIdFromRequestParam(request); String classId = null; String pathInfo = request.getPathInfo(); if (pathInfo.startsWith("/class/")) { String[] pathParts = pathInfo.split("/"); classId = pathParts[2]; } else { classId = RequestUtils.getClassIdFromRequestParam(request); } logger.info("userUidFromSession : {} - userIdFromRequest {} - classId : {}", userUidFromSession, userIdFromRequest, classId); if (StringUtils.isBlank(userIdFromRequest) && "ANONYMOUS".equalsIgnoreCase(userUidFromSession)) { InsightsLogger.info("ANONYMOUS user can't be a teacher class creator"); return false; } else if (StringUtils.isNotBlank(userIdFromRequest) && userIdFromRequest.equalsIgnoreCase(userUidFromSession)) { return true; } else if (StringUtils.isNotBlank(classId) && userUidFromSession.equalsIgnoreCase(getTeacherUid(classId))) { return true; } } catch (Exception e) { InsightsLogger.error("Exception", e); } return false; }
From source file:com.lyncode.oai.proxy.ProxyDataProvider.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ProxyIdentify identify = new ProxyIdentify(req); ProxySetRepository listsets = new ProxySetRepository(); ProxyItemRepository itemRepository = new ProxyItemRepository(); try {/* w ww .j av a2 s . c o m*/ XOAIManager.initialize("config" + File.separator + "xoai"); log.debug("Creating XOAI Data Provider Instance"); log.debug("Requested context: " + req.getPathInfo().replace("/", "")); OAIDataProvider dataprovider = new OAIDataProvider(req.getPathInfo().replace("/", ""), identify, listsets, itemRepository); log.debug("Reading parameters from request"); OutputStream out = resp.getOutputStream(); OAIRequestParameters parameters = new OAIRequestParameters(); parameters.setFrom(req.getParameter("from")); parameters.setUntil(req.getParameter("until")); parameters.setSet(req.getParameter("set")); parameters.setVerb(req.getParameter("verb")); parameters.setMetadataPrefix(req.getParameter("metadataPrefix")); parameters.setIdentifier(req.getParameter("identifier")); parameters.setResumptionToken(req.getParameter("resumptionToken")); resp.setContentType("application/xml"); dataprovider.handle(parameters, out); out.flush(); out.close(); } catch (InvalidContextException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Requested OAI context \"" + req.getPathInfo().replace("/", "") + "\" does not exist"); } catch (OAIException e) { log.error(e.getMessage(), e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred, please, contact the develop team development@lyncode.com"); } catch (com.lyncode.xoai.dataprovider.exceptions.ConfigurationException e) { log.error(e.getMessage(), e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred, please, contact the develop team development@lyncode.com"); } }