Example usage for javax.servlet.http HttpServletRequest getUserPrincipal

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

Introduction

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

Prototype

public java.security.Principal getUserPrincipal();

Source Link

Document

Returns a java.security.Principal object containing the name of the current authenticated user.

Usage

From source file:net.triptech.buildulator.web.BaseController.java

/**
 * Load the person from the request.//www .jav  a 2 s  . c  om
 *
 * @param request the request
 * @return the person
 */
protected final Person getUser(final HttpServletRequest request) {

    Person user = null;

    if (request.getUserPrincipal() != null && StringUtils.isNotBlank(request.getUserPrincipal().getName())) {
        user = Person.findByOpenIdIdentifier(request.getUserPrincipal().getName());
    }
    return user;
}

From source file:org.wte4j.ui.server.filters.SessionContextFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        serviceContext.setLocale(httpRequest.getLocale());

        if (httpRequest.getUserPrincipal() != null) {
            String userName = httpRequest.getUserPrincipal().getName();
            serviceContext.setUser(new User(userName, userName));
        } else {//from ww w.j a v a2  s  .  c  o m
            serviceContext.setUser(new User(ANONYMOUS_USER, ANONYMOUS_USER));
        }

    }

    filterChain.doFilter(request, response);
}

From source file:org.rti.zcore.dar.struts.action.report.CombinedReportListAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed./*w w w  .j a v  a2  s  .  c o m*/
 *
 * @param mapping  The ActionMapping used to select this instance
 * @param form     The optional ActionForm bean for this request (if any)
 * @param request  The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @return Action to forward to
 * @throws Exception if an input/output error or servlet exception occurs
 */
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Principal user = request.getUserPrincipal();
    String username = user.getName();
    HttpSession session = request.getSession();
    SessionUtil zeprs_session = null;
    Site site = null;
    String siteAbbrev = null;
    try {
        zeprs_session = (SessionUtil) session.getAttribute("zeprs_session");
    } catch (Exception e) {
        // unit testing - it's ok...
    }
    try {
        ClientSettings clientSettings = zeprs_session.getClientSettings();
        site = clientSettings.getSite();
        siteAbbrev = site.getAbbreviation();
    } catch (SessionUtil.AttributeNotFoundException e) {
        log.error(e);
    } catch (NullPointerException e) {
        // it's ok - unit testing
        siteAbbrev = "test";
    }
    //String path = Constants.ARCHIVE_PATH + site.getAbbreviation() + Constants.pathSep + "reports" + Constants.pathSep;
    String path = null;
    if (request.getParameter("path") != null) {
        path = request.getParameter("path");
    }
    String message = "Reports are saved at ";
    request.setAttribute("message", message);
    request.setAttribute("path", path);
    return mapping.findForward("success");
}

From source file:be.fedict.hsm.admin.webapp.security.SecurityInterceptor.java

@AroundInvoke
public Object securityVerification(InvocationContext invocationContext) throws Exception {
    Method method = invocationContext.getMethod();
    Class<?> clazz = invocationContext.getMethod().getDeclaringClass();
    LOG.trace("security verification: " + clazz.getSimpleName() + "." + method.getName());
    RolesAllowed rolesAllowedAnnotation = method.getAnnotation(RolesAllowed.class);
    if (null == rolesAllowedAnnotation) {
        rolesAllowedAnnotation = clazz.getAnnotation(RolesAllowed.class);
    }/*from  ww w  . j a va 2s  .com*/
    String[] allowedRoles = rolesAllowedAnnotation.value();

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
    Principal userPrincipal = httpServletRequest.getUserPrincipal();
    if (null == userPrincipal) {
        throw new SecurityException("user not logged in");
    }

    boolean userInRole = false;
    for (String allowedRole : allowedRoles) {
        if (httpServletRequest.isUserInRole(allowedRole)) {
            LOG.trace("user in role: " + allowedRole);
            userInRole = true;
            break;
        }
    }
    if (false == userInRole) {
        throw new SecurityException("user not in allowed roles");
    }

    return invocationContext.proceed();
}

From source file:edu.nwpu.gemfire.monitor.service.ClusterDetailsService.java

public ObjectNode execute(final HttpServletRequest request) throws Exception {

    String userName = request.getUserPrincipal().getName();

    // get cluster object
    Cluster cluster = Repository.get().getCluster();

    // json object to be sent as response
    ObjectNode responseJSON = mapper.createObjectNode();

    Cluster.Alert[] alertsList = cluster.getAlertsList();
    int severeAlertCount = 0;
    int errorAlertCount = 0;
    int warningAlertCount = 0;
    int infoAlertCount = 0;

    for (Cluster.Alert alertObj : alertsList) {
        if (alertObj.getSeverity() == Cluster.Alert.SEVERE) {
            severeAlertCount++;/*from   w w  w  . ja v a2s. c  om*/
        } else if (alertObj.getSeverity() == Cluster.Alert.ERROR) {
            errorAlertCount++;
        } else if (alertObj.getSeverity() == Cluster.Alert.WARNING) {
            warningAlertCount++;
        } else {
            infoAlertCount++;
        }
    }
    // getting basic details of Cluster
    responseJSON.put("clusterName", cluster.getServerName());
    responseJSON.put("severeAlertCount", severeAlertCount);
    responseJSON.put("errorAlertCount", errorAlertCount);
    responseJSON.put("warningAlertCount", warningAlertCount);
    responseJSON.put("infoAlertCount", infoAlertCount);

    responseJSON.put("totalMembers", cluster.getMemberCount());
    responseJSON.put("servers", cluster.getServerCount());
    responseJSON.put("clients", cluster.getClientConnectionCount());
    responseJSON.put("locators", cluster.getLocatorCount());
    responseJSON.put("totalRegions", cluster.getTotalRegionCount());
    Long heapSize = cluster.getTotalHeapSize();

    DecimalFormat df2 = new DecimalFormat(PulseConstants.DECIMAL_FORMAT_PATTERN);
    Double heapS = heapSize.doubleValue() / 1024;
    responseJSON.put("totalHeap", Double.valueOf(df2.format(heapS)));
    responseJSON.put("functions", cluster.getRunningFunctionCount());
    responseJSON.put("uniqueCQs", cluster.getRegisteredCQCount());
    responseJSON.put("subscriptions", cluster.getSubscriptionCount());
    responseJSON.put("txnCommitted", cluster.getTxnCommittedCount());
    responseJSON.put("txnRollback", cluster.getTxnRollbackCount());
    responseJSON.put("userName", userName);

    return responseJSON;
}

