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:nl.b3p.viewer.util.IPAuthenticationFilter.java

/**
 *
 * @param r The servlet request we are processing
 * @param response The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 *///from  ww  w .j a  v  a2 s  . c om
@Override
public void doFilter(ServletRequest r, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) r;
    HttpSession session = request.getSession();
    if (request.getUserPrincipal() != null) {
        chain.doFilter(request, response);
    } else {
        User u = null;
        if ((session.getAttribute(IP_CHECK) == null && session.getAttribute(USER_CHECK) == null)
                || isCacheValid(session)) {

            String ipAddress = getIp(request);
            session.setAttribute(IP_CHECK, ipAddress);
            Stripersist.requestInit();

            EntityManager em = Stripersist.getEntityManager();
            List<User> users = em.createQuery("from User", User.class).getResultList();
            List<User> possibleUsers = new ArrayList<User>();

            for (User user : users) {
                if (checkValidIpAddress(request, user)) {
                    possibleUsers.add(user);
                }
            }

            if (possibleUsers.isEmpty()) {
                log.debug("No eligible users found for ip");
            } else if (possibleUsers.size() == 1) {
                u = possibleUsers.get(0);
                u.setAuthenticatedByIp(true);
                Hibernate.initialize(u.getGroups());
                session.setAttribute(IP_CHECK, ipAddress);
                session.setAttribute(USER_CHECK, u);
                session.setAttribute(TIME_USER_CHECKED, System.currentTimeMillis());
            } else {
                log.debug("Too many eligible users found for ip.");
            }
            Stripersist.requestComplete();
        } else {
            u = (User) session.getAttribute(USER_CHECK);
        }
        final User user = u;

        RequestWrapper wrappedRequest = new RequestWrapper((HttpServletRequest) request) {
            @Override
            public Principal getUserPrincipal() {
                if (user != null) {
                    return user;
                } else {
                    return super.getUserPrincipal();
                }
            }

            @Override
            public String getRemoteUser() {
                if (user != null) {
                    return user.getName();
                } else {
                    return super.getRemoteUser();
                }
            }

            @Override
            public boolean isUserInRole(String role) {
                if (user != null) {
                    return user.checkRole(role);
                } else {
                    return super.isUserInRole(role);
                }
            }
        };

        Throwable problem = null;

        try {
            chain.doFilter(wrappedRequest, response);
        } catch (IOException | ServletException t) {
            log.error("Error processing chain", problem);
            throw t;
        }
    }
}

From source file:uk.ac.ebi.metabolights.controller.SubmissionQueueController.java

@RequestMapping(value = { "/referencespectraupload" })
public ModelAndView referenceSpectraUpload(HttpServletRequest request) {
    MetabolightsUser user = null;//from  w  w  w  .j a  va  2  s. c  om
    ModelAndView mav = AppContext.getMAVFactory().getFrontierMav("referencespectraupload"); // Call the Submission form page

    if (request.getUserPrincipal() != null)
        user = (MetabolightsUser) (SecurityContextHolder.getContext().getAuthentication().getPrincipal());

    if (user != null) {
        //mav.addObject("user", user);
        try {
            mav.addObject("queueditems", SubmissionQueue.getQueuedForUserId(user.getUserName().toString()));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // If the user is a curator
        if (user.isCurator()) {
            mav.addObject("users", userService.getAll());
        }
    }

    return mav;
}

From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(403, "User is not logged in");
        return;/*from   ww w.j a v  a2s .c  o  m*/
    }
    if (!servletRequest.isUserInRole("HOPS_ADMIN")) {
        servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "You don't have the access right for this service");
        return;
    }
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    // note: we won't transfer the protocol version because I'm not 
    // sure it would truly be compatible
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);

    try {
        // Execute the request

        HttpClientParams params = new HttpClientParams();
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpClient client = new HttpClient(params);
        HostConfiguration config = new HostConfiguration();
        InetAddress localAddress = InetAddress.getLocalHost();
        config.setLocalAddress(localAddress);

        String method = servletRequest.getMethod();
        HttpMethod m;
        if (method.equalsIgnoreCase("PUT")) {
            m = new PutMethod(proxyRequestUri);
            RequestEntity requestEntity = new InputStreamRequestEntity(servletRequest.getInputStream(),
                    servletRequest.getContentType());
            ((PutMethod) m).setRequestEntity(requestEntity);
        } else {
            m = new GetMethod(proxyRequestUri);
        }
        Enumeration<String> names = servletRequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String headerName = names.nextElement();
            String value = servletRequest.getHeader(headerName);
            if (PASS_THROUGH_HEADERS.contains(headerName)) {
                //yarn does not send back the js if encoding is not accepted
                //but we don't want to accept encoding for the html because we
                //need to be able to parse it
                if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null
                        || !servletRequest.getPathInfo().contains(".js"))) {
                    continue;
                } else {
                    m.setRequestHeader(headerName, value);
                }
            }
        }
        String user = servletRequest.getRemoteUser();
        if (user != null && !user.isEmpty()) {
            m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII"));
        }

        client.executeMethod(config, m);

        // Process the response
        int statusCode = m.getStatusCode();

        // Pass the response code. This method with the "reason phrase" is 
        //deprecated but it's the only way to pass the reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase());

        copyResponseHeaders(m, servletRequest, servletResponse);

        // Send the content to the client
        copyResponseEntity(m, servletResponse);

    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);

    }
}

From source file:org.opendaylight.controller.web.DaylightWeb.java

@RequestMapping(value = "login")
public String login(Model model, final HttpServletRequest request, final HttpServletResponse response) {
    // response.setHeader("X-Page-Location", "/login");
    IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this);
    if (userManager == null) {
        return "User Manager is not available";
    }/*from   ww  w  . j  a va  2  s  .c om*/

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

    model.addAttribute("username", username);
    model.addAttribute("role", userManager.getUserLevel(username).toNumber());
    return "forward:" + "/";
}

From source file:nl.b3p.kaartenbalie.struts.WMSUrlCreatorAction.java

public void createLists(DynaValidatorForm form, HttpServletRequest request) throws JSONException, Exception {
    super.createLists(form, request);

    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    User sesuser = (User) request.getUserPrincipal();
    if (sesuser == null) {
        return;//  w ww .  j a  v  a  2  s.co  m
    }
    User user = (User) em.find(User.class, sesuser.getId());
    if (user == null) {
        return;
    }
    form.set("personalUrl", user.getPersonalURL(request));
    String bbox = (String) form.get("bbox");
    if (bbox == null || bbox.length() == 0) {
        form.set("bbox", "12000,304000,280000,620000"); // heel nederland
    }
    String[] formats = new String[5];
    formats[0] = "image/gif";
    formats[1] = "image/png";
    formats[2] = "image/jpeg";
    formats[3] = "image/bmp";
    formats[4] = "image/tiff";
    request.setAttribute("formatList", formats);

    Set userLayers = user.getLayers();
    JSONObject root = createTree("Kaartlagen", userLayers);
    request.setAttribute("layerList", root);

    LayerValidator lv = new LayerValidator(userLayers);
    String[] alSrsen = lv.validateSRS();
    request.setAttribute("projectieList", alSrsen);

}

From source file:org.soulwing.cas.filter.AbstractValidationFilter.java

private void passToFilterChain(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws IOException, ServletException {
    if (log.isDebugEnabled()) {
        log.debug("User " + request.getUserPrincipal().getName() + " is authentic");
    }//from www.  jav a2  s .  co  m
    filterChain.doFilter(request, response);
}

From source file:org.smigo.log.LogHandler.java

public String getRequestDump(HttpServletRequest request, HttpServletResponse response, String separator) {
    StringBuilder s = new StringBuilder("####REQUEST ").append(request.getMethod()).append(" ")
            .append(request.getRequestURL()).append(separator);
    s.append("Auth type:").append(request.getAuthType()).append(separator);
    s.append("Principal:").append(request.getUserPrincipal()).append(separator);
    s.append(Log.create(request, response).toString()).append(separator);
    s.append("Headers:").append(separator);
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        s.append(headerName).append("=").append(request.getHeader(headerName)).append(separator);
    }// w  w w.j  a  va  2s  .  c o  m
    s.append(separator);
    s.append("####RESPONSE").append(separator);
    s.append("Status:").append(response.getStatus()).append(separator);
    s.append("Char encoding:").append(response.getCharacterEncoding()).append(separator);
    s.append("Locale:").append(response.getLocale()).append(separator);
    s.append("Content type:").append(response.getContentType()).append(separator);

    s.append("Headers:").append(separator);
    s.append(response.getHeaderNames().stream().map(rh -> rh + "=" + response.getHeader(rh))
            .collect(Collectors.joining(separator)));

    final Long start = (Long) request.getAttribute(RequestLogFilter.REQUEST_TIMER);
    if (start != null) {
        final long elapsedTime = System.nanoTime() - start;
        s.append(separator).append("####Request time elapsed:").append(elapsedTime);
        s.append("ns which is ").append(elapsedTime / 1000000).append("ms").append(separator);
    }
    return s.toString();
}

From source file:edu.nwpu.gemfire.monitor.controllers.PulseController.java

/**
 * Method isUserLoggedIn Check whether user is logged in or not.
 * //from w ww .  java  2s  .co  m
 * @param request
 * @return boolean
 */
protected boolean isUserLoggedIn(HttpServletRequest request) {
    return null != request.getUserPrincipal();
}

From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java

/**
 * Handles a POST request.//from   ww  w. j  a v  a2s .co m
 * 
 * @param request
 *          the servlet request
 * @param response
 *          the servlet response
 * @throws ServletException
 * @throws IOException
 *           if an exception occurs
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (!_redirectURL.startsWith("http"))
        setURL(request);

    Principal p = request.getUserPrincipal();
    if (p != null) {
        LOGGER.finer("UserName : " + p.getName());
    }

    executeProxy(request, response);
}

From source file:org.cerberus.servlet.crud.usermanagement.UpdateMyUserReporting1.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    JSONObject jsonResponse = new JSONObject();

    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);

    String login = request.getUserPrincipal().getName();
    String charset = request.getCharacterEncoding();
    /**//from ww w  . j  a v a2 s  . c  om
     * Parse parameters - list of values
     */
    List<String> tcstatusList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcstatus"), null, charset);
    List<String> groupList = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues("group"),
            null, charset);
    List<String> tcactiveList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcactive"), null, charset);
    List<String> priorityList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("priority"), null, charset);

    List<String> countryList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("country"), null, charset);
    List<String> browserList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("browser"), null, charset);
    List<String> tcestatusList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcestatus"), null, charset);

    //environment
    List<String> environmentList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("environment"), null, charset);
    List<String> projectList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("project"), null, charset);
    /**
     * Parse parameters - free text
     */
    String ip = StringEscapeUtils.escapeHtml4(request.getParameter("ip"));
    String port = StringEscapeUtils.escapeHtml4(request.getParameter("port"));
    String tag = StringEscapeUtils.escapeHtml4(request.getParameter("tag"));
    String browserversion = StringEscapeUtils.escapeHtml4(request.getParameter("browserversion"));
    String comment = StringEscapeUtils.escapeHtml4(request.getParameter("comment"));

    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());
    IUserService userService = appContext.getBean(UserService.class);

    try {
        User user = userService.findUserByKey(login);
        if (user != null) {
            JSONObject preferences = new JSONObject();

            if (tcstatusList != null) {
                preferences.put("s", tcstatusList);
            }
            if (groupList != null) {
                preferences.put("g", groupList);
            }
            if (tcactiveList != null) {
                preferences.put("a", tcactiveList);
            }
            if (priorityList != null) {
                preferences.put("pr", priorityList);
            }
            if (countryList != null) {
                preferences.put("co", countryList);
            }
            if (browserList != null) {
                preferences.put("b", browserList);
            }
            if (tcestatusList != null) {
                preferences.put("es", tcestatusList);
            }
            if (environmentList != null) {
                preferences.put("e", environmentList);
            }
            if (projectList != null) {
                preferences.put("prj", projectList);
            }

            if (!StringUtil.isNullOrEmpty(ip)) {
                preferences.put("ip", ip);
            }
            if (!StringUtil.isNullOrEmpty(port)) {
                preferences.put("p", port);
            }
            if (!StringUtil.isNullOrEmpty(tag)) {
                preferences.put("t", tag);
            }
            if (!StringUtil.isNullOrEmpty(browserversion)) {
                preferences.put("br", browserversion);
            }
            if (!StringUtil.isNullOrEmpty(comment)) {
                preferences.put("cm", comment);
            }

            user.setReportingFavorite(preferences.toString());
            userService.updateUser(user); //TODO: when converting to the new standard this should return an answer
            //re-send the updated preferences 

            jsonResponse.put("preferences", preferences);

            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Execution reporting filters ")
                    .replace("%OPERATION%", "Update"));

            ILogEventService logEventService = appContext.getBean(LogEventService.class);
            logEventService.createPrivateCalls("/UpdateMyUserReporting1", "UPDATE",
                    "Update user reporting preference for user: " + login, request);
        } else {
            msg.setDescription(
                    msg.getDescription().replace("%DESCRIPTION%", "Unable to update User was not found!"));
        }

        jsonResponse.put("messageType", msg.getMessage().getCodeString());
        jsonResponse.put("message", msg.getDescription());
    } catch (JSONException ex) {
        Logger.getLogger(UpdateMyUserReporting1.class.getName()).log(Level.SEVERE, null, ex);
        //returns a default error message with the json format that is able to be parsed by the client-side
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    } catch (CerberusException ex) {
        Logger.getLogger(UpdateMyUserReporting1.class.getName()).log(Level.SEVERE, null, ex);
        //returns a default error message with the json format that is able to be parsed by the client-side
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    }

    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}