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.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) {
    HttpServletRequest initialRequest = (HttpServletRequest) request;
    this.session = session;
    this.authorization = authorization;
    //Copy common data
    authType = initialRequest.getAuthType();
    contextPath = initialRequest.getContextPath();
    remoteUser = initialRequest.getRemoteUser();
    userPrincipal = initialRequest.getUserPrincipal();
    requestedSessionId = initialRequest.getRequestedSessionId();
    requestedSessionIdValid = initialRequest.isRequestedSessionIdValid();

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }//  www.jav a 2  s  .c o  m
    }

    // Warning:  For some reason, the various javax.include.* attributes are
    // not available via the getAttributeNames() call.  This may be limited
    // to a Liferay issue but when the MainPortlet dispatches the call to
    // the MainServlet, all of the javax.include.* attributes can be
    // retrieved using this.request.getAttribute() but they do NOT appear in
    // the Enumeration of names returned by getAttributeNames().  So here
    // we manually add them to our map to ensure we can find them later.
    String[] incAttrKeys = Constants.INC_CONSTANTS;
    for (int index = 0; index < incAttrKeys.length; index++) {
        String incAttrKey = incAttrKeys[index];
        Object incAttrVal = initialRequest.getAttribute(incAttrKey);
        if (incAttrVal != null) {
            attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey));
        }
    }

    headers = new HashMap();
    Enumeration headerNames = initialRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration values = initialRequest.getHeaders(name);
        headers.put(name, Collections.list(values));
    }

    parameters = new HashMap();
    Enumeration parameterNames = initialRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = (String) parameterNames.nextElement();
        parameters.put(name, initialRequest.getParameterValues(name));
    }

    scheme = initialRequest.getScheme();
    serverName = initialRequest.getServerName();
    serverPort = initialRequest.getServerPort();
    secure = initialRequest.isSecure();

    //Copy servlet specific data
    cookies = initialRequest.getCookies();
    method = initialRequest.getMethod();
    pathInfo = initialRequest.getPathInfo();
    pathTranslated = initialRequest.getPathTranslated();
    queryString = initialRequest.getQueryString();
    requestURI = initialRequest.getRequestURI();
    try {
        requestURL = initialRequest.getRequestURL();
    } catch (NullPointerException e) {
        //TODO remove this catch block when GlassFish bug is addressed
        if (log.isErrorEnabled()) {
            log.error("Null Protocol Scheme in request", e);
        }
        HttpServletRequest req = initialRequest;
        requestURL = new StringBuffer(
                "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI());
    }
    servletPath = initialRequest.getServletPath();
    servletSession = initialRequest.getSession();
    isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie();
    isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL();
    characterEncoding = initialRequest.getCharacterEncoding();
    contentLength = initialRequest.getContentLength();
    contentType = initialRequest.getContentType();
    protocol = initialRequest.getProtocol();
    remoteAddr = initialRequest.getRemoteAddr();
    remoteHost = initialRequest.getRemoteHost();
    initializeServlet2point4Properties(initialRequest);
}

From source file:org.apache.hadoop.hbase.http.TestHttpServer.java

@Test
public void testHasAdministratorAccess() throws Exception {
    Configuration conf = new Configuration();
    conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false);
    ServletContext context = Mockito.mock(ServletContext.class);
    Mockito.when(context.getAttribute(HttpServer.CONF_CONTEXT_ATTRIBUTE)).thenReturn(conf);
    Mockito.when(context.getAttribute(HttpServer.ADMINS_ACL)).thenReturn(null);
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    Mockito.when(request.getRemoteUser()).thenReturn(null);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    //authorization OFF
    Assert.assertTrue(HttpServer.hasAdministratorAccess(context, request, response));

    //authorization ON & user NULL
    response = Mockito.mock(HttpServletResponse.class);
    conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, true);
    Assert.assertFalse(HttpServer.hasAdministratorAccess(context, request, response));
    Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED), Mockito.anyString());

    //authorization ON & user NOT NULL & ACLs NULL
    response = Mockito.mock(HttpServletResponse.class);
    Mockito.when(request.getRemoteUser()).thenReturn("foo");
    Assert.assertTrue(HttpServer.hasAdministratorAccess(context, request, response));

    //authorization ON & user NOT NULL & ACLs NOT NULL & user not in ACLs
    response = Mockito.mock(HttpServletResponse.class);
    AccessControlList acls = Mockito.mock(AccessControlList.class);
    Mockito.when(acls.isUserAllowed(Mockito.<UserGroupInformation>any())).thenReturn(false);
    Mockito.when(context.getAttribute(HttpServer.ADMINS_ACL)).thenReturn(acls);
    Assert.assertFalse(HttpServer.hasAdministratorAccess(context, request, response));
    Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED), Mockito.anyString());

    //authorization ON & user NOT NULL & ACLs NOT NULL & user in in ACLs
    response = Mockito.mock(HttpServletResponse.class);
    Mockito.when(acls.isUserAllowed(Mockito.<UserGroupInformation>any())).thenReturn(true);
    Mockito.when(context.getAttribute(HttpServer.ADMINS_ACL)).thenReturn(acls);
    Assert.assertTrue(HttpServer.hasAdministratorAccess(context, request, response));

}

From source file:com.kesdip.license.web.servlet.UpdateServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */// w w w .ja  v  a  2  s .  c om
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    // make sure this is not a browser
    String userAgent = req.getHeader("user-agent");
    if (!userAgent.startsWith("Java")) {
        if (logger.isDebugEnabled()) {
            logger.debug("'" + userAgent + "' forbidden");
        }
        res.sendError(HttpServletResponse.SC_FORBIDDEN, FORBIDDEN_MESSAGE);
        return;
    }
    // get the customer UUID
    String uuid = req.getRemoteUser();
    if (StringUtils.isEmpty(uuid)) {
        logger.debug("Empty customer uuid");
        res.sendError(HttpServletResponse.SC_FORBIDDEN, FORBIDDEN_MESSAGE);
        return;
    }
    // if requesting site.xml or the root (Eclipse does both), check the DB
    String uri = req.getRequestURI();
    String servletPath = req.getServletPath();
    if (uri.endsWith(servletPath) || uri.endsWith(SITE_XML)) {
        if (!supportEnabled(uuid)) {
            logger.warn("Update denied for '" + uuid + "'");
            res.sendError(HttpServletResponse.SC_FORBIDDEN, FORBIDDEN_MESSAGE);
            return;
        }
    }
    // if requesting site.xml, log the request
    if (uri.endsWith(SITE_XML)) {
        logUpdateRequest(uuid, req.getRemoteAddr(), userAgent);
    }
    // all OK, forward to the actual file
    String translatedUri = uri.substring(req.getContextPath().length()).replace(servletPath, actualUpdateRoot);
    if (logger.isTraceEnabled()) {
        logger.trace("Forwarding to '" + translatedUri + "'");
    }
    RequestDispatcher rd = servletContext.getRequestDispatcher(translatedUri);
    rd.forward(req, res);
}

From source file:md.ibanc.rm.spring.service.SingInOutSessionsServiceImpl.java

@Override
@Transactional//from  w ww.  jav  a 2 s.c  om
public SingInOutSessions save(String guidId, Customers customers, HttpServletRequest request) {
    Sessions sessions = new Sessions();

    Calendar cal = Calendar.getInstance();
    Timestamp timestamp = new Timestamp(cal.getTimeInMillis());

    sessions.setCreatedAt(timestamp);
    sessions.setSessionUid(guidId);

    sessionsDAO.save(sessions);

    SingInOutSessions singInOutSessions = new SingInOutSessions();
    singInOutSessions.setCustomers(customers);
    singInOutSessions.setSessions(sessions);
    singInOutSessions.setSingInDate(timestamp);
    singInOutSessions.setIp(request.getRemoteAddr());
    singInOutSessions.setLocation(request.getRemoteUser());

    singInOutSessionsDAO.save(singInOutSessions);
    return singInOutSessions;

}

From source file:de.fhg.fokus.openride.services.profile.ProfileService.java

@GET
@Produces("text/json")
public Response getProfile(@Context HttpServletRequest con, @PathParam("username") String username) {

    System.out.println("getProfile start");

    // check if remote user == {username} in path param
    if (!username.equals(con.getRemoteUser())) {
        //  return Response.status(Response.Status.FORBIDDEN).build();
    }/*from w ww  . ja  v  a2  s  .c  om*/

    CustomerEntity c = customerControllerBean.getCustomerByNickname(username);
    CarDetailsEntity cd = carDetailsControllerBean.getCarDetails(c);

    // build a List of Objects that shall be available in the JSON context.
    ArrayList list = new ArrayList();
    list.add(new ProfileResponse());

    XStream x = Utils.getJasonXStreamer(list);

    Long dateOfBirth = null;
    if (c.getCustDateofbirth() != null) {
        dateOfBirth = c.getCustDateofbirth().getTime();
    }
    Short licenseDate = null;
    if (c.getCustLicensedate() != null) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(c.getCustLicensedate());
        licenseDate = (short) cal.get(Calendar.YEAR);
    }

    ProfileResponse profile = new ProfileResponse(StringEscapeUtils.escapeHtml(c.getCustFirstname()),
            StringEscapeUtils.escapeHtml(c.getCustLastname()), c.getCustGender(), dateOfBirth,
            StringEscapeUtils.escapeHtml(c.getCustEmail()),
            StringEscapeUtils.escapeHtml(c.getCustMobilephoneno()),
            StringEscapeUtils.escapeHtml(c.getCustFixedphoneno()),
            StringEscapeUtils.escapeHtml(c.getCustAddrStreet()), c.getCustAddrZipcode(),
            StringEscapeUtils.escapeHtml(c.getCustAddrCity()), getCustIssmokerChar(c.getCustIssmoker()),
            licenseDate, (cd != null) ? cd.getCardetColour() : null, (cd != null) ? cd.getCardetBrand() : null,
            (cd != null) ? cd.getCardetBuildyear() : null, (cd != null) ? cd.getCardetPlateno() : null);

    return Response.ok(x.toXML(profile)).build();

}

From source file:org.apache.hadoop.http.HttpServer2.java

/**
 * check whether user is static and unauthenticated, if the
 * answer is TRUE, that means http sever is in non-security
 * environment./*from   w ww  .  j a  va  2 s . co  m*/
 * @param servletContext the servlet context.
 * @param request the servlet request.
 * @return TRUE/FALSE based on the logic described above.
 */
public static boolean isStaticUserAndNoneAuthType(ServletContext servletContext, HttpServletRequest request) {
    Configuration conf = (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);
    final String authType = request.getAuthType();
    final String staticUser = conf.get(CommonConfigurationKeys.HADOOP_HTTP_STATIC_USER,
            CommonConfigurationKeys.DEFAULT_HADOOP_HTTP_STATIC_USER);
    return authType == null && staticUser.equals(request.getRemoteUser());
}

From source file:com.redhat.rhn.frontend.servlets.DumpFilter.java

/** {@inheritDoc} */
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {

    if (log.isDebugEnabled()) {
        // handle request
        HttpServletRequest request = (HttpServletRequest) req;
        log.debug("Entered doFilter() ===================================");
        log.debug("AuthType: " + request.getAuthType());
        log.debug("Method: " + request.getMethod());
        log.debug("PathInfo: " + request.getPathInfo());
        log.debug("Translated path: " + request.getPathTranslated());
        log.debug("ContextPath: " + request.getContextPath());
        log.debug("Query String: " + request.getQueryString());
        log.debug("Remote User: " + request.getRemoteUser());
        log.debug("Remote Host: " + request.getRemoteHost());
        log.debug("Remote Addr: " + request.getRemoteAddr());
        log.debug("SessionId: " + request.getRequestedSessionId());
        log.debug("uri: " + request.getRequestURI());
        log.debug("url: " + request.getRequestURL().toString());
        log.debug("Servlet path: " + request.getServletPath());
        log.debug("Server Name: " + request.getServerName());
        log.debug("Server Port: " + request.getServerPort());
        log.debug("RESPONSE encoding: " + resp.getCharacterEncoding());
        log.debug("REQUEST encoding: " + request.getCharacterEncoding());
        log.debug("JVM encoding: " + System.getProperty("file.encoding"));
        logSession(request.getSession());
        logHeaders(request);//from  ww w. j  av  a2  s .  c  o  m
        logCookies(request.getCookies());
        logParameters(request);
        logAttributes(request);
        log.debug("Calling chain.doFilter() -----------------------------");
    }

    chain.doFilter(req, resp);

    if (log.isDebugEnabled()) {
        log.debug("Returned from chain.doFilter() -----------------------");
        log.debug("Handle Response, not much to print");
        log.debug("Response: " + resp.toString());
        log.debug("Leaving doFilter() ===================================");
    }
}

From source file:org.kuali.rice.ken.web.spring.SendNotificationMessageController.java

/**
 * Handles the display of the form for sending a simple notification message
 * @param request : a servlet request//from   ww  w  . j  a v a2 s .co m
 * @param response : a servlet response
 * @throws ServletException : an exception
 * @throws IOException : an exception
 * @return a ModelAndView object
 */
public ModelAndView sendSimpleNotificationMessage(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String view = "SendSimpleNotificationMessage";

    LOG.debug("remoteUser: " + request.getRemoteUser());

    Map<String, Object> model = setupModelForSendSimpleNotification(request);
    model.put("errors", new ErrorList()); // need an empty one so we don't have an NPE

    return new ModelAndView(view, model);
}

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

/**
 * Adds the case./* ww w.  j  a v  a  2s. c  o  m*/
 * 
 * @param alphaCase
 *            the alpha case
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @param response
 *            the response
 * @return the string
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST, params = { "addCase" })
public String addCase(AlphaCase alphaCase, final BindingResult errors, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {

    final User currentUser = this.userManager.getUserByUsername(request.getRemoteUser());
    alphaCase.addParticipant(currentUser);
    alphaCase = this.caseManager.save(alphaCase);

    this.saveMessage(request, this.getText("case.added", request.getLocale()));
    return "redirect:/caseform?caseId=" + alphaCase.getCaseId();

}

From source file:gov.nih.nci.ncicb.cadsr.umlmodelbrowser.struts.actions.BaseDispatchAction.java

/**
 * Sets default method name if no method is specified
 *
 * @return ActionForward// w  w  w.  j av a  2  s  . c  o  m
 *
 * @throws Exception
 */
protected ActionForward dispatchMethod(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, String name) throws Exception {
    if ((name == null) || name.equals("")) {
        name = DEFAULT_METHOD;
    }

    try {
        return super.dispatchMethod(mapping, form, request, response, name);
    } catch (Throwable throwable) {
        HttpSession session = request.getSession();
        String userName = request.getRemoteUser();
        if (userName == null)
            userName = "";
        Collection keys = (Collection) session.getAttribute(this.CLEAR_SESSION_KEYS);
        if (keys != null) {
            Iterator it = keys.iterator();
            while (it.hasNext()) {
                session.removeAttribute((String) it.next());
            }
        }
        if (log.isFatalEnabled()) {
            log.fatal(userName + ": Exception in dispatchMethod in method " + name, throwable);
        }
        saveError(ERROR_FATAL, request);
        throw new FatalException(throwable);
    }
}