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.eclipse.orion.server.git.servlets.GitIgnoreHandlerV1.java
@Override public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, String pathInfo) throws ServletException { try {// www . ja v a 2 s . c om IPath path = pathInfo == null ? Path.ROOT : new Path(pathInfo); IPath filePath = path.hasTrailingSeparator() ? path : path.removeLastSegments(1); if (!AuthorizationService.checkRights(request.getRemoteUser(), "/" + filePath.toString(), request.getMethod())) { String msg = NLS.bind("Forbidden: {0}", EncodingUtils.encodeForHTML(filePath.toString())); ServerStatus status = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, msg, null); return statusHandler.handleRequest(request, response, status); } /* TODO: Do not duplicate .gitignore entries. Traverse the working directory tree before adding .gitignore rules */ Set<Entry<IPath, File>> set = GitUtils.getGitDirs(filePath, Traverse.GO_UP).entrySet(); File gitDir = set.iterator().next().getValue(); if (gitDir == null) return false; // TODO: or an error response code, 405? switch (getMethod(request)) { case PUT: return handlePut(request, response, filePath); default: //fall through and return false below } return false; } catch (Exception e) { String msg = NLS.bind("Failed to process an ignore operation for {0}", //$NON-NLS-1$ EncodingUtils.encodeForHTML(pathInfo)); ServerStatus status = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e); LogHelper.log(status); return statusHandler.handleRequest(request, response, status); } }
From source file:org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet.java
private Subject authenticate(HttpServletRequest request, SubjectCreator subjectCreator) { Subject subject = null;// w ww .j ava2s . com String remoteUser = request.getRemoteUser(); if (remoteUser != null) { subject = authenticateUserAndGetSubject(subjectCreator, remoteUser, null); } else { String header = request.getHeader("Authorization"); if (header != null) { String[] tokens = header.split("\\s"); if (tokens.length >= 2 && "BASIC".equalsIgnoreCase(tokens[0])) { if (!isBasicAuthSupported(request)) { //TODO: write a return response indicating failure? throw new IllegalArgumentException("BASIC Authorization is not enabled."); } subject = performBasicAuth(subject, subjectCreator, tokens[1]); } } } return subject; }
From source file:de.fhg.fokus.openride.services.rating.RatingService.java
@GET @Path("summary/") @Produces("text/json") public Response getRatingsSummary(@Context HttpServletRequest con, @PathParam("username") String username) { System.out.println("getRatingsSummary start"); if (!username.equals(con.getRemoteUser())) { /*/*w w w . j a va 2 s.c o m*/ * RatingsSummary may be requested by any logged in user? * return Response.status(Response.Status.FORBIDDEN).build(); */ } CustomerEntity c = customerControllerBean.getCustomerByNickname(username); // build a List of Objects that shall be available in the JSON context. ArrayList list = new ArrayList(); list.add(new RatingsSummaryResponse()); XStream x = Utils.getJasonXStreamer(list); RatingsSummaryResponse ratingsSummary = new RatingsSummaryResponse(); ratingsSummary.setRatingsTotal(riderUndertakesRideControllerBean.getRatingsTotalByCustomer(c)); ratingsSummary.setRatingsRatioPercent( Math.round(riderUndertakesRideControllerBean.getRatingsRatioByCustomer(c) * 100)); ratingsSummary .setRatingsLatestPositive(riderUndertakesRideControllerBean.getPositiveRatingsTotalByCustomer(c)); ratingsSummary.setRatingsLatestDecent(riderUndertakesRideControllerBean.getDecentRatingsTotalByCustomer(c)); ratingsSummary .setRatingsLatestNeutral(riderUndertakesRideControllerBean.getNeutralRatingsTotalByCustomer(c)); ratingsSummary .setRatingsLatestMediocre(riderUndertakesRideControllerBean.getMediocreRatingsTotalByCustomer(c)); ratingsSummary .setRatingsLatestNegative(riderUndertakesRideControllerBean.getNegativeRatingsTotalByCustomer(c)); return Response.ok(x.toXML(ratingsSummary)).build(); }
From source file:org.scigap.iucig.controller.ScienceDisciplineController.java
@ResponseBody @RequestMapping(value = "/getUsersScienceDiscipline", method = RequestMethod.GET) public String getUsersScienceDiscipline(@RequestParam(value = "selectedCluster") String cluster, HttpServletRequest request) throws Exception { String responseJSON = null;//from www. ja va 2 s . co m String remoteUser; if (request != null) { remoteUser = request.getRemoteUser(); } else { throw new Exception("Remote user is null"); } DefaultHttpClient httpClient = new DefaultHttpClient(); String url = SCIENCE_DISCIPLINE_URL + "user/" + remoteUser + "?format=json&fields=disciplines&cluster=" + cluster; System.out.println(url); HttpRequestBase disciplines = new HttpGet(url); logger.debug("Executing REST GET request" + disciplines.getRequestLine()); try { httpClient = (DefaultHttpClient) WebClientDevWrapper.wrapClient(httpClient); HttpResponse response = httpClient.execute(disciplines); HttpEntity entity = response.getEntity(); if (entity != null && response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) { responseJSON = convertStreamToString(entity.getContent()); } EntityUtils.consume(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return responseJSON; }
From source file:org.kuali.kra.web.filter.RequestLoggingFilter.java
/** * <p>Does the actual logging. The log4j.properties file already covers user and date/time logging for us, so the * only thing that gets logged in <b>INFO</b> here is the intended action.</p> * /*from www.j a v a 2 s . co m*/ * <p><b>Inefficiency:</b>Currently, an action map is being used * to determine the intended action of the user.</p> * * <p>This is a convenience method so avoid redeclaration of variables.</p> * * @param request cast from ServletRequest * @param response cast from ServletResponse * @see #doFilter(ServletRequest,ServletResponse,FilterChain) */ private void doFilter(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (isInfoNotAllowed()) { return; } MDC.put("clientIp", request.getRemoteAddr()); LOG.info("Current User :" + request.getRemoteUser()); //RequestURI & methodToCall (request parameter) are logged to trace user actions LOG.info("RequestURI : " + request.getRequestURI()); LOG.info(getRequestParametersMessage(request, SENSITIVE_FILEDS_FILTER, paramsToLogInfoByDefault)); if (LOG.isDebugEnabled()) { LOG.debug("\n***************************** HEADERS **********************************\n" + getRequestHeadersMessage(request)); LOG.debug("\n***************************** PARAMETERS *******************************\n" + getRequestParametersMessage(request, SENSITIVE_FILEDS_FILTER)); LOG.debug("\n***************************** ATTRIBUTES *******************************\n" + getRequestAttributesMessage(request)); } }
From source file:de.fhg.fokus.openride.services.rating.RatingService.java
@GET @Produces("text/json") public Response getRatings(@Context HttpServletRequest con, @PathParam("username") String username) { System.out.println("getRatings start"); if (!username.equals(con.getRemoteUser())) { /*/*from ww w.j ava2 s.c o m*/ * Ratings may be requested by any logged in user? * return Response.status(Response.Status.FORBIDDEN).build(); */ } CustomerEntity c = customerControllerBean.getCustomerByNickname(username); // build a List of Objects that shall be available in the JSON context. ArrayList list = new ArrayList(); list.add(new ReceivedRatingResponse()); XStream x = Utils.getJasonXStreamer(list); List<RiderUndertakesRideEntity> receivedRatingsAsRider; List<RiderUndertakesRideEntity> receivedRatingsAsDriver; receivedRatingsAsRider = riderUndertakesRideControllerBean.getRatedRidesByRider(c); receivedRatingsAsDriver = riderUndertakesRideControllerBean.getRatedRidesByDriver(c); ArrayList receivedRatings = new ArrayList(); ReceivedRatingResponse response; for (RiderUndertakesRideEntity ride : receivedRatingsAsRider) { response = new ReceivedRatingResponse(); response.setCustRole("d".charAt(0)); // this is a driver's rating response.setCustId(ride.getRideId().getCustId().getCustId()); response.setCustNickname(ride.getRideId().getCustId().getCustNickname()); response.setCustGender(ride.getRideId().getCustId().getCustGender()); // TODO: This should be replaced with Timestamprealized once this is set! response.setTimestamprealized(ride.getStarttimeEarliest().getTime()); //response.setTimestamprealized(ride.getTimestamprealized().getTime()); response.setReceivedRating(ride.getReceivedrating()); response.setReceivedRatingComment(StringEscapeUtils.escapeHtml(ride.getReceivedratingComment())); receivedRatings.add(response); } for (RiderUndertakesRideEntity ride : receivedRatingsAsDriver) { response = new ReceivedRatingResponse(); response.setCustRole("r".charAt(0)); // this is a rider's rating response.setCustId(ride.getCustId().getCustId()); response.setCustNickname(ride.getCustId().getCustNickname()); response.setCustGender(ride.getCustId().getCustGender()); // TODO: This should be replaced with Timestamprealized once this is set! response.setTimestamprealized(ride.getStarttimeEarliest().getTime()); //response.setTimestamprealized(ride.getTimestamprealized().getTime()); response.setReceivedRating(ride.getGivenrating()); response.setReceivedRatingComment(ride.getGivenratingComment()); receivedRatings.add(response); } // sort receivedRatings list by timestamprealized! Collections.sort(receivedRatings); return Response.ok(x.toXML(receivedRatings)).build(); }
From source file:de.fhg.fokus.openride.services.rating.RatingService.java
@GET @Produces("text/json") @Path("open/") public Response getOpenRatings(@Context HttpServletRequest con, @PathParam("username") String username) { System.out.println("getUnratedRides start"); if (!username.equals(con.getRemoteUser())) { return Response.status(Response.Status.FORBIDDEN).build(); }// w ww .jav a 2s .co m CustomerEntity c = customerControllerBean.getCustomerByNickname(username); // build a List of Objects that shall be available in the JSON context. ArrayList list = new ArrayList(); list.add(new OpenRatingResponse()); XStream x = Utils.getJasonXStreamer(list); List<RiderUndertakesRideEntity> unratedRidesAsRider; List<RiderUndertakesRideEntity> unratedRidesAsDriver; unratedRidesAsRider = (List<RiderUndertakesRideEntity>) riderUndertakesRideControllerBean .getRidesWithoutGivenRatingByRider(c); unratedRidesAsDriver = (List<RiderUndertakesRideEntity>) riderUndertakesRideControllerBean .getRidesWithoutReceivedRatingByDriver(c); ArrayList openRatings = new ArrayList(); OpenRatingResponse response; for (RiderUndertakesRideEntity ride : unratedRidesAsRider) { response = new OpenRatingResponse(); response.setCustRole("d".charAt(0)); // this is a driver's rating response.setRiderRouteId(ride.getRiderrouteId()); response.setCustId(ride.getRideId().getCustId().getCustId()); response.setCustNickname(ride.getRideId().getCustId().getCustNickname()); response.setCustGender(ride.getRideId().getCustId().getCustGender()); // TODO: This should be replaced with Timestamprealized once this is set! response.setTimestamprealized(ride.getStarttimeEarliest().getTime()); //response.setTimestamprealized(ride.getTimestamprealized().getTime()); openRatings.add(response); } for (RiderUndertakesRideEntity ride : unratedRidesAsDriver) { response = new OpenRatingResponse(); response.setCustRole("r".charAt(0)); // this is a rider's rating response.setRiderRouteId(ride.getRiderrouteId()); response.setCustId(ride.getCustId().getCustId()); response.setCustNickname(ride.getCustId().getCustNickname()); response.setCustGender(ride.getCustId().getCustGender()); // TODO: This should be replaced with Timestamprealized once this is set! response.setTimestamprealized(ride.getStarttimeEarliest().getTime()); //response.setTimestamprealized(ride.getTimestamprealized().getTime()); openRatings.add(response); } // sort openRatings list by timestamprealized! Collections.sort(openRatings); return Response.ok(x.toXML(openRatings)).build(); }
From source file:org.apereo.portal.rest.MarketplaceRESTController.java
@RequestMapping(value = "/marketplace/{fname}/rating/{rating}", method = RequestMethod.POST) public ModelAndView saveUserRating(HttpServletRequest request, @PathVariable String fname, @PathVariable String rating, @RequestParam(required = false) String review) { Validate.notNull(rating, "Please supply a rating - should not be null"); Validate.notNull(fname, "Please supply a portlet to rate - should not be null"); marketplaceRatingDAO.createOrUpdateRating(Integer.parseInt(rating), request.getRemoteUser(), review, marketplaceService.getOrCreateMarketplacePortletDefinitionIfTheFnameExists(fname)); return new ModelAndView("json", "rating", new MarketplaceEntryRating(Integer.parseInt(rating), review)); }
From source file:com.pkrete.locationservice.admin.controller.mvc.UserInfoController.java
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }) public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); if (user == null) { user = usersService.getUser(request.getRemoteUser()); session.setAttribute("user", user); }/*from w ww . j ava 2s . c o m*/ /* Model that is returned together with the view */ java.util.Map<String, Object> model = new HashMap<String, Object>(); if (request.getParameter("save") != null) { boolean ok = true; String passOld = request.getParameter("password_old"); String passNew = request.getParameter("password_new"); String passNewControl = request.getParameter("password_new_control"); if (passOld.isEmpty()) { ok = false; model.put("errorMsgPwOld", this.messageSource.getMessage("error.userinfo.password.old.missing", null, null)); } if (passNew.isEmpty()) { ok = false; model.put("errorMsgPwNew", this.messageSource.getMessage("error.userinfo.password.new.missing", null, null)); } else if (passNew.length() < 5) { ok = false; model.put("errorMsgPwNew", this.messageSource.getMessage("error.userinfo.password.new.length", null, null)); } else if (!passNew.matches("\\w+")) { ok = false; model.put("errorMsgPwNew", this.messageSource.getMessage("error.userinfo.password.new.form", null, null)); } if (passNewControl.isEmpty()) { ok = false; model.put("errorMsgPwCtrl", this.messageSource.getMessage("error.userinfo.password.control.missing", null, null)); } if (!passNewControl.equals(passNew)) { ok = false; model.put("errorMsgPwNew", this.messageSource.getMessage("error.userinfo.password.new.match", null, null)); } if (passNew.length() > 100) { ok = false; model.put("errorMsgPwNew", this.messageSource.getMessage("error.user.password.length", null, null)); } if (passNewControl.length() > 100) { ok = false; model.put("errorMsgPwCtrl", this.messageSource.getMessage("error.user.password.length", null, null)); } if (ok) { UserFull userFull = usersService.getFullUser(user.getUsername()); String pass = this.encryptionService.encrypt(passOld); if (pass.equals(userFull.getPassword())) { String passNewCrypted = this.encryptionService.encrypt(passNew); if (!passNewCrypted.equals(userFull.getPassword())) { userFull.setUpdater(user.getUsername()); userFull.setPasswordUi(passNew); usersService.update(userFull); model.put("responseMsg", this.messageSource.getMessage("response.userinfo.password.changed", null, null)); user.setUpdated(new Date()); user.setUpdater(user.getUsername()); } else { model.put("errorMsgPwNew", this.messageSource.getMessage("error.userinfo.password.old.new.same", null, null)); } } else { model.put("errorMsgPwOld", this.messageSource.getMessage("error.userinfo.password.old.match", null, null)); } } } else if (request.getParameter("save_email") != null) { boolean ok = true; String email = request.getParameter("email"); if (email.isEmpty()) { ok = false; model.put("errorMsgEmail", this.messageSource.getMessage("error.userinfo.email.empty", null, null)); } else if (!WebUtil.validateEmail(email)) { ok = false; model.put("errorMsgEmail", this.messageSource.getMessage("error.userinfo.email.invalid", null, null)); } else if (email.length() > 100) { ok = false; model.put("errorMsgEmail", this.messageSource.getMessage("error.user.email.length", null, null)); } if (ok) { UserFull userFull = usersService.getFullUser(user.getUsername()); userFull.setUpdater(user.getUsername()); userFull.setEmail(email); usersService.update(userFull); user.setEmail(email); session.removeAttribute("user"); session.setAttribute("user", user); model.put("responseMsg", this.messageSource.getMessage("response.userinfo.email.changed", null, null)); user.setUpdated(new Date()); user.setUpdater(user.getUsername()); } } model.put("user", user); return new ModelAndView("user_info", "model", model); }
From source file:com.tremolosecurity.scale.totp.TotpController.java
@PostConstruct public void init() { this.error = null; HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest();/*from www.j a v a2s .c om*/ this.scaleTotpConfig = (ScaleTOTPConfigType) commonConfig.getScaleConfig(); this.login = request.getRemoteUser(); UnisonUserData userData; try { userData = this.scaleSession.loadUserFromUnison(this.login, new AttributeData(scaleTotpConfig.getServiceConfiguration().getLookupAttributeName(), scaleTotpConfig.getUiConfig().getDisplayNameAttribute(), scaleTotpConfig.getAttributeName())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } this.user = userData.getUserObj(); this.displayName = userData.getUserObj().getDisplayName(); ScaleAttribute scaleAttr = userData.getUserObj().getAttrs().get(scaleTotpConfig.getAttributeName()); if (scaleAttr == null) { if (logger.isDebugEnabled()) logger.debug("no sattribute"); this.error = "Token not found"; return; } this.encryptedToken = scaleAttr.getValue(); try { byte[] decryptionKeyBytes = Base64.decodeBase64(scaleTotpConfig.getDecryptionKey().getBytes("UTF-8")); SecretKey decryptionKey = new SecretKeySpec(decryptionKeyBytes, 0, decryptionKeyBytes.length, "AES"); Gson gson = new Gson(); Token token = gson.fromJson(new String(Base64.decodeBase64(this.encryptedToken.getBytes("UTF-8"))), Token.class); byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv()); IvParameterSpec spec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, decryptionKey, spec); String decryptedJSON = new String( cipher.doFinal(Base64.decodeBase64(token.getEncryptedRequest().getBytes("UTF-8")))); if (logger.isDebugEnabled()) logger.debug(decryptedJSON); TOTPKey totp = gson.fromJson(decryptedJSON, TOTPKey.class); this.otpURL = "otpauth://totp/" + totp.getUserName() + "@" + totp.getHost() + "?secret=" + totp.getSecretKey(); } catch (Exception e) { e.printStackTrace(); this.error = "Could not decrypt token"; } try { int size = 250; Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix byteMatrix = qrCodeWriter.encode(this.otpURL, BarcodeFormat.QR_CODE, size, size, hintMap); int CrunchifyWidth = byteMatrix.getWidth(); BufferedImage image = new BufferedImage(CrunchifyWidth, CrunchifyWidth, BufferedImage.TYPE_INT_RGB); image.createGraphics(); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth); graphics.setColor(Color.BLACK); for (int i = 0; i < CrunchifyWidth; i++) { for (int j = 0; j < CrunchifyWidth; j++) { if (byteMatrix.get(i, j)) { graphics.fillRect(i, j, 1, 1); } } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "png", baos); this.encodedQRCode = new String(Base64.encodeBase64(baos.toByteArray())); } catch (Exception e) { e.printStackTrace(); this.error = "Could not encode QR Code"; } }