From source file:org.springframework.boot.actuate.endpoint.mvc.MvcEndpointSecurityInterceptor.java

private void sendFailureResponse(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (request.getUserPrincipal() != null) {
        String roles = StringUtils.collectionToDelimitedString(this.roles, " ");
        response.sendError(HttpStatus.FORBIDDEN.value(),
                "Access is denied. User must have one of the these roles: " + roles);
    } else {// w ww.  j  a  va2  s.c o  m
        logUnauthorizedAttempt();
        response.sendError(HttpStatus.UNAUTHORIZED.value(),
                "Full authentication is required to access this resource.");
    }
}

From source file:com.example.securelogin.app.common.interceptor.PasswordExpirationCheckInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws IOException {
    Authentication authentication = (Authentication) request.getUserPrincipal();

    if (authentication != null) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            LoggedInUser userDetails = (LoggedInUser) principal;
            if ((userDetails.getAccount().getRoles().contains(Role.ADMIN)
                    && accountSharedService.isCurrentPasswordExpired(userDetails.getUsername()))
                    || accountSharedService.isInitialPassword(userDetails.getUsername())) {
                response.sendRedirect(request.getContextPath() + "/password?form");
                return false;
            }//from  w  w w .j ava 2s.  com
        }
    }

    return true;
}

From source file:com.ocs.dynamo.service.impl.DefaultUserDetailsServiceImpl.java

@Override
public String getCurrentUserName() {
    try {/*from w w w.j a  va 2  s  .  co  m*/
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .currentRequestAttributes()).getRequest();
        return request.getUserPrincipal().getName();
    } catch (Exception ex) {
        // ignore - no request available during integration test
        return SYSTEM;
    }
}

From source file:org.smigo.config.ErrorViewExceptionResolver.java

@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {//from   w w w .j  a  va 2  s . com
    log.info("Invalidating session and removing persistent token:" + request.getUserPrincipal());
    try {
        request.logout();
    } catch (ServletException e) {
        log.error("Could not logout user " + request.getUserPrincipal(), e);
    }
    return new ModelAndView("error.jsp", "statusCode", response.getStatus());
}

From source file:com.pivotal.gemfire.tools.pulse.internal.service.ClusterDetailsService.java

public JSONObject execute(final HttpServletRequest request) throws Exception {

    String userName = request.getUserPrincipal().getName();

    // get cluster object
    Cluster cluster = Repository.get().getCluster();

    // json object to be sent as response
    JSONObject responseJSON = new JSONObject();

    Cluster.Alert[] alertsList = cluster.getAlertsList();
    int severeAlertCount = 0;
    int errorAlertCount = 0;
    int warningAlertCount = 0;
    int infoAlertCount = 0;

    for (Cluster.Alert alertObj : alertsList) {
        if (alertObj.getSeverity() == Cluster.Alert.SEVERE) {
            severeAlertCount++;//  w  w  w  . j  a  va2 s  .co  m
        } else if (alertObj.getSeverity() == Cluster.Alert.ERROR) {
            errorAlertCount++;
        } else if (alertObj.getSeverity() == Cluster.Alert.WARNING) {
            warningAlertCount++;
        } else {
            infoAlertCount++;
        }
    }
    try {
        // getting basic details of Cluster
        responseJSON.put("clusterName", cluster.getServerName());
        responseJSON.put("severeAlertCount", severeAlertCount);
        responseJSON.put("errorAlertCount", errorAlertCount);
        responseJSON.put("warningAlertCount", warningAlertCount);
        responseJSON.put("infoAlertCount", infoAlertCount);

        responseJSON.put("totalMembers", cluster.getMemberCount());
        responseJSON.put("servers", cluster.getServerCount());
        responseJSON.put("clients", cluster.getClientConnectionCount());
        responseJSON.put("locators", cluster.getLocatorCount());
        responseJSON.put("totalRegions", cluster.getTotalRegionCount());
        Long heapSize = cluster.getTotalHeapSize();

        DecimalFormat df2 = new DecimalFormat(PulseConstants.DECIMAL_FORMAT_PATTERN);
        Double heapS = heapSize.doubleValue() / 1024;
        responseJSON.put("totalHeap", Double.valueOf(df2.format(heapS)));
        responseJSON.put("functions", cluster.getRunningFunctionCount());
        responseJSON.put("uniqueCQs", cluster.getRegisteredCQCount());
        responseJSON.put("subscriptions", cluster.getSubscriptionCount());
        responseJSON.put("txnCommitted", cluster.getTxnCommittedCount());
        responseJSON.put("txnRollback", cluster.getTxnRollbackCount());
        responseJSON.put("userName", userName);
        responseJSON.put("connectedFlag", cluster.isConnectedFlag());
        responseJSON.put("connectedErrorMsg", cluster.getConnectionErrorMsg());

        return responseJSON;
    } catch (JSONException e) {
        throw new Exception(e);
    }
}