List of usage examples for javax.servlet.http HttpServletRequest getRemoteUser
public String getRemoteUser();
null
if the user has not been authenticated. From source file:com.pkrete.locationservice.admin.controller.mvc.AddLanguageController.java
@RequestMapping(method = RequestMethod.POST) public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("language") Language language, BindingResult result) throws Exception { Owner owner = getOwner(request); language.setOwner(owner);//from w ww . java 2 s . c o m validator.validate(language, result); if (result.hasErrors()) { return new ModelAndView("add_language", new ModelMap()); } language.setCreator(getUser(request).getUsername()); /* Save new language to DB */ if (!languagesService.create(language)) { throw new Exception("Creating language failed."); } /* Does user want to create default templates */ if (request.getParameter("templates") != null) { /* Create default templates. */ templatesService.createDefaults(language.getCode(), owner); } /* Update logged in user */ HttpSession session = request.getSession(); session.removeAttribute("user"); session.setAttribute("user", usersService.getUser(request.getRemoteUser())); /* Return to languages page */ return new ModelAndView("redirect:languages.htm"); }
From source file:org.eclipse.orion.server.git.servlets.GitCloneHandlerV1.java
private boolean handleDelete(HttpServletRequest request, HttpServletResponse response, String pathString) throws GitAPIException, CoreException, IOException, ServletException { IPath path = pathString == null ? Path.EMPTY : new Path(pathString); //expected path format is /file/{workspaceId}/{projectId}[/{directoryPath}] if (path.segment(0).equals("file") && path.segmentCount() > 2) { //$NON-NLS-1$ // make sure a clone is addressed ProjectInfo webProject = GitUtils.projectFromPath(path); if (webProject != null && isAccessAllowed(request.getRemoteUser(), webProject)) { File gitDir = GitUtils.getGitDirs(path, Traverse.CURRENT).values().iterator().next(); Repository repo = FileRepositoryBuilder.create(gitDir); repo.close();/* www . j a va 2s. co m*/ FileUtils.delete(repo.getWorkTree(), FileUtils.RECURSIVE | FileUtils.RETRY); if (path.segmentCount() == 3) return statusHandler.handleRequest(request, response, removeProject(request.getRemoteUser(), webProject)); return true; } String msg = NLS.bind("Nothing found for the given ID: {0}", path); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } String msg = NLS.bind("Invalid delete request {0}", pathString); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); }
From source file:org.apache.cocoon.servlet.DebugFilter.java
/** * Log debug information about the current environment. * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) *///from ww w. j a v a2s .c o m public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException { // we don't do debug msgs if this is not a http servlet request if (!(req instanceof HttpServletRequest)) { filterChain.doFilter(req, res); return; } try { ++activeRequestCount; final HttpServletRequest request = (HttpServletRequest) req; if (getLogger().isDebugEnabled()) { final StringBuffer msg = new StringBuffer(); msg.append("DEBUGGING INFORMATION:").append(lineSeparator); msg.append("REQUEST: ").append(request.getRequestURI()).append(lineSeparator).append(lineSeparator); msg.append("CONTEXT PATH: ").append(request.getContextPath()).append(lineSeparator); msg.append("SERVLET PATH: ").append(request.getServletPath()).append(lineSeparator); msg.append("PATH INFO: ").append(request.getPathInfo()).append(lineSeparator).append(lineSeparator); msg.append("REMOTE HOST: ").append(request.getRemoteHost()).append(lineSeparator); msg.append("REMOTE ADDRESS: ").append(request.getRemoteAddr()).append(lineSeparator); msg.append("REMOTE USER: ").append(request.getRemoteUser()).append(lineSeparator); msg.append("REQUEST SESSION ID: ").append(request.getRequestedSessionId()).append(lineSeparator); msg.append("REQUEST PREFERRED LOCALE: ").append(request.getLocale().toString()) .append(lineSeparator); msg.append("SERVER HOST: ").append(request.getServerName()).append(lineSeparator); msg.append("SERVER PORT: ").append(request.getServerPort()).append(lineSeparator) .append(lineSeparator); msg.append("METHOD: ").append(request.getMethod()).append(lineSeparator); msg.append("CONTENT LENGTH: ").append(request.getContentLength()).append(lineSeparator); msg.append("PROTOCOL: ").append(request.getProtocol()).append(lineSeparator); msg.append("SCHEME: ").append(request.getScheme()).append(lineSeparator); msg.append("AUTH TYPE: ").append(request.getAuthType()).append(lineSeparator).append(lineSeparator); msg.append("CURRENT ACTIVE REQUESTS: ").append(activeRequestCount).append(lineSeparator); // log all of the request parameters final Enumeration e = request.getParameterNames(); msg.append("REQUEST PARAMETERS:").append(lineSeparator).append(lineSeparator); while (e.hasMoreElements()) { String p = (String) e.nextElement(); msg.append("PARAM: '").append(p).append("' ").append("VALUES: '"); String[] params = request.getParameterValues(p); for (int i = 0; i < params.length; i++) { msg.append("[" + params[i] + "]"); if (i != (params.length - 1)) { msg.append(", "); } } msg.append("'").append(lineSeparator); } // log all of the header parameters final Enumeration e2 = request.getHeaderNames(); msg.append("HEADER PARAMETERS:").append(lineSeparator).append(lineSeparator); while (e2.hasMoreElements()) { String p = (String) e2.nextElement(); msg.append("PARAM: '").append(p).append("' ").append("VALUES: '"); Enumeration e3 = request.getHeaders(p); while (e3.hasMoreElements()) { msg.append("[" + e3.nextElement() + "]"); if (e3.hasMoreElements()) { msg.append(", "); } } msg.append("'").append(lineSeparator); } msg.append(lineSeparator).append("SESSION ATTRIBUTES:").append(lineSeparator).append(lineSeparator); // log all of the session attributes final HttpSession session = ((HttpServletRequest) req).getSession(false); if (session != null) { // Fix bug #12139: Session can be modified while still // being enumerated here synchronized (session) { final Enumeration se = session.getAttributeNames(); while (se.hasMoreElements()) { String p = (String) se.nextElement(); msg.append("PARAM: '").append(p).append("' ").append("VALUE: '") .append(session.getAttribute(p)).append("'").append(lineSeparator); } } } getLogger().debug(msg.toString()); } // Delegate filterChain.doFilter(request, res); } finally { --activeRequestCount; } }
From source file:alpha.portal.webapp.controller.FileUploadController.java
/** * On submit.//from ww w .java2 s .c om * * @param fileUpload * the file upload * @param errors * the errors * @param request * the request * @return the string * @throws Exception * the exception */ @RequestMapping(method = RequestMethod.POST) public String onSubmit(final FileUpload fileUpload, final BindingResult errors, final HttpServletRequest request) throws Exception { if (request.getParameter("cancel") != null) return this.getCancelView(); if (this.validator != null) { // validator is null during testing this.validator.validate(fileUpload, errors); if (errors.hasErrors()) return "fileupload"; } // validate a file was entered if (fileUpload.getFile().length == 0) { final Object[] args = new Object[] { this.getText("uploadForm.file", request.getLocale()) }; errors.rejectValue("file", "errors.required", args, "File"); return "fileupload"; } final MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; final CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file"); // the directory to upload to final String uploadDir = this.getServletContext().getRealPath("/resources") + "/" + request.getRemoteUser() + "/"; // Create the directory if it doesn't exist final File dirPath = new File(uploadDir); if (!dirPath.exists()) { dirPath.mkdirs(); } // retrieve the file data final InputStream stream = file.getInputStream(); // write the file to the file specified final OutputStream bos = new FileOutputStream(uploadDir + file.getOriginalFilename()); int bytesRead; final byte[] buffer = new byte[8192]; while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead); } bos.close(); // close the stream stream.close(); // place the data into the request for retrieval on next page request.setAttribute("friendlyName", fileUpload.getName()); request.setAttribute("fileName", file.getOriginalFilename()); request.setAttribute("contentType", file.getContentType()); request.setAttribute("size", file.getSize() + " bytes"); request.setAttribute("location", dirPath.getAbsolutePath() + Constants.FILE_SEP + file.getOriginalFilename()); final String link = request.getContextPath() + "/resources" + "/" + request.getRemoteUser() + "/"; request.setAttribute("link", link + file.getOriginalFilename()); return this.getSuccessView(); }
From source file:org.apache.qpid.server.management.plugin.servlet.rest.SaslServlet.java
protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); HttpSession session = request.getSession(); getRandom(session);/*from w w w . j av a 2s .com*/ SubjectCreator subjectCreator = getSubjectCreator(request); String[] mechanisms = subjectCreator.getMechanisms().split(" "); Map<String, Object> outputObject = new LinkedHashMap<String, Object>(); final Subject subject = getAuthorisedSubjectFromSession(session); if (subject != null) { Principal principal = AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(subject); outputObject.put("user", principal.getName()); } else if (request.getRemoteUser() != null) { outputObject.put("user", request.getRemoteUser()); } outputObject.put("mechanisms", (Object) mechanisms); final PrintWriter writer = response.getWriter(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); mapper.writeValue(writer, outputObject); }
From source file:com.tremolosecurity.scale.singlerequest.SingleRequestController.java
public void makeRequest() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest();/*from ww w .j a va 2 s .co m*/ this.error = ""; if (this.requestReason == null || this.requestReason.isEmpty()) { this.error = "Reason is required"; return; } try { WFCall wfcall = new WFCall(); wfcall.setName(this.singleRequestConfig.getWorkflowName()); wfcall.setReason(this.requestReason); wfcall.setRequestParams(new HashMap<String, Object>()); wfcall.setUidAttributeName(this.singleRequestConfig.getServiceConfiguration().getLookupAttributeName()); TremoloUser user = new TremoloUser(); ArrayList<Attribute> tuAttrs = new ArrayList<Attribute>(); tuAttrs.add(new Attribute(this.singleRequestConfig.getServiceConfiguration().getLookupAttributeName(), request.getRemoteUser())); user.setAttributes(tuAttrs); wfcall.setUser(user); // touch to ensure the session is alive StringBuffer callURL = new StringBuffer(); callURL.append( this.singleRequestConfig.getServiceConfiguration().getUnisonURL() + "/services/wf/login"); HttpGet httpget = new HttpGet(callURL.toString()); HttpResponse response = scaleSession.getHttp().execute(httpget); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = null; StringBuffer json = new StringBuffer(); while ((line = in.readLine()) != null) { json.append(line); } httpget.abort(); Gson gson = new Gson(); ProvisioningResult pres = gson.fromJson(json.toString(), ProvisioningResult.class); if (!pres.isSuccess()) { this.error = "We could not submit your request at this time, please try again later"; System.err.println(pres.getError().getError()); return; } // Execute workflow callURL.setLength(0); callURL.append( this.singleRequestConfig.getServiceConfiguration().getUnisonURL() + "/services/wf/execute"); if (logger.isDebugEnabled()) logger.debug("URL for wf : '" + callURL.toString() + "'"); String sjson = gson.toJson(wfcall); HttpPost post = new HttpPost(callURL.toString()); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("wfcall", sjson)); post.setEntity(new UrlEncodedFormEntity(urlParameters)); response = scaleSession.getHttp().execute(post); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); line = null; json.setLength(0); while ((line = in.readLine()) != null) { json.append(line); } pres = gson.fromJson(json.toString(), ProvisioningResult.class); if (!pres.isSuccess()) { this.error = "We could not submit your request at this time, please try again later"; logger.error(pres.getError().getError()); return; } else { this.singleRequestSubmitted = true; } } catch (Throwable t) { logger.error("Could not submit request", t); this.error = "We could not submit your request at this time, please try again later"; return; } }
From source file:org.opennms.web.controller.alarm.AlarmFilterController.java
private ModelAndView createListModelAndView(HttpServletRequest request, List<Filter> filterList, AcknowledgeType ackType) {// w ww . j a va2 s.c o m final AlarmQueryParms parms = createAlarmQueryParms(request, filterList, ackType); AlarmCriteria queryCriteria = new AlarmCriteria(parms); AlarmCriteria countCriteria = new AlarmCriteria(filterList, ackType); final OnmsAlarm[] alarms = m_webAlarmRepository.getMatchingAlarms(AlarmUtil.getOnmsCriteria(queryCriteria)); final long alarmCount = m_webAlarmRepository.countMatchingAlarms(AlarmUtil.getOnmsCriteria(countCriteria)); final ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("alarms", alarms); modelAndView.addObject("alarmCount", alarmCount); modelAndView.addObject("parms", new NormalizedQueryParameters(parms)); modelAndView.addObject("callback", getFilterCallback()); modelAndView.addObject("favorites", favoriteService.getFavorites(request.getRemoteUser(), OnmsFilterFavorite.Page.ALARM).toArray()); return modelAndView; }
From source file:org.auscope.portal.server.web.controllers.JobListController.java
/** * Returns a JSON object containing an array of series that match the query * parameters.// w ww .j a v a 2 s . c o m * * @param request The servlet request with query parameters * @param response The servlet response * * @return A JSON object with a series attribute which is an array of * GeodesySeries objects matching the criteria. */ @RequestMapping("/querySeries.do") public ModelAndView querySeries(HttpServletRequest request, HttpServletResponse response) { String qUser = request.getParameter("qUser"); String qName = request.getParameter("qSeriesName"); String qDesc = request.getParameter("qSeriesDesc"); if (qUser == null && qName == null && qDesc == null) { qUser = request.getRemoteUser(); logger.debug("No query parameters provided. Will return " + qUser + "'s series."); } logger.debug("qUser=" + qUser + ", qName=" + qName + ", qDesc=" + qDesc); List<GeodesySeries> series = jobManager.querySeries(qUser, qName, qDesc); logger.debug("Returning list of " + series.size() + " series."); return new ModelAndView("jsonView", "series", series); }
From source file:org.apereo.portal.layout.dlm.remoting.ChannelListController.java
private Set<IPortletDefinition> calculateFavoritePortlets(HttpServletRequest request) { /*/*from w w w.j a va 2 s .co m*/ * It's not fantastic, but the storage strategy for favorites in the layout XML doc. We * have to use it to know which portlets are favorites. */ final IUserInstance ui = userInstanceManager.getUserInstance(request); final UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager(); final IUserLayoutManager ulm = upm.getUserLayoutManager(); final IUserLayout layout = ulm.getUserLayout(); final Set<IPortletDefinition> rslt = favoritesUtils.getFavoritePortletDefinitions(layout); logger.debug("Found the following favoritePortlets for user='{}': {}", request.getRemoteUser(), rslt); return rslt; }