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.jahia.bin.errors.ErrorLoggingFilter.java

/**
 * Returns the request information for logging purposes.
 *
 * @param request the http request object
 * @return the request information for logging purposes
 *//*from ww  w  . ja  v a 2 s . c  o  m*/
private static String getRequestInfo(HttpServletRequest request) {
    StringBuilder info = new StringBuilder(512);
    if (request != null) {
        String uri = (String) request.getAttribute("javax.servlet.error.request_uri");
        String queryString = (String) request.getAttribute("javax.servlet.forward.query_string");
        if (StringUtils.isNotEmpty(queryString)) {
            uri = uri + "?" + queryString;
        }
        info.append("Request information:").append("\nURL: ").append(uri).append("\nMethod: ")
                .append(request.getMethod()).append("\nProtocol: ").append(request.getProtocol())
                .append("\nRemote host: ").append(request.getRemoteHost()).append("\nRemote address: ")
                .append(request.getRemoteAddr()).append("\nRemote port: ").append(request.getRemotePort())
                .append("\nRemote user: ").append(request.getRemoteUser()).append("\nSession ID: ")
                .append(request.getRequestedSessionId()).append("\nSession user: ").append(getUserInfo(request))
                .append("\nRequest headers: ");

        @SuppressWarnings("unchecked")
        Iterator<String> headerNames = new EnumerationIterator(request.getHeaderNames());
        while (headerNames.hasNext()) {
            String headerName = headerNames.next();
            String headerValue = request.getHeader(headerName);
            info.append("\n  ").append(headerName).append(": ").append(headerValue);
        }
    }
    return info.toString();
}

From source file:com.googlecode.psiprobe.controllers.logs.DownloadLogController.java

protected ModelAndView handleLogFile(HttpServletRequest request, HttpServletResponse response,
        LogDestination logDest) throws Exception {
    File file = logDest.getFile();
    logger.info("Sending " + file + " to " + request.getRemoteAddr() + "(" + request.getRemoteUser() + ")");
    Utils.sendFile(request, response, file);
    return null;// w  ww.j  av a2 s .com
}

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

@PUT
@Consumes("application/json")
public ReturnCodeBean setView(@Context HttpServletRequest request, ViewBean view) {
    try {//ww w  .ja  va2  s.  c  om
        if (request.getRemoteUser().intern() == view.getOwner().intern()) {
            ViewStore vs = new ViewStore(view.getOwner(), view.getName());
            vs.set(view);
        } else {
            throw new WebApplicationException(
                    Response.status(Response.Status.FORBIDDEN).entity("Permission denied.").build());
        }
    } catch (IllegalAccessException e) {
        log.error(ExceptionUtil.getStackTrace(e));
        throw new WebApplicationException(
                Response.status(Response.Status.NOT_FOUND).entity("View save failed.").build());
    }
    return new ReturnCodeBean(ReturnCodeBean.SUCCESS, "Saved");
}

From source file:edu.ucmerced.cas.adaptors.casshib.web.flow.PrincipalFromHttpHeadersNonInteractiveCredentialsAction.java

protected Credentials constructCredentialsFromRequest(final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final String remoteUser = request.getRemoteUser();

    if (StringUtils.hasText(remoteUser)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Remote  User [" + remoteUser + "] found in HttpServletRequest");
        }//  w  w  w.ja v  a 2 s.  c  om

        /**
         * Grab the Shibboleth attributes from the HTTP headers, create a
         * map of them, and include the, in the SimplePrincipal.
         */
        HashMap<String, Object> attributes = new HashMap<String, Object>();

        Enumeration en = request.getHeaderNames();
        while (en.hasMoreElements()) {
            String name = (String) en.nextElement();
            if (name.startsWith("shibattr-") || name.startsWith("Shib-")) {
                ArrayList<String> valueList = new ArrayList<String>();
                Enumeration en2 = request.getHeaders(name);
                while (en2.hasMoreElements()) {
                    String value = (String) en2.nextElement();
                    if (value.length() > 0) {
                        valueList.add(value);
                    }
                }
                if (valueList.size() > 0) {
                    if (name.startsWith("shibattr-"))
                        attributes.put(name.substring("shibattr-".length()),
                                (valueList.size() == 1 ? valueList.get(0) : valueList));
                    else
                        attributes.put(name, (valueList.size() == 1 ? valueList.get(0) : valueList));
                }
            }
        }

        return new PrincipalBearingCredentials(new SimplePrincipal(remoteUser, attributes));
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Remote User not found in HttpServletRequest.");
    }

    return null;
}

From source file:pdfjsannotator.controller.AnnotationController.java

@RequestMapping(value = "/api", method = RequestMethod.GET)
public StoreMeta root(HttpServletRequest request) {
    LOGGER.info("Requested annotator store API information.");
    return new StoreMeta("Annotator Store API", "2.0.0", request.getRemoteUser());
}

From source file:se.vgregion.portal.requestlogger.RequestLoggerController.java

private Map<String, String> getRequestInfo(PortletRequest request) {
    Map<String, String> requestResult = new TreeMap<String, String>();

    HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(request);

    requestResult.put("RemoteUser", httpRequest.getRemoteUser());
    requestResult.put("P3P.USER_LOGIN_ID", getRemoteUserId(request));
    requestResult.put("RemoteAddr", httpRequest.getRemoteAddr());
    requestResult.put("RemoteHost", httpRequest.getRemoteHost());
    requestResult.put("RemotePort", String.valueOf(httpRequest.getRemotePort()));
    requestResult.put("AuthType", httpRequest.getAuthType());
    requestResult.put("CharacterEncoding", httpRequest.getCharacterEncoding());
    requestResult.put("ContentLength", String.valueOf(httpRequest.getContentLength()));
    requestResult.put("ContentType", httpRequest.getContentType());
    requestResult.put("ContextPath", httpRequest.getContextPath());
    requestResult.put("LocalAddr", httpRequest.getLocalAddr());
    requestResult.put("Locale", httpRequest.getLocale().toString());
    requestResult.put("LocalName", httpRequest.getLocalName());
    requestResult.put("LocalPort", String.valueOf(httpRequest.getLocalPort()));
    requestResult.put("Method", httpRequest.getMethod());
    requestResult.put("PathInfo", httpRequest.getPathInfo());
    requestResult.put("PathTranslated", httpRequest.getPathTranslated());
    requestResult.put("Protocol", httpRequest.getProtocol());
    requestResult.put("QueryString", httpRequest.getQueryString());
    requestResult.put("RequestedSessionId", httpRequest.getRequestedSessionId());
    requestResult.put("RequestURI", httpRequest.getRequestURI());
    requestResult.put("Scheme", httpRequest.getScheme());
    requestResult.put("ServerName", httpRequest.getServerName());
    requestResult.put("ServerPort", String.valueOf(httpRequest.getServerPort()));
    requestResult.put("ServletPath", httpRequest.getServletPath());

    return requestResult;
}

From source file:com.pkrete.locationservice.admin.controller.mvc.LanguageController.java

protected void updateUser(HttpServletRequest request) {
    HttpSession session = request.getSession();
    session.removeAttribute("user");
    session.setAttribute("user", usersService.getUser(request.getRemoteUser()));
}

From source file:com.liferay.portal.spring.servlet.RemotingServlet.java

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    try {/*from   www.  j a v  a2  s  . c  o m*/
        PortalInstances.getCompanyId(request);

        String remoteUser = request.getRemoteUser();

        if (_log.isDebugEnabled()) {
            _log.debug("Remote user " + remoteUser);
        }

        if (remoteUser != null) {
            PrincipalThreadLocal.setName(remoteUser);

            long userId = GetterUtil.getLong(remoteUser);

            User user = UserLocalServiceUtil.getUserById(userId);

            PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user, true);

            PermissionThreadLocal.setPermissionChecker(permissionChecker);
        } else {
            if (_log.isWarnEnabled()) {
                _log.warn("User id is not provided. An exception will be "
                        + "thrown  if a protected method is accessed.");
            }
        }

        super.service(request, response);
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:edu.stanford.epad.epadws.security.EPADSessionOperations.java

public static EPADSessionResponse authenticateUser(HttpServletRequest httpRequest) {
    String username = extractUserNameFromAuthorizationHeader(httpRequest);
    String password = extractPasswordFromAuthorizationHeader(httpRequest);
    if (username == null || username.length() == 0) {
        username = httpRequest.getParameter("username");
        password = httpRequest.getParameter("password");
    }//from w w w .  j av a 2  s. c  o m
    EPADSession session = null;
    try {
        if (username != null && password == null && httpRequest.getParameter("adminuser") != null) {
            session = EPADSessionOperations.createProxySession(username, httpRequest.getParameter("adminuser"),
                    httpRequest.getParameter("adminpassword"));
        } else if (username == null && httpRequest.getAuthType().equals("WebAuth")
                && httpRequest.getRemoteUser() != null) {
            if (password != null && password.equals(EPADConfig.webAuthPassword))
                session = EPADSessionOperations.createPreAuthenticatedSession(httpRequest.getRemoteUser());
        } else {
            session = EPADSessionOperations.createNewEPADSession(username, password);
        }
        EPADSessionResponse response = new EPADSessionResponse(HttpServletResponse.SC_OK,
                session.getSessionId(), "");
        log.info("Session ID " + response.response + " generated for user " + username);
        return response;
    } catch (Exception x) {
        EPADSessionResponse response = new EPADSessionResponse(HttpServletResponse.SC_UNAUTHORIZED, null,
                x.getMessage());
        return response;
    }
}

From source file:com.ikon.servlet.DownloadServlet.java

/**
 * //from   ww  w.  java2  s.  co  m
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    request.setCharacterEncoding("UTF-8");
    String userId = request.getRemoteUser();
    String path = WebUtils.getString(request, "path");
    String uuid = WebUtils.getString(request, "uuid");
    boolean inline = WebUtils.getBoolean(request, "inline");
    InputStream is = null;

    try {
        // Now an document can be located by UUID
        if (uuid != null && !uuid.equals("")) {
            path = OKMRepository.getInstance().getNodePath(null, uuid);
        }

        if (path != null) {
            Document doc = OKMDocument.getInstance().getProperties(null, path);
            String fileName = PathUtils.getName(doc.getPath());
            log.info("Download {} by {} ({})",
                    new Object[] { path, userId, (inline ? "inline" : "attachment") });
            is = OKMDocument.getInstance().getContent(null, path, false);
            WebUtils.sendFile(request, response, fileName, doc.getMimeType(), inline, is);
        } else {
            response.setContentType("text/plain; charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("Missing document reference");
            out.close();
        }
    } catch (PathNotFoundException e) {
        log.warn(e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "PathNotFoundException: " + e.getMessage());
    } catch (RepositoryException e) {
        log.warn(e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "RepositoryException: " + e.getMessage());
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        IOUtils.closeQuietly(is);
    }
}