List of usage examples for javax.servlet.http HttpServletRequest getRemoteUser
public String getRemoteUser();
null
if the user has not been authenticated. From source file:org.auscope.portal.server.web.controllers.GridSubmitController.java
/** * Create stageIn directories on portal host, so user can upload files easy. */*from w ww . j a v a 2 s . c o m*/ */ private boolean createLocalDir(HttpServletRequest request) { final String user = request.getRemoteUser(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); String dateFmt = sdf.format(new Date()); String jobID = user + "-" + dateFmt + File.separator; String jobInputDir = gridAccess.getLocalGridFtpStageInDir() + jobID; boolean success = (new File(jobInputDir)).mkdir(); //create rinex directory. success = (new File(jobInputDir + GridSubmitController.RINEX_DIR + File.separator)).mkdir(); //tables files. success = Util.copyFilesRecursive(new File(GridSubmitController.PRE_STAGE_IN_TABLE_FILES), new File(jobInputDir + GridSubmitController.TABLE_DIR + File.separator)); if (!success) { logger.error("Could not create local stageIn directories "); jobInputDir = gridAccess.getGridFtpStageInDir(); } // Save in session to use it when submitting job request.getSession().setAttribute("localJobInputDir", jobInputDir); return success; }
From source file:org.auscope.portal.server.web.controllers.GridSubmitController.java
/** * Returns a JSON object containing a list of the current user's series. * * @param request The servlet request//from w w w.j a va 2s . co m * @param response The servlet response * * @return A JSON object with a series attribute which is an array of * GeodesySeries objects. */ @RequestMapping("/mySeries.do") public ModelAndView mySeries(HttpServletRequest request, HttpServletResponse response) { String user = request.getRemoteUser(); logger.debug("Querying series of " + user); List<GeodesySeries> series = jobManager.querySeries(user, null, null); logger.debug("Returning list of " + series.size() + " series."); return new ModelAndView("jsonView", "series", series); }
From source file:org.auscope.portal.server.web.controllers.GridSubmitController.java
/** * Returns a JSON object containing a list of jobTypes. * * @param request The servlet request/*ww w. j av a2 s. c o m*/ * @param response The servlet response * * @return A JSON object with a series attribute which is an array of * SimpleBean objects contain available jobTypes. */ @RequestMapping("/getGetArguments.do") public ModelAndView getGetArguments(HttpServletRequest request, HttpServletResponse response) { String user = request.getRemoteUser(); logger.debug("Querying param for " + user); List<SimpleBean> params = new ArrayList<SimpleBean>(); params.add(new SimpleBean("enter args ...")); logger.debug("Returning list of " + params.size() + " params."); return new ModelAndView("jsonView", "paramLines", params); }
From source file:org.auscope.portal.server.web.controllers.GridSubmitController.java
/** * Returns a JSON object containing a list of code. * * @param request The servlet request/*from w ww . j a v a 2 s.c om*/ * @param response The servlet response * * @return A JSON object with a series attribute which is an array of * SimpleBean objects contain available code. */ @RequestMapping("/getCodeObject.do") public ModelAndView getCodeObject(HttpServletRequest request, HttpServletResponse response) { String user = request.getRemoteUser(); logger.debug("Querying code list for " + user); List<SimpleBean> code = new ArrayList<SimpleBean>(); code.add(new SimpleBean("Gamit")); code.add(new SimpleBean("Burmese")); logger.debug("Returning list of " + code.size() + " codeObject."); return new ModelAndView("jsonView", "code", code); }
From source file:org.auscope.portal.server.web.controllers.GridSubmitController.java
/** * Returns a JSON object containing a list of jobTypes. * * @param request The servlet request//from www . j a v a 2 s . com * @param response The servlet response * * @return A JSON object with a series attribute which is an array of * SimpleBean objects contain available jobTypes. */ @RequestMapping("/listJobTypes.do") public ModelAndView listJobTypes(HttpServletRequest request, HttpServletResponse response) { String user = request.getRemoteUser(); logger.debug("Querying job types list for " + user); List<SimpleBean> jobType = new ArrayList<SimpleBean>(); jobType.add(new SimpleBean("multi")); jobType.add(new SimpleBean("single")); logger.debug("Returning list of " + jobType.size() + " jobType."); return new ModelAndView("jsonView", "jobType", jobType); }
From source file:org.gbif.portal.web.controller.registration.RegistrationController.java
/** * This will send an email for approval to portal@gbif.org to ask if someone can see a providers details * //from w ww . ja va 2 s . c o m * @param request * @param response * @return * @throws Exception */ public ModelAndView sendRegistrationLoginsRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String user = request.getParameter("user"); if (StringUtils.isEmpty(user)) { user = request.getRemoteUser(); } UserLogin ul = ldapUtils.getUserLogin(user); String[] businessKeysToRemove = request.getParameterValues("businessKeyToRemove"); List<String> existingKeys = uddiUtils.getAssociatedBusinessKeys(user); // remove the selected registration logins if (businessKeysToRemove != null) { for (String element : businessKeysToRemove) { if (existingKeys.contains(element)) uddiUtils.deleteRegistrationLogin(user, element); } } // send approval email String[] businessKeys = request.getParameterValues(REQUEST_BUSINESS_UDDI_KEY); // if not businesskeys selected, non requested return to menu if (businessKeys == null) { return new ModelAndView(new RedirectView(request.getContextPath() + "/register/")); } // send verification email SimpleMailMessage verificationMessage = new SimpleMailMessage(userTemplateMessage); verificationMessage.setTo(adminEmail); verificationMessage.setSubject("User has requested access to Provider Details"); StringBuffer sb = new StringBuffer("Please click here to review request:\n\n"); sb.append("http://"); sb.append(request.getHeader("host")); sb.append(request.getContextPath()); sb.append("/register/reviewUserRequest"); sb.append("?u=" + user); for (String businessKey : businessKeys) { sb.append("&r="); sb.append(businessKey); } verificationMessage.setText(sb.toString()); try { mailSender.send(verificationMessage); } catch (MailException e) { // simply log it and go on... logger.error("Couldn't send message", e); ModelAndView mav = new ModelAndView("emailDetailsFailureView"); return mav; } // request sent view ModelAndView mav = new ModelAndView("requestSentView"); mav.addObject("userLogin", ul); return mav; }
From source file:org.openecomp.sdcrests.action.rest.services.ActionsImpl.java
@Override public Response actOnAction(String actionInvariantUuId, String requestJson, HttpServletRequest servletRequest) { Response response = null;//from www.j a v a2 s .c o m try { initializeRequestMDC(servletRequest, actionInvariantUuId, ActionRequest.ACTION_VERSIONING); log.debug("entering actOnAction with invariantUUID= " + actionInvariantUuId + " and requestJSON= " + requestJson); Map<String, String> errorMap = validateRequestHeaders(servletRequest); Map<String, String> requestBodyErrors = validateRequestBody(REQUEST_TYPE_VERSION_ACTION, requestJson); errorMap.putAll(requestBodyErrors); ActionVersionDto versionDTO = JsonUtil.json2Object(requestJson, ActionVersionDto.class); checkAndThrowError(errorMap); String status = versionDTO.getStatus(); Action action = new Action(); String user = servletRequest.getRemoteUser(); switch (status) { case "Checkout": action = actionManager.checkout(actionInvariantUuId, user); break; case "Undo_Checkout": actionManager.undoCheckout(actionInvariantUuId, user); StringWrapperResponse responseText = new StringWrapperResponse(); responseText.setValue(ActionConstants.UNDO_CHECKOUT_RESPONSE_TEXT); response = Response.status(Response.Status.OK).entity(responseText).build(); return response; case "Checkin": action = actionManager.checkin(actionInvariantUuId, user); break; case "Submit": action = actionManager.submit(actionInvariantUuId, user); break; default: throw new ActionException(ACTION_INVALID_PARAM_CODE, String.format(ACTION_UNSUPPORTED_OPERATION, status)); } ActionResponseDto actionResponseDto = new ActionResponseDto(); new MapActionToActionResponseDto().doMapping(action, actionResponseDto); response = Response.ok(actionResponseDto).build(); actionLogPostProcessor(StatusCode.COMPLETE, true); } catch (ActionException e) { actionLogPostProcessor(StatusCode.ERROR, e.getErrorCode(), e.getDescription(), true); actionErrorLogProcessor(CategoryLogLevel.ERROR, e.getErrorCode(), e.getDescription()); log.error(MDC.get(ERROR_DESCRIPTION)); throw e; } catch (Exception e) { actionLogPostProcessor(StatusCode.ERROR, true); actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); log.error(e.getMessage()); throw e; } finally { finalAuditMetricsLogProcessor(ActionRequest.ACTION_VERSIONING.name()); log.debug("exit actOnAction with invariantUUID= " + actionInvariantUuId + " and requestJSON= " + requestJson); } return response; }
From source file:com.occamlab.te.web.TestServlet.java
public void processFormData(HttpServletRequest request, HttpServletResponse response) throws ServletException { try {/* www .j a v a 2 s.c o m*/ FileItemFactory ffactory; ServletFileUpload upload; List /* FileItem */ items = null; HashMap<String, String> params = new HashMap<String, String>(); boolean multipart = ServletFileUpload.isMultipartContent(request); if (multipart) { ffactory = new DiskFileItemFactory(); upload = new ServletFileUpload(ffactory); items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } } } else { Enumeration paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String name = (String) paramNames.nextElement(); params.put(name, request.getParameter(name)); } } HttpSession session = request.getSession(); ServletOutputStream out = response.getOutputStream(); String operation = params.get("te-operation"); if (operation.equals("Test")) { TestSession s = new TestSession(); String user = request.getRemoteUser(); File logdir = new File(conf.getUsersDir(), user); String mode = params.get("mode"); RuntimeOptions opts = new RuntimeOptions(); opts.setWorkDir(conf.getWorkDir()); opts.setLogDir(logdir); if (mode.equals("retest")) { opts.setMode(Test.RETEST_MODE); String sessionid = params.get("session"); String test = params.get("test"); if (sessionid == null) { int i = test.indexOf("/"); sessionid = i > 0 ? test.substring(0, i) : test; } opts.setSessionId(sessionid); if (test == null) { opts.addTestPath(sessionid); } else { opts.addTestPath(test); } for (Entry<String, String> entry : params.entrySet()) { if (entry.getKey().startsWith("profile_")) { String profileId = entry.getValue(); int i = profileId.indexOf("}"); opts.addTestPath(sessionid + "/" + profileId.substring(i + 1)); } } s.load(logdir, sessionid); opts.setSourcesName(s.getSourcesName()); } else if (mode.equals("resume")) { opts.setMode(Test.RESUME_MODE); String sessionid = params.get("session"); opts.setSessionId(sessionid); s.load(logdir, sessionid); opts.setSourcesName(s.getSourcesName()); } else { opts.setMode(Test.TEST_MODE); String sessionid = LogUtils.generateSessionId(logdir); s.setSessionId(sessionid); String sources = params.get("sources"); s.setSourcesName(sources); SuiteEntry suite = conf.getSuites().get(sources); s.setSuiteName(suite.getId()); // String suite = params.get("suite"); // s.setSuiteName(suite); String description = params.get("description"); s.setDescription(description); opts.setSessionId(sessionid); opts.setSourcesName(sources); opts.setSuiteName(suite.getId()); ArrayList<String> profiles = new ArrayList<String>(); for (Entry<String, String> entry : params.entrySet()) { if (entry.getKey().startsWith("profile_")) { profiles.add(entry.getValue()); opts.addProfile(entry.getValue()); } } s.setProfiles(profiles); s.save(logdir); } String webdir = conf.getWebDirs().get(s.getSourcesName()); // String requestURI = request.getRequestURI(); // String contextPath = requestURI.substring(0, requestURI.indexOf(request.getServletPath()) + 1); // URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), contextPath, null, null); URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), request.getRequestURI(), null, null); opts.setBaseURI(new URL(contextURI.toURL(), webdir + "/").toString()); // URI baseURI = new URL(contextURI.toURL(), webdir).toURI(); // String base = baseURI.toString() + URLEncoder.encode(webdir, "UTF-8") + "/"; // opts.setBaseURI(base); //System.out.println(opts.getSourcesName()); TECore core = new TECore(engine, indexes.get(opts.getSourcesName()), opts); //System.out.println(indexes.get(opts.getSourcesName()).toString()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); core.setOut(ps); core.setWeb(true); Thread thread = new Thread(core); session.setAttribute("testsession", core); thread.start(); response.setContentType("text/xml"); out.println("<thread id=\"" + thread.getId() + "\" sessionId=\"" + s.getSessionId() + "\"/>"); } else if (operation.equals("Stop")) { response.setContentType("text/xml"); TECore core = (TECore) session.getAttribute("testsession"); if (core != null) { core.stopThread(); session.removeAttribute("testsession"); out.println("<stopped/>"); } else { out.println("<message>Could not retrieve core object</message>"); } } else if (operation.equals("GetStatus")) { TECore core = (TECore) session.getAttribute("testsession"); response.setContentType("text/xml"); out.print("<status"); if (core.getFormHtml() != null) { out.print(" form=\"true\""); } if (core.isThreadComplete()) { out.print(" complete=\"true\""); session.removeAttribute("testsession"); } out.println(">"); out.print("<![CDATA["); // out.print(core.getOutput()); out.print(URLEncoder.encode(core.getOutput(), "UTF-8").replace('+', ' ')); out.println("]]>"); out.println("</status>"); } else if (operation.equals("GetForm")) { TECore core = (TECore) session.getAttribute("testsession"); String html = core.getFormHtml(); core.setFormHtml(null); response.setContentType("text/html"); out.print(html); } else if (operation.equals("SubmitForm")) { TECore core = (TECore) session.getAttribute("testsession"); Document doc = DB.newDocument(); Element root = doc.createElement("values"); doc.appendChild(root); for (String key : params.keySet()) { if (!key.startsWith("te-")) { Element valueElement = doc.createElement("value"); valueElement.setAttribute("key", key); valueElement.appendChild(doc.createTextNode(params.get(key))); root.appendChild(valueElement); } } if (multipart) { Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField() && !item.getName().equals("")) { File uploadedFile = new File(core.getLogDir(), StringUtils.getFilenameFromString(item.getName())); item.write(uploadedFile); Element valueElement = doc.createElement("value"); String key = item.getFieldName(); valueElement.setAttribute("key", key); if (core.getFormParsers().containsKey(key)) { Element parser = core.getFormParsers().get(key); URL url = uploadedFile.toURI().toURL(); Element resp = core.parse(url.openConnection(), parser, doc); Element content = DomUtils.getElementByTagName(resp, "content"); if (content != null) { Element child = DomUtils.getChildElement(content); if (child != null) { valueElement.appendChild(child); } } } else { Element fileEntry = doc.createElementNS(CTL_NS, "file-entry"); fileEntry.setAttribute("full-path", uploadedFile.getAbsolutePath().replace('\\', '/')); fileEntry.setAttribute("media-type", item.getContentType()); fileEntry.setAttribute("size", String.valueOf(item.getSize())); valueElement.appendChild(fileEntry); } root.appendChild(valueElement); } } } core.setFormResults(doc); response.setContentType("text/html"); out.println("<html>"); out.println("<head><title>Form Submitted</title></head>"); out.print("<body onload=\"window.parent.update()\"></body>"); out.println("</html>"); } } catch (Throwable t) { throw new ServletException(t); } }
From source file:org.gbif.portal.web.controller.registration.RegistrationController.java
/** * Enables a user to find a provider and request access to provider details. * //from w w w . ja v a 2 s . c o m * @param request * @param response * @return * @throws Exception */ public ModelAndView findDataProvider(HttpServletRequest request, HttpServletResponse response) throws Exception { List<KeyValueDTO> providerList = uddiUtils.getProviderListAsKeyValues(); List<String> businessKeys = uddiUtils.getAssociatedBusinessKeys(request.getRemoteUser()); List<KeyValueDTO> providerRegistrationLogins = new ArrayList<KeyValueDTO>(); List<KeyValueDTO> toRemove = new ArrayList<KeyValueDTO>(); for (KeyValueDTO providerKV : providerList) { if (businessKeys.contains(providerKV.getKey())) { providerRegistrationLogins.add(providerKV); toRemove.add(providerKV); } } // remove the ones already accessible providerList.removeAll(toRemove); // view this of providers ModelAndView mav = new ModelAndView("registrationProviderList"); mav.addObject("providerList", providerList); mav.addObject("providerRegistrationLogins", providerRegistrationLogins); // if user is admin, not need to send requests if (request.isUserInRole(adminRole)) { mav.addObject("updateAction", "updateRegistrationLogins"); } else { mav.addObject("updateAction", "sendRegistrationLoginsRequest"); } return mav; }
From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebServices.java
private UserGroupInformation getCallerUserGroupInformation(HttpServletRequest hsr, boolean usePrincipal) { String remoteUser = hsr.getRemoteUser(); if (usePrincipal) { Principal princ = hsr.getUserPrincipal(); remoteUser = princ == null ? null : princ.getName(); }// w ww . j a va 2s . c o m UserGroupInformation callerUGI = null; if (remoteUser != null) { callerUGI = UserGroupInformation.createRemoteUser(remoteUser); } return callerUGI; }