Example usage for javax.servlet.http HttpServletRequest getRemoteUser

List of usage examples for javax.servlet.http HttpServletRequest getRemoteUser

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRemoteUser.

Prototype

public String getRemoteUser();

Source Link

Document

Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.

Usage

From source file:com.openkm.servlet.admin.CronTabServlet.java

/**
 * Download script or jar/*from   w w w .j  av  a 2s  .  c o  m*/
 */
private void download(HttpServletRequest request, HttpServletResponse response)
        throws IOException, DatabaseException {
    log.debug("download({}, {})", new Object[] { request, response });
    int ctId = WebUtils.getInt(request, "ct_id");
    CronTab ct = CronTabDAO.findByPk(ctId);
    ByteArrayInputStream bais = null;

    try {
        byte[] content = SecureStore.b64Decode(ct.getFileContent());
        bais = new ByteArrayInputStream(content);
        WebUtils.sendFile(request, response, ct.getFileName(), ct.getFileMime(), false, bais);
    } finally {
        IOUtils.closeQuietly(bais);
    }

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_CRONTAB_DOWNLOAD", Integer.toString(ctId), null,
            ct.toString());
    log.debug("download: void");
}

From source file:com.datatorrent.stram.webapp.StramWebServices.java

Boolean hasAccess(HttpServletRequest request) {
    String remoteUser = request.getRemoteUser();
    if (remoteUser != null) {
        UserGroupInformation callerUGI = UserGroupInformation.createRemoteUser(remoteUser);
        if (callerUGI != null) {
            return false;
        }//from  w w  w . j  a v  a  2s .  c o m
    }
    return true;
}

From source file:com.tremolosecurity.scale.user.ScaleUser.java

@PostConstruct
public void init() {
    try {/*from w  w  w .j  a  v  a 2  s. c  om*/
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                .getRequest();
        this.login = request.getRemoteUser();

        UserObj userObj = loadUserFromUnison(this.login, scaleConfig.getAttributeData());

        this.displayName = userObj.getDisplayName();
        this.groups = userObj.getGroups();
        this.attributes = userObj.getAttributes();

        this.orgTree = null;

        this.loadURLs();
        this.loadReports();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.edgenius.core.webapp.filter.LocaleFilter.java

public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    //       if(log.isDebugEnabled()){
    //          log.debug("Request URL: " + request.getRequestURI());
    //       }//  w w w.  j a v a 2 s. c o m

    //charset encoding
    if (!StringUtils.isEmpty(this.encoding))
        request.setCharacterEncoding(encoding);
    else
        request.setCharacterEncoding(Constants.UTF8);

    String direction = null;
    Locale preferredLocale = null;
    TimeZone timezone = null;
    HttpSession session = request.getSession(false);
    if (getUserService() != null) { //for Install mode, it will return null
        User user = getUserService().getUserByName(request.getRemoteUser());
        if (user != null && !user.isAnonymous()) {
            //locale
            UserSetting set = user.getSetting();
            String userLang = set.getLocaleLanguage();
            String userCountry = set.getLocaleCountry();
            if (userLang != null && userCountry != null) {
                preferredLocale = new Locale(userLang, userCountry);
            }
            //text direction in HTML 
            direction = set.getDirection();
            //timezone
            if (set.getTimeZone() != null)
                timezone = TimeZone.getTimeZone(set.getTimeZone());
        }
    }
    if (preferredLocale == null) {
        if (Global.DetectLocaleFromRequest) {
            Locale locale = request.getLocale();
            if (locale != null) {
                preferredLocale = locale;
            }
        }
        if (preferredLocale == null) {
            preferredLocale = Global.getDefaultLocale();
        }
    }

    if (direction == null) {
        direction = Global.DefaultDirection;
    }

    if (timezone == null) {
        if (session != null) {
            //try to get timezone from HttpSession, which will be intial set in SecurityControllerImpl.checkLogin() method
            timezone = (TimeZone) session.getAttribute(Constants.TIMEZONE);
        }
        if (timezone == null)
            timezone = TimeZone.getTimeZone(Global.DefaultTimeZone);
    }

    //set locale for STURTS and JSTL
    // set the time zone - must be set for dates to display the time zone
    if (session != null) {
        Config.set(session, Config.FMT_LOCALE, preferredLocale);
        session.setAttribute(Constants.DIRECTION, direction);
        Config.set(session, Config.FMT_TIME_ZONE, timezone);
    }

    //replace request by LocaleRequestWrapper
    if (!(request instanceof LocaleRequestWrapper)) {
        request = new LocaleRequestWrapper(request, preferredLocale);
        LocaleContextConfHolder.setLocale(preferredLocale);
    }

    if (chain != null) {
        request.setAttribute(PREFERRED_LOCALE, preferredLocale.toString());
        chain.doFilter(request, response);
    }
    // Reset thread-bound LocaleContext.
    LocaleContextConfHolder.setLocaleContext(null);
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.FileUploadController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(MetadataPackage metadataPackage, BindingResult errors, HttpServletRequest request)
        throws Exception {

    if (request.getParameter("cancel") != null) {
        return getCancelView();
    }//from w  ww.j  ava  2 s.  co m
    Locale locale = request.getLocale();
    if (validator != null) { // validator is null during testing
        validator.validate(metadataPackage, errors);

        if (errors.hasErrors()) {
            return "packageupload";
        }
    }

    // validate a file was entered
    if (metadataPackage.getFile().length == 0) {
        Object[] args = new Object[] { getText("uploadForm.file", request.getLocale()) };
        errors.rejectValue("file", "errors.required", args, "File");

        return "packageupload";
    }
    saveMessage(request, getText("package.uploaded", locale));
    User uname;

    log.debug("" + userManager.getUserByUsername(request.getRemoteUser()));
    uname = userManager.getUserByUsername(request.getRemoteUser());

    // Deserializing the package
    MetadataPackage pkg = packageManager.deserializePackage(metadataPackage.getFile());
    metadataPackage.setUser(uname);
    metadataPackage.setFields(pkg);
    MetadataPackage meta = packageManager.savePackage(metadataPackage);
    Long id = meta.getId();

    return getSuccessView() + "?id=" + meta.getId();
}

From source file:alpha.portal.webapp.controller.UserFormController.java

/**
 * Show form.//from   ww  w.j av a2 s. c o m
 * 
 * @param request
 *            the request
 * @param response
 *            the response
 * @return the model and view
 * @throws Exception
 *             the exception
 */
@ModelAttribute
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
protected ModelAndView showForm(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {

    final ModelAndView model = new ModelAndView();
    User user;

    // If not an administrator, make sure user is not trying to add or edit
    // another user
    if (!request.isUserInRole(Constants.ADMIN_ROLE) && !this.isFormSubmission(request)) {
        if (this.isAdd(request) || (request.getParameter("id") != null)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            this.log.warn("User '" + request.getRemoteUser() + "' is trying to edit user with id '"
                    + request.getParameter("id") + "'");

            throw new AccessDeniedException("You do not have permission to modify other users.");
        }
    }

    if (!this.isFormSubmission(request)) {
        final String userId = request.getParameter("id");

        // if user logged in with remember me, display a warning that they
        // can't change passwords
        this.log.debug("checking for remember me login...");

        final AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
        final SecurityContext ctx = SecurityContextHolder.getContext();

        if (ctx.getAuthentication() != null) {
            final Authentication auth = ctx.getAuthentication();

            if (resolver.isRememberMe(auth)) {
                request.getSession().setAttribute("cookieLogin", "true");

                // add warning message
                this.saveMessage(request, this.getText("userProfile.cookieLogin", request.getLocale()));
            }
        }

        if ((userId == null) && !this.isAdd(request)) {
            user = this.getUserManager().getUserByUsername(request.getRemoteUser());
        } else if (!StringUtils.isBlank(userId) && !"".equals(request.getParameter("version"))) {
            user = this.getUserManager().getUser(userId);
        } else {
            user = new User();
            user.addRole(new Role(Constants.USER_ROLE));
        }

        user.setConfirmPassword(user.getPassword());

        UserExtension userExtension;
        final Long uId = user.getId();
        if ((uId != null) && this.userExtensionManager.exists(uId)) {
            userExtension = this.userExtensionManager.get(uId);
        } else {
            userExtension = new UserExtension(user);
        }

        model.addObject("userExtension", userExtension);
        model.addObject("contributorRoles", this.contributorRoleManager.getAll());

    } else {
        // populate user object from database, so all fields don't need to
        // be hidden fields in form
        user = this.getUserManager().getUser(request.getParameter("id"));
    }

    model.addObject("user", user);

    return model;
}

From source file:org.opennms.web.asset.ImportAssetsServlet.java

/**
 * {@inheritDoc}//  www. j av a2  s . co  m
 *
 * Acknowledge the events specified in the POST and then redirect the client
 * to an appropriate URL for display.
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String assetsText = request.getParameter("assetsText");

    if (assetsText == null) {
        logger.error("assetsText was null");
        throw new MissingParameterException("assetsText");
    }

    try {
        List<Asset> assets = this.decodeAssetsText(assetsText);
        List<Integer> nodesWithAssets = this.getCurrentAssetNodesList();

        for (Asset asset : assets) {
            // update with the current information
            asset.setUserLastModified(request.getRemoteUser());
            asset.setLastModifiedDate(new Date());

            if (nodesWithAssets.contains(Integer.valueOf(asset.getNodeId()))) {
                logger.debug("modifyAsset call for asset:'{}'", asset);
                this.model.modifyAsset(asset);
            } else {
                logger.debug("createAsset:'{}'", asset);
                this.model.createAsset(asset);
            }
        }

        StringBuffer messageText = new StringBuffer();
        messageText.append("Successfully imported ").append(assets.size()).append(" asset");
        if (assets.size() > 1) {
            messageText.append("s");
        }
        messageText.append(".");

        if (errors.size() > 0) {
            messageText.append("  ").append(errors.size()).append(" non-fatal errors occurred:");
            for (String error : errors) {
                messageText.append("<br />").append(error);
            }
        }

        request.getSession().setAttribute("message", messageText.toString());
        response.sendRedirect(response.encodeRedirectURL(this.redirectSuccess + "&showMessage=true"));
    } catch (AssetException e) {
        String message = "Error importing assets: " + e.getMessage();
        redirectWithErrorMessage(request, response, e, message);
    } catch (SQLException e) {
        String message = "Database exception importing assets: " + e.getMessage();
        redirectWithErrorMessage(request, response, e, message);
    }
}

From source file:alpha.portal.webapp.controller.UserFormController.java

/**
 * On user role save.//from w  w  w  .  j  ava  2s. c  o  m
 * 
 * @param jspUserExtension
 *            the jsp user extension
 * @param request
 *            the request
 * @param response
 *            the response
 * @return the string
 */
@RequestMapping(method = RequestMethod.POST, params = { "saveRoles" })
public String onUserRoleSave(final UserExtension jspUserExtension, final HttpServletRequest request,
        final HttpServletResponse response) {
    // parameters when editing users as an admin
    final String id = request.getParameter("id");
    final String from = request.getParameter("from");
    Long idL = null;
    if (id != null) {
        try {
            idL = Long.parseLong(id);
        } catch (final NumberFormatException e) {
            return "redirect:/caseMenu";
        }
    }
    // get current user for checks
    final User user = this.getUserManager().getUserByUsername(request.getRemoteUser());
    // check whether id exists and user is allowed to edit this one
    if (((id != null) && !this.getUserManager().exists(idL))
            || ((id != null) && (idL != user.getId()) && !request.isUserInRole(Constants.ADMIN_ROLE)))
        return "redirect:/caseMenu";
    // reload UserExtension from database or create a new one
    UserExtension userExtension;
    // if user is editing himself
    if (id == null) {
        if (this.userExtensionManager.exists(user.getId())) {
            userExtension = this.userExtensionManager.get(user.getId());
        } else {
            userExtension = new UserExtension(this.getUserManager().get(user.getId()));
        }
    } else {// if admin is editing other users
        if (this.userExtensionManager.exists(idL)) {
            userExtension = this.userExtensionManager.get(idL);
        } else {
            userExtension = new UserExtension(this.getUserManager().get(idL));
        }
    }
    // parse submitted roleIds to ContributorRole
    final Set<ContributorRole> roles = new HashSet<ContributorRole>();
    if ((jspUserExtension != null) && (jspUserExtension.getRoles() != null)) {
        for (final ContributorRole jspRole : jspUserExtension.getRoles()) {
            Long roleId = null;
            try {
                // WTF, Spring puts the submitted roleIds into name!
                roleId = Long.parseLong(jspRole.getName());
            } catch (final NumberFormatException e) {
                this.saveError(request, "userextension.invalidRole");
                continue;
            }
            if (!this.contributorRoleManager.exists(roleId)) {
                this.saveError(request, "userextension.invalidRole");
                continue;
            } else {
                roles.add(this.contributorRoleManager.get(roleId));
            }
        }
    }
    userExtension.setRoles(roles);
    userExtension = this.userExtensionManager.save(userExtension);

    return "redirect:/userform?id=" + userExtension.getUserId() + (from != null ? "&from=" + from : "");

}

From source file:org.egov.services.zuulproxy.filter.ZuulProxyFilter.java

private String getUserInfo(final HttpServletRequest request, final WebApplicationContext springContext,
        final String tenantId) {
    final HttpSession session = request.getSession();
    String userInfoJson = null;/*from w ww.  ja va 2  s  .  c o m*/

    if (session.getAttribute(USER_INFO_FIELD_NAME) != null)
        userInfoJson = session.getAttribute(USER_INFO_FIELD_NAME).toString();

    if (log.isInfoEnabled())
        log.info("userInfo is from the session... " + userInfoJson);

    if (StringUtils.isBlank(userInfoJson)) {
        final UserService userService = (UserService) springContext.getBean(USER_SERVICE);
        final CurrentUser userDetails = new CurrentUser(userService.getUserByUsername(request.getRemoteUser()));

        final User user = userDetails.getUser();

        final List<Role> roles = new ArrayList<Role>();
        userDetails.getUser().getRoles().forEach(authority -> roles.add(new Role(authority.getName())));

        final UserInfo userInfo = new UserInfo(roles, userDetails.getUserId(), userDetails.getUsername(),
                user.getName(), user.getEmailId(), user.getMobileNumber(), userDetails.getUserType().toString(),
                tenantId);
        final ObjectMapper mapper = new ObjectMapper();
        try {
            userInfoJson = mapper.writeValueAsString(userInfo);
        } catch (final JsonProcessingException e) {
            throw new ApplicationRuntimeException("Could not convert object to json string", e);
        }
        if (log.isInfoEnabled())
            log.info("Read userInfo from the DB and set it to the session... " + userInfoJson);
        session.setAttribute(USER_INFO_FIELD_NAME, userInfoJson);
    }

    return userInfoJson;
}

From source file:org.jets3t.servlets.gatekeeper.GatekeeperServlet.java

/**
 * Handles POST requests that contain Gatekeeper messages encoded as POST form properties, and
 * sends a plain text response document containing the Gatekeeper response message encoded as
 * a properties file./*  ww  w .ja va2 s . co  m*/
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (log.isDebugEnabled()) {
        log.debug("Handling POST request");
    }
    try {
        // Build Gatekeeper request from POST form parameters.
        GatekeeperMessage gatekeeperMessage = GatekeeperMessage.decodeFromProperties(request.getParameterMap());

        // Obtain client information
        ClientInformation clientInformation = new ClientInformation(request.getRemoteAddr(),
                request.getRemoteHost(), request.getRemoteUser(), request.getRemotePort(),
                request.getSession(false), request.getUserPrincipal(), request.getHeader("User-Agent"),
                request);

        // Generate Transaction ID, and store it in the message.
        String transactionId = transactionIdProvider.getTransactionId(gatekeeperMessage, clientInformation);
        if (transactionId != null) {
            gatekeeperMessage.addMessageProperty(GatekeeperMessage.PROPERTY_TRANSACTION_ID, transactionId);
        }

        if (!isInitCompleted) {
            if (log.isWarnEnabled()) {
                log.warn("Cannot process POST request as Gatekeeper servlet did not initialize correctly");
            }
            gatekeeperMessage.addApplicationProperty(GatekeeperMessage.APP_PROPERTY_GATEKEEPER_ERROR_CODE,
                    "GatekeeperInitializationError");
        } else if (gatekeeperMessage.getApplicationProperties()
                .containsKey(GatekeeperMessage.LIST_OBJECTS_IN_BUCKET_FLAG)) {
            // Handle "limited listing" requests.
            if (log.isDebugEnabled()) {
                log.debug("Listing objects");
            }
            boolean allowed = authorizer.allowBucketListingRequest(gatekeeperMessage, clientInformation);
            if (allowed) {
                bucketLister.listObjects(gatekeeperMessage, clientInformation);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Processing " + gatekeeperMessage.getSignatureRequests().length
                        + " object signature requests");
            }
            // Process each signature request.
            for (int i = 0; i < gatekeeperMessage.getSignatureRequests().length; i++) {
                SignatureRequest signatureRequest = gatekeeperMessage.getSignatureRequests()[i];

                // Determine whether the request will be allowed. If the request is not allowed, the
                // reason will be made available in the signature request object (with signatureRequest.declineRequest())
                boolean allowed = authorizer.allowSignatureRequest(gatekeeperMessage, clientInformation,
                        signatureRequest);

                // Sign requests when they are allowed. When a request is signed, the signed URL is made available
                // in the SignatureRequest object.
                if (allowed) {
                    String signedUrl = null;
                    if (SignatureRequest.SIGNATURE_TYPE_GET.equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signGet(gatekeeperMessage, clientInformation, signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_HEAD
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signHead(gatekeeperMessage, clientInformation, signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_PUT
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signPut(gatekeeperMessage, clientInformation, signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_DELETE
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signDelete(gatekeeperMessage, clientInformation,
                                signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_ACL_LOOKUP
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signGetAcl(gatekeeperMessage, clientInformation,
                                signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_ACL_UPDATE
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signPutAcl(gatekeeperMessage, clientInformation,
                                signatureRequest);
                    }
                    signatureRequest.signRequest(signedUrl);
                }
            }
        }

        // Build response as a set of properties, and return this document.
        Properties responseProperties = gatekeeperMessage.encodeToProperties();
        if (log.isDebugEnabled()) {
            log.debug("Sending response message as properties: " + responseProperties);
        }

        // Serialize properties to bytes.
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        responseProperties.store(baos, "");

        // Send successful response.
        response.setStatus(200);
        response.setContentType("text/plain");
        response.getOutputStream().write(baos.toByteArray());
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Gatekeeper failed to send valid response", e);
        }
        response.setStatus(500);
        response.setContentType("text/plain");
        response.getWriter().println(e.toString());
    }
}