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:org.apache.struts.faces.systest1.ContextAction.java

/**
 * <p>Process an attempted logon.</p>
 *//*w  ww.j  a va  2  s.c  o  m*/
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    this.authType = request.getAuthType();
    this.contextPath = request.getContextPath();
    this.locale = request.getLocale();
    this.pathInfo = request.getPathInfo();
    this.remoteUser = request.getRemoteUser();
    this.servletPath = request.getServletPath();

    request.setAttribute("contextAction", this);
    return (mapping.findForward("context1"));

}

From source file:org.apache.hadoop.chukwa.rest.resource.ViewResource.java

@POST
@Path("permission")
public ReturnCodeBean changeViewPermission(@Context HttpServletRequest request,
        @FormParam("owner") String owner, @FormParam("view_vid") String vid,
        @FormParam("permission") String permission) {
    try {//from  www . ja  v a2  s  .c o m
        if (owner.intern() == request.getRemoteUser().intern()) {
            ViewStore vs = new ViewStore(owner, vid);
            ViewBean view = vs.get();
            view.setPermissionType(permission);
            vs.set(view);
        } else {
            throw new Exception("Permission denied.");
        }
    } catch (Exception e) {
        log.error(ExceptionUtil.getStackTrace(e));
        throw new WebApplicationException(
                Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("View save failed.").build());
    }
    return new ReturnCodeBean(ReturnCodeBean.SUCCESS, "Saved");
}

From source file:oculus.memex.rest.AttributeDetailsResource.java

/**
 * //from ww w  . j  a  v a2 s  .  c o m
 * @param attributesIds
 * @param request
 * @return Map of attributeid --> ClusterDetailsResource
 */
@POST
@Path("fetchAds")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes({ MediaType.TEXT_HTML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public ClustersDetailsResult fetchAds(String attributesIds, @Context HttpServletRequest request) {
    TimeLog log = new TimeLog();
    log.pushTime("Fetching attribute graph ad details for user " + request.getRemoteUser());
    HashMap<Integer, ClusterDetailsResult> results = new HashMap<Integer, ClusterDetailsResult>();
    MemexOculusDB oculusdb = MemexOculusDB.getInstance();
    MemexHTDB htdb = MemexHTDB.getInstance();
    Connection oculusconn;
    Connection htconn;

    try {
        JSONObject jo = new JSONObject(attributesIds);
        JSONArray attributeClusterIds = jo.getJSONArray("ids");
        oculusconn = oculusdb.open();
        HashMap<Integer, AttributeValue> allAttributes = AttributeLinks.getAttributes(oculusconn);
        oculusdb.close();
        for (int i = 0; i < attributeClusterIds.length(); i++) {
            Integer attrid = Integer.parseInt(attributeClusterIds.get(i).toString());

            // Get the ad->attribute list mapping
            log.pushTime("Fetch Ad IDs for cluster " + attrid);
            HashMap<Integer, HashSet<Integer>> adToAttributes = new HashMap<Integer, HashSet<Integer>>();
            ArrayList<Integer> ads = new ArrayList<Integer>();
            htconn = htdb.open();
            oculusconn = oculusdb.open();
            AttributeDetails.getAdsInAttributes(attrid, attrid, allAttributes, adToAttributes, oculusconn,
                    htconn, ads);
            htdb.close();
            oculusdb.close();
            HashSet<Integer> members = new HashSet<Integer>(adToAttributes.keySet());
            log.popTime();

            log.pushTime("Fetch ad contents for cluster " + attrid);
            List<DataRow> result = new ArrayList<DataRow>();
            PreclusterDetailsResource.getDetails(members, result, request.getRemoteUser());
            log.popTime();

            log.pushTime("Prepare results for attribute cluster: " + attrid);
            ArrayList<HashMap<String, String>> details = DataUtil.sanitizeHtml(result);
            ArrayList<StringMap> serializableDetails = new ArrayList<StringMap>();
            for (HashMap<String, String> map : details) {
                serializableDetails.add(new StringMap(map));
            }
            results.put(attrid, new ClusterDetailsResult(serializableDetails));
            log.popTime();
        }
        log.popTime();
        return new ClustersDetailsResult(results);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.apereo.portal.web.ExceptionLoggingFilter.java

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

    try {/*from   w w w.java 2 s. co m*/
        chain.doFilter(request, response);
    } catch (Throwable t) {
        StringBuilder msg = new StringBuilder();
        if (request instanceof HttpServletRequest) {
            HttpServletRequest req = (HttpServletRequest) request;
            msg.append("for URL=" + req.getRequestURI());
            if (StringUtils.isNotBlank(req.getQueryString())) {
                msg.append("?" + req.getQueryString());
            }
            msg.append(", user=" + req.getRemoteUser());
            msg.append(" ");
        }
        msg.append(", from IP=" + request.getRemoteAddr());
        this.logger.error("uPortal: unhandled exception '" + t.getMessage() + "' " + msg.toString(), t);

        if (t instanceof Error) {
            throw (Error) t;
        }
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        }
        if (t instanceof ServletException) {
            throw (ServletException) t;
        }
        if (t instanceof IOException) {
            throw (IOException) t;
        }
        throw new ServletException(t);
    }
}

From source file:io.hops.hopsworks.api.user.AuthService.java

private void logoutAndInvalidateSession(HttpServletRequest req) throws UserException {
    Users user = userFacade.findByEmail(req.getRemoteUser());
    try {//  w  ww  . jav  a2  s  .  co  m
        req.getSession().invalidate();
        req.logout();
        if (user != null) {
            authController.registerLogout(user, req);
            //remove zeppelin ticket for user
            TicketContainer.instance.invalidate(user.getEmail());
        }
    } catch (ServletException e) {
        accountAuditFacade.registerLoginInfo(user, UserAuditActions.LOGOUT.name(),
                UserAuditActions.FAILED.name(), req);
        throw new UserException(RESTCodes.UserErrorCode.LOGOUT_FAILURE, Level.SEVERE, null, e.getMessage(), e);
    }
}

From source file:com.novartis.pcs.ontology.rest.servlet.OntologiesServlet.java

private String getUsername(HttpServletRequest request) {
    String username = request.getRemoteUser();

    if (username == null) {
        Principal principal = request.getUserPrincipal();
        if (principal != null) {
            username = principal.getName();
        }/*from   w ww  .j a va2  s . co  m*/
    }

    return username;
}

From source file:org.opennms.web.controller.alarm.AlarmFilterController.java

public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws Exception {
    List<OnmsFilterFavorite> userFilterList = favoriteService.getFavorites(request.getRemoteUser(),
            OnmsFilterFavorite.Page.ALARM);
    ModelAndView modelAndView = new ModelAndView("alarm/index");
    modelAndView.addObject("favorites", userFilterList.toArray());
    modelAndView.addObject("callback", getFilterCallback());
    return modelAndView;
}

From source file:net.unicon.cas.chalkwire.servlet.CasChalkWireHttpServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {/*  w ww  .  j  a v a 2  s .c om*/
        if (req.getRemoteUser() == null)
            throw new ServletException("User is not authenticated. Check the CAS client log files for details");

        String userId = req.getUserPrincipal().getName();

        if (logger.isDebugEnabled())
            logger.debug("Received login request from user " + userId);

        final String URL = buildSingleSignOnTokenRequestUrl(userId);

        if (logger.isDebugEnabled()) {
            logger.debug("Requesing security token from ePortfolio Connect Server");
            logger.debug("Requesting url:" + URL);
        }

        /*
         * Send the single sign-on request url to server and parse the response.
         */
        ChalkWireResponseParser parser = new ChalkWireResponseParser(URL);

        if (logger.isDebugEnabled())
            logger.debug("Response is success:" + parser.isSuccess());

        if (parser.isSuccess()) {

            if (logger.isDebugEnabled())
                logger.debug("url: " + parser.getURL());

            if (logger.isDebugEnabled())
                logger.debug("token: " + parser.getToken());

            String finalURL = buildFinalSingleSignOnUrl(userId, parser);

            if (logger.isDebugEnabled())
                logger.debug("Single sign-on URL:" + finalURL);

            parser = new ChalkWireResponseParser(finalURL);

            if (!parser.isSuccess())
                throw new ServletException(parser.getMessage());

            resp.sendRedirect(finalURL);

        } else
            throw new ServletException(parser.getMessage());

    } catch (ServletException e) {
        logger.error(e.getMessage(), e);

        String casServerLoginUrl = getServletContext().getInitParameter("casServerLoginUrl");

        String service = req.getRequestURL().toString();
        casServerLoginUrl += "login?renew=true&service=" + URLEncoder.encode(service, ENCODING_TYPE);

        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher("/WEB-INF/view/jsp/chalkWireError.jsp");
        req.setAttribute("exception", e);

        if (logger.isDebugEnabled())
            logger.debug("Constructed CAS login url:" + casServerLoginUrl);

        req.setAttribute("loginUrl", casServerLoginUrl);
        dispatcher.forward(req, resp);

    }

}

From source file:org.opennms.web.controller.alarm.AlarmFilterController.java

public ModelAndView list(HttpServletRequest request, HttpServletResponse response) throws Exception {
    OnmsFilterFavorite favorite = getFavorite(request.getParameter("favoriteId"), request.getRemoteUser(),
            request.getParameterValues("filter"));
    return list(request, favorite);
}

From source file:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java

private boolean checkForAuthorization(HttpServletRequest request) {
    M_log.debug("checkLdapForAuthorization(): called");
    String remoteUser = request.getRemoteUser();
    String testUser = request.getParameter(TEST_USER);
    boolean isAuthorized = false;
    String user = null;//from www .  j  av  a  2s.c  om
    String testUserInSession = (String) request.getSession().getAttribute(TEST_USER);
    String sessionId = request.getSession().getId();

    if (isTestUrlEnabled && testUser != null) {
        user = testUser;
        request.getSession().setAttribute(TEST_USER, testUser);
    } else if (isTestUrlEnabled && testUserInSession != null) {
        user = testUserInSession;
    }
    M_log.debug("remote user: " + remoteUser);
    M_log.debug("test user: " + testUser);
    M_log.debug("session test user: " + testUserInSession);
    M_log.debug("User: " + user);
    if (!isAuthorized && remoteUser != null) {
        user = remoteUser;
        M_log.info(String.format(
                "The session id \"%s\" of Service Desk Person with uniqname  \"%s\" issuing the request",
                sessionId, remoteUser));
    }
    isAuthorized = ldapAuthorizationVerification(user);
    return isAuthorized;

}