List of usage examples for javax.servlet.http HttpServletRequest getPathInfo
public String getPathInfo();
From source file:com.jd.survey.web.settings.DataSetController.java
@Secured({ "ROLE_ADMIN" }) @RequestMapping(method = RequestMethod.POST, produces = "text/html") public String createPost(@RequestParam(value = "_proceed", required = false) String proceed, @Valid DataSet dataSet, BindingResult bindingResult, Principal principal, Model uiModel, HttpServletRequest httpServletRequest) { log.info("create(): handles " + RequestMethod.POST.toString()); try {// w w w. j a v a 2 s . com 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, dataSet, user); return "settings/datasets/create"; } if (surveySettingsService.dataset_findByName(dataSet.getName()) != null && !surveySettingsService .dataset_findByName(dataSet.getName()).getId().equals(dataSet.getId())) { bindingResult.rejectValue("name", "field_unique"); populateEditForm(uiModel, dataSet, user); return "settings/datasets/update"; } uiModel.asMap().clear(); dataSet = surveySettingsService.dataSet_merge(dataSet); return "redirect:/settings/datasets/" + encodeUrlPathSegment(dataSet.getId().toString(), httpServletRequest); } else { return "redirect:/settings/datasets"; } } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
From source file:fr.inrialpes.exmo.align.service.HTTPTransport.java
/** * Starts a HTTP server to given port./*from w ww . j a va2 s .c o m*/ * * @param params: the parameters of the connection, including HTTP port and host * @param manager: the manager which will deal with connections * @param serv: the set of services to be listening on this connection * @throws AServException when something goes wrong (e.g., socket already in use) */ public void init(Properties params, AServProtocolManager manager, Vector<AlignmentServiceProfile> serv) throws AServException { this.manager = manager; services = serv; tcpPort = Integer.parseInt(params.getProperty("http")); tcpHost = params.getProperty("host"); // ******************************************************************** // JE: Jetty implementation server = new Server(tcpPort); // The handler deals with the request // most of its work is to deal with large content sent in specific ways Handler handler = new AbstractHandler() { public void handle(String String, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String method = request.getMethod(); String uri = request.getPathInfo(); Properties params = new Properties(); try { decodeParams(request.getQueryString(), params); } catch (Exception ex) { logger.debug("IGNORED EXCEPTION: {}", ex); } ; // I do not decode them here because it is useless // See below how it is done. Properties header = new Properties(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); header.setProperty(headerName, request.getHeader(headerName)); } // Get the content if any // This is supposed to be only an uploaded file // Note that this could be made more uniform // with the text/xml part stored in a file as well. String mimetype = request.getContentType(); // Multi part: the content provided by an upload HTML form if (mimetype != null && mimetype.startsWith("multipart/form-data")) { try { //if ( !ServletFileUpload.isMultipartContent( request ) ) { // logger.debug( "Does not detect multipart" ); //} DiskFileItemFactory factory = new DiskFileItemFactory(); File tempDir = new File(System.getProperty("java.io.tmpdir")); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); for (FileItem fi : items) { if (fi.isFormField()) { logger.trace(" >> {} = {}", fi.getFieldName(), fi.getString()); params.setProperty(fi.getFieldName(), fi.getString()); } else { logger.trace(" >> {} : {}", fi.getName(), fi.getSize()); logger.trace(" Stored at {}", fi.getName(), fi.getSize()); try { // FilenameUtils.getName() needed for Internet Explorer problem File uploadedFile = new File(tempDir, FilenameUtils.getName(fi.getName())); fi.write(uploadedFile); params.setProperty("filename", uploadedFile.toString()); params.setProperty("todiscard", "true"); } catch (Exception ex) { logger.warn("Cannot load file", ex); } // Another solution is to run this in /* InputStream uploadedStream = item.getInputStream(); ... uploadedStream.close(); */ } } ; } catch (FileUploadException fuex) { logger.trace("Upload Error", fuex); } } else if (mimetype != null && mimetype.startsWith("text/xml")) { // Most likely Web service request (REST through POST) int length = request.getContentLength(); if (length > 0) { char[] mess = new char[length + 1]; try { new BufferedReader(new InputStreamReader(request.getInputStream())).read(mess, 0, length); } catch (Exception e) { logger.debug("IGNORED Exception", e); } params.setProperty("content", new String(mess)); } // File attached to SOAP messages } else if (mimetype != null && mimetype.startsWith("application/octet-stream")) { File alignFile = new File(File.separator + "tmp" + File.separator + newId() + "XXX.rdf"); // check if file already exists - and overwrite if necessary. if (alignFile.exists()) alignFile.delete(); FileOutputStream fos = new FileOutputStream(alignFile); InputStream is = request.getInputStream(); try { byte[] buffer = new byte[4096]; int bytes = 0; while (true) { bytes = is.read(buffer); if (bytes < 0) break; fos.write(buffer, 0, bytes); } } catch (Exception e) { } finally { fos.flush(); fos.close(); } is.close(); params.setProperty("content", ""); params.setProperty("filename", alignFile.getAbsolutePath()); } // Get the answer (HTTP) HTTPResponse r = serve(uri, method, header, params); // Return it response.setContentType(r.getContentType()); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(r.getData()); ((Request) request).setHandled(true); } }; server.setHandler(handler); // Common part try { server.start(); } catch (Exception e) { throw new AServException("Cannot launch HTTP Server", e); } //server.join(); // ******************************************************************** //if ( params.getProperty( "wsdl" ) != null ){ // wsmanager = new WSAServProfile(); // if ( wsmanager != null ) wsmanager.init( params, manager ); //} //if ( params.getProperty( "http" ) != null ){ // htmanager = new HTMLAServProfile(); // if ( htmanager != null ) htmanager.init( params, manager ); //} myId = "LocalHTMLInterface"; serverId = manager.serverURL(); logger.info("Launched on {}/html/", serverId); localId = 0; }
From source file:com.jsmartframework.web.manager.ServletControl.java
private String getRedirectPath(String path, HttpServletRequest request, boolean authNeeded) { StringBuilder nextUrl = new StringBuilder(); if (authNeeded) { nextUrl.append("?").append(NEXT_URL).append("="); if (!request.getContextPath().equals("/")) { nextUrl.append(request.getContextPath()); }// w w w . j a va 2s . c o m nextUrl.append(request.getServletPath()); if (StringUtils.isNotBlank(request.getPathInfo())) { nextUrl.append(request.getPathInfo()); } if (StringUtils.isNotBlank(request.getQueryString())) { nextUrl.append(encodeUrlQuietly("?" + request.getQueryString())); } } else { String nextPath = request.getParameter(NEXT_URL); if (StringUtils.isNotBlank(nextPath)) { return nextPath; } } return (path.startsWith("/") ? request.getContextPath() : "") + path + nextUrl; }
From source file:com.liferay.petra.doulos.servlet.DoulosServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException { String remoteAddr = request.getRemoteAddr(); if (_log.isInfoEnabled()) { _log.info("Remote address: " + remoteAddr); }/*from w w w . ja v a2 s . c o m*/ if (!isValidIP(remoteAddr)) { sendError(response, "IP " + remoteAddr + " is invalid."); return; } String pathInfo = request.getPathInfo(); if (pathInfo.length() > 1) { if (pathInfo.endsWith("/")) { pathInfo = pathInfo.substring(0, pathInfo.length() - 1); } } for (Map.Entry<String, DoulosRequestProcessor> entry : _doulosRequestProcessors.entrySet()) { String doulosRequestProcessorKey = entry.getKey(); if (!pathInfo.startsWith(doulosRequestProcessorKey)) { continue; } DoulosRequestProcessor doulosRequestProcessor = entry.getValue(); if (_log.isInfoEnabled()) { _log.info(StringBundler.concat("Processing ", String.valueOf(request.getRequestURL()), " with ", String.valueOf(doulosRequestProcessor))); } try { String payload = request.getParameter("payload"); if (_log.isInfoEnabled()) { _log.info("Payload parameter: " + payload); } if (payload == null) { StringBuilder sb = new StringBuilder(); String line = null; BufferedReader bufferedReader = request.getReader(); while ((line = bufferedReader.readLine()) != null) { sb.append(line); } bufferedReader.close(); payload = sb.toString(); if (_log.isInfoEnabled()) { _log.info("Payload body: " + payload); } } JSONObject payloadJSONObject = null; if (payload.length() > 0) { payloadJSONObject = new JSONObject(payload); } else { payloadJSONObject = new JSONObject(); } JSONObject responseJSONObject = new JSONObject(); doulosRequestProcessor.process(request.getMethod(), pathInfo.substring(doulosRequestProcessorKey.length()), request.getParameterMap(), payloadJSONObject, responseJSONObject); String redirect = responseJSONObject.optString("doulosRedirect"); if (!isBlank(redirect)) { response.sendRedirect(redirect); return; } String json = responseJSONObject.toString(); write(response, new ByteArrayInputStream(json.getBytes("UTF-8"))); } catch (Exception e) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); e.printStackTrace(printWriter); String output = stringWriter.toString(); if (_log.isInfoEnabled()) { _log.info(output); } sendError(response, output); } return; } sendError(response, "Unregistered path " + request.getPathInfo() + "."); }
From source file:net.nan21.dnet.core.web.controller.ui.extjs.UiExtjsFrameController.java
/** * Handler for a frame html page./*from w w w .jav a 2s . co m*/ * * @param frame * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/{bundle}/{frameFQN}", method = RequestMethod.GET) protected ModelAndView home(@PathVariable("frameFQN") String frame, HttpServletRequest request, HttpServletResponse response) throws Exception { try { @SuppressWarnings("unused") ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } catch (java.lang.ClassCastException e) { throw new NotAuthorizedRequestException("Not authenticated"); } Map<String, Object> model = new HashMap<String, Object>(); this._prepare(model, request, response); String[] tmp = request.getPathInfo().split("/"); String frameFQN = tmp[tmp.length - 1]; String bundle = tmp[tmp.length - 2]; String[] t = frameFQN.split("\\."); String frameName = t[t.length - 1]; model.put("item", frameFQN); model.put("itemSimpleName", frameName); model.put("bundle", bundle); // get extensions model.put("extensions", getExtensionFiles(frameFQN, uiExtjsSettings.getUrlModules())); model.put("extensionsContent", getExtensionContent(frameFQN)); if (Constants.PROP_WORKING_MODE_DEV.equalsIgnoreCase(this.getSettings().get(Constants.PROP_WORKING_MODE))) { List<String> listCmp = new ArrayList<String>(); List<String> listTrl = new ArrayList<String>(); DependencyLoader loader = this.getDependencyLoader(); loader.resolveFrameDependencies(bundle, frameName, (String) model.get("shortLanguage"), listCmp, listTrl); model.put("frameDependenciesCmp", listCmp); model.put("frameDependenciesTrl", listTrl); } else { if (this.cacheFolderWritable == null) { synchronized (this) { if (this.cacheFolderWritable == null) { if (this.cacheFolder == null) { this.cacheFolder = this.getUiExtjsSettings().getCacheFolder(); } File cf = new File(this.cacheFolder); if (!cf.exists()) { if (!cf.mkdirs()) { throw new Exception("Cache folder " + this.cacheFolder + " does not exist and could not be created."); } } if (!cf.isDirectory() || !cf.canWrite()) { throw new Exception("Cache folder " + this.cacheFolder + " is not writeable. Cannot pack and cache the frame dependencies for the configured `prod` working mode. "); } this.cacheFolderWritable = true; } } } } return new ModelAndView(this.jspName, model); }
From source file:com.aipo.container.protocol.AipoDataServiceServlet.java
/** * Actual dispatch handling for servlet requests *//*from ww w. j a v a 2 s. c o m*/ protected void executeRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException { if (LOG.isLoggable(Level.FINEST)) { LOG.finest("Handling restful request for " + servletRequest.getPathInfo()); } setCharacterEncodings(servletRequest, servletResponse); SecurityToken token = getSecurityToken(servletRequest); if (token == null) { sendError(servletResponse, AipoErrorCode.TOKEN_EXPIRED); return; } if (token instanceof AipoOAuth2SecurityToken) { AipoOAuth2SecurityToken securityToken = (AipoOAuth2SecurityToken) token; String viewerId = securityToken.getViewerId(); String[] split = viewerId.split(":"); String orgId = split[0]; String userId = split[1]; String currentOrgId = Database.getDomainName(); if (currentOrgId == null) { try { DataContext dataContext = Database.createDataContext(orgId); DataContext.bindThreadObjectContext(dataContext); } catch (Throwable t) { sendError(servletResponse, AipoErrorCode.INTERNAL_ERROR); return; } } else if (!currentOrgId.equals(orgId)) { sendError(servletResponse, AipoErrorCode.INTERNAL_ERROR); return; } TurbineUser tuser = turbineUserDbService.findByUsername(userId); if (tuser == null) { sendError(servletResponse, AipoErrorCode.INVALID_UER); return; } } HttpUtil.setCORSheader(servletResponse, containerConfig.<String>getList(token.getContainer(), "gadgets.parentOrigins")); handleSingleRequest(servletRequest, servletResponse, token); }
From source file:com.palantir.stash.stashbot.servlet.BuildSuccessReportingServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try {// w ww . ja v a2s . com // Look at JenkinsManager class if you change this: // final two arguments could be empty... final String URL_FORMAT = "BASE_URL/REPO_ID/TYPE/STATE/BUILD_NUMBER/BUILD_HEAD[/MERGE_HEAD/PULLREQUEST_ID]"; final String pathInfo = req.getPathInfo(); final String[] parts = pathInfo.split("/"); if (parts.length != 6 && parts.length != 8) { throw new IllegalArgumentException("The format of the URL is " + URL_FORMAT); } final int repoId; final RepositoryConfiguration rc; try { repoId = Integer.valueOf(parts[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("The format of the URL is " + URL_FORMAT, e); } // This is necessary if we want unauthenticated users to be able to call this. *sigh* RepoIdFetcherOperation getRepoId = new RepoIdFetcherOperation(repositoryService, repoId); ss.withPermission(Permission.REPO_READ, "BUILD SUCCESS REPORT").call(getRepoId); final Repository repo = getRepoId.getRepo(); rc = configurationPersistanceManager.getRepositoryConfigurationForRepository(repo); if (repo == null) { throw new IllegalArgumentException("Unable to get a repository for id " + repoId); } JobTemplate jt = jtm.fromString(rc, parts[2].toLowerCase()); if (jt == null) { throw new IllegalArgumentException("Unable to get a valid JobTemplate from " + parts[2]); } final BuildState state = BuildState.fromString(parts[3]); if (state == null) { throw new IllegalArgumentException("The state must be 'successful', 'failed', or 'inprogress'"); } final long buildNumber; try { buildNumber = Long.parseLong(parts[4]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Unable to parse build number", e); } // TODO: ensure this hash actually exists? final String buildHead = parts[5]; final String mergeHead; final long pullRequestId; final PullRequest pullRequest; final String retUrl; if (parts.length == 8 && !parts[6].isEmpty() && !parts[7].isEmpty()) { mergeHead = parts[6]; try { // This is a pull request, so add a comment pullRequestId = Long.parseLong(parts[7]); PullRequestFetcherOperation prfo = new PullRequestFetcherOperation(pullRequestService, repoId, pullRequestId); ss.withPermission(Permission.REPO_READ, "BUILD SUCCESS REPORT").call(prfo); pullRequest = prfo.getPullRequest(); if (pullRequest == null) { throw new IllegalArgumentException("Unable to find pull request for repo id " + repo.getId() + " pr id " + Long.toString(pullRequestId)); } } catch (NumberFormatException e) { throw new IllegalArgumentException("Unable to parse pull request id " + parts[7], e); } retUrl = ub.getJenkinsTriggerUrl(repo, jt.getJobType(), buildHead, pullRequest); } else { mergeHead = null; pullRequestId = 0; pullRequest = null; retUrl = ub.getJenkinsTriggerUrl(repo, jt.getJobType(), buildHead, null); } if (mergeHead == null) { BuildStatusAddOperation bssAdder = new BuildStatusAddOperation(ub, buildStatusService, configurationPersistanceManager, plf, buildHead); bssAdder.setBuildStatus(repo, jt, state, buildNumber); // Yeah, I know what you are thinking... "Admin permission? To add a build status?" // I tried REPO_WRITE and REPO_ADMIN and neither was enough, but this worked! ss.withPermission(Permission.SYS_ADMIN, "BUILD SUCCESS REPORT").call(bssAdder); printOutput(req, res); return; } // Update the metadata. We do this before adding the comment so that any listeners consuming // comment events will have the updated state. // arg order for bools is started, success, override, failed if (state.equals(BuildState.SUCCESSFUL)) { configurationPersistanceManager.setPullRequestMetadata(pullRequest, mergeHead, buildHead, null, true, null, false); } else if (state.equals(BuildState.INPROGRESS)) { configurationPersistanceManager.setPullRequestMetadata(pullRequest, mergeHead, buildHead, true, false, null, null); } else if (state.equals(BuildState.FAILED)) { configurationPersistanceManager.setPullRequestMetadata(pullRequest, mergeHead, buildHead, null, false, null, true); } // mergeHead is not null *and* pullRequest is not null if we reach // here. final StringBuffer sb = new StringBuffer(); final String url = ub.getJenkinsBuildUrl(repo, jt, buildNumber); /* NOTE: mergeHead and buildHead are the reverse of what you might * think, because we have to check out the "toRef" becasue it is * the ref that is guaranteed to be in the correct repo. * Nonetheless, buildHead is the commit that is being merged "into" * the target branch, which is the mergeHead variable here. */ final int hashLength = 4; final String shortMergeHead = mergeHead.substring(0, hashLength); final String shortBuildHead = buildHead.substring(0, hashLength); final String mergeHeadUrl = ub.buildStashCommitUrl(repo, mergeHead); final String buildHeadUrl = ub.buildStashCommitUrl(repo, buildHead); final String mergeHeadLink = "[" + shortMergeHead + "](" + mergeHeadUrl + ")"; final String buildHeadLink = "[" + shortBuildHead + "](" + buildHeadUrl + ")"; final String consoleUrl = url + "/console"; sb.append("*[Build #" + buildNumber + "](" + url + ") "); sb.append("(merging " + mergeHeadLink + " into " + buildHeadLink + ") "); switch (state) { case INPROGRESS: sb.append("is in progress...*"); break; case SUCCESSFUL: sb.append("has **passed ✓**.*"); break; case FAILED: sb.append("has* **FAILED ✖**. "); sb.append("([*Retrigger this build* ⟳](" + retUrl + ") *or* [*view console output* ☰](" + consoleUrl + ").)"); break; } log.debug("Registering comment on pr for buildHead " + buildHead + " mergeHead " + mergeHead); // Still make comment so users can see links to build PullRequestCommentAddOperation prcao = new PullRequestCommentAddOperation(pullRequestService, repo.getId(), pullRequest.getId(), sb.toString()); // So in order to create comments, we have to do it AS some user. ss.doAsUser rather than ss.doWithPermission is the magic sauce here. JenkinsServerConfiguration jsc = configurationPersistanceManager .getJenkinsServerConfiguration(rc.getJenkinsServerName()); ApplicationUser user = us.findUserByNameOrEmail(jsc.getStashUsername()); ss.impersonating(user, "BUILD SUCCESS REPORT").call(prcao); printOutput(req, res); } catch (SQLException e) { throw new RuntimeException("Unable to get configuration", e); } catch (Exception e) { throw new RuntimeException("Unable to report build status", e); } }
From source file:org.apache.ofbiz.base.util.UtilHttp.java
public static Map<String, Object> getUrlOnlyParameterMap(HttpServletRequest request) { // NOTE: these have already been through canonicalizeParameterMap, so not doing it again here Map<String, Object> paramMap = getQueryStringOnlyParameterMap(request.getQueryString()); paramMap.putAll(getPathInfoOnlyParameterMap(request.getPathInfo(), null, null)); return paramMap; }
From source file:org.apache.karaf.cellar.http.balancer.CellarBalancerProxyServlet.java
/** * For a redirect response from the target server, this translates {@code theUrl} to redirect to * and translates it to one the original client can use. *//*from w w w . j a va2 s.c om*/ protected String rewriteUrlFromResponse(HttpServletRequest servletRequest, String theUrl, String location) { //TODO document example paths if (theUrl.startsWith(location)) { String curUrl = servletRequest.getRequestURL().toString();//no query String pathInfo = servletRequest.getPathInfo(); if (pathInfo != null) { assert curUrl.endsWith(pathInfo); curUrl = curUrl.substring(0, curUrl.length() - pathInfo.length());//take pathInfo off } theUrl = curUrl + theUrl.substring(location.length()); } return theUrl; }