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.iwethey.forums.web.HeaderInterceptor.java

/**
 * Load the request attributes with the User object (if authenticated)
 * and start time for the page for audit purposes.
 * <p>/*from   ww  w  . j  a  v a  2  s  .c o m*/
 * @param request The servlet request object.
 * @param response The servlet response object.
 * @param handler The request handler processing this request.
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    Date now = new Date();
    request.setAttribute("now", now);

    long start = now.getTime();
    request.setAttribute("start", new Long(start));

    Integer id = (Integer) WebUtils.getSessionAttribute(request, USER_ID_ATTRIBUTE);

    User user = null;

    if (id == null) {
        user = (User) WebUtils.getSessionAttribute(request, USER_ATTRIBUTE);

        if (user == null) {
            user = new User("Anonymous");
            WebUtils.setSessionAttribute(request, USER_ATTRIBUTE, user);
        }
    } else {
        user = mUserManager.getUserById(id.intValue());
        user.setLastPresent(new Date());
        mUserManager.saveUserAttributes(user);
    }

    request.setAttribute("username", user.getNickname());
    request.setAttribute(USER_ATTRIBUTE, user);

    System.out.println("Local Address  = [" + request.getLocalAddr() + "]");
    System.out.println("Local Name     = [" + request.getLocalName() + "]");
    System.out.println("Remote Address = [" + request.getRemoteAddr() + "]");
    System.out.println("Remote Host    = [" + request.getRemoteHost() + "]");
    System.out.println("Remote Port    = [" + request.getRemotePort() + "]");
    System.out.println("Remote User    = [" + request.getRemoteUser() + "]");
    System.out.println("Context Path   = [" + request.getContextPath() + "]");
    System.out.println("====================");

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            System.out.println("Cookie Domain = [" + cookie.getDomain() + "]");
            System.out.println("Cookie Name   = [" + cookie.getName() + "]");
            System.out.println("Cookie Value  = [" + cookie.getValue() + "]");
            System.out.println("Cookie Expire = [" + cookie.getMaxAge() + "]");
            System.out.println("====================");

            if ("iwt_cookie".equals(cookie.getName())) {
                cookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6);
                response.addCookie(cookie);
            }
        }
    } else {
        System.out.println("No cookies were found in the request");
    }

    Cookie newCookie = new Cookie("iwt_cookie", "harrr2!");
    newCookie.setPath(request.getContextPath());
    newCookie.setDomain(request.getLocalName());
    newCookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6);
    response.addCookie(newCookie);

    request.setAttribute(HEADER_IMAGE_ATTRIBUTE, "/images/iwethey-lrpd-small.png");

    return true;
}

From source file:com.ikon.servlet.admin.PropertyGroupsServlet.java

/**
 * List property groups/*from w  ww  . j ava2 s . com*/
 * @throws Exception 
 */
private void list(HttpServletRequest request, HttpServletResponse response) throws Exception {
    log.debug("list({}, {})", new Object[] { request, response });
    ServletContext sc = getServletContext();

    XMLUtils utils = new XMLUtils(PROPERTY_GROUPS_XML);
    if (utils.isPGXMLEmpty()) {
        sc.getRequestDispatcher("/admin/property_group_register.jsp").forward(request, response);
    } else {

        FormUtils.resetPropertyGroupsForms();
        OKMPropertyGroup okmPropGroups = OKMPropertyGroup.getInstance();
        List<PropertyGroup> groups = okmPropGroups.getAllGroups(null);
        Map<PropertyGroup, List<Map<String, String>>> pGroups = new LinkedHashMap<PropertyGroup, List<Map<String, String>>>();

        for (PropertyGroup group : groups) {
            List<FormElement> mData = okmPropGroups.getPropertyGroupForm(null, group.getName());
            List<Map<String, String>> fMaps = new ArrayList<Map<String, String>>();

            for (FormElement fe : mData) {
                fMaps.add(FormUtils.toString(fe));
            }

            pGroups.put(group, fMaps);
        }

        sc.setAttribute("pGroups", pGroups);
        sc.getRequestDispatcher("/admin/property_groups_list.jsp").forward(request, response);

        // Activity log
        UserActivity.log(request.getRemoteUser(), "ADMIN_PROPERTY_GROUP_LIST", null, null, null);
    }
    log.debug("list: void");
}

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

@POST
@Path("picture/")
@Produces("text/json")
public Response postPicture(@Context HttpServletRequest con, @PathParam("username") String username) {

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

    boolean success = false;

    //String profilePicturesPath = "C:\\OpenRide\\pictures\\profile";
    String profilePicturesPath = "../OpenRideWeb/img/profile/default";

    //TODO/*from  www .j ava 2  s .c  o m*/
    //String imagePath = getServletConfig().getInitParameter("imagePath");

    // FIXME: The following try/catch may be removed for production deployments:
    /*try {
    if (java.net.InetAddress.getLocalHost().getHostName().equals("elan-tku-r2032.fokus.fraunhofer.de")) {
        profilePicturesPath = "/mnt/windows/OpenRide/pictures/profile";
    }
    else if (java.net.InetAddress.getLocalHost().getHostName().equals("robusta2.fokus.fraunhofer.de")) {
        profilePicturesPath = "/usr/lib/openride/pictures/profile";
    }
    } catch (UnknownHostException ex) {
    }*/

    int picSize = 125;
    int picThumbSize = 60;

    // check if remote user == {username} in path param
    if (!username.equals(con.getRemoteUser())) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }

    if (ServletFileUpload.isMultipartContent(con)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(con);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        if (items != null) {
            Iterator<FileItem> iter = items.iterator();

            CustomerEntity c = customerControllerBean.getCustomerByNickname(username);
            String uploadedFileName = c.getCustNickname() + "_" + c.getCustId();

            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (!item.isFormField() && item.getSize() > 0) {

                    try {
                        BufferedImage uploadedPicture = ImageIO.read(item.getInputStream());

                        int newWidth, newHeight;
                        int xPos, yPos;
                        float ratio = (float) uploadedPicture.getHeight() / (float) uploadedPicture.getWidth();

                        // Resize for "large" size
                        if (uploadedPicture.getWidth() > uploadedPicture.getHeight()) {
                            newWidth = picSize;
                            newHeight = Math.round(newWidth * ratio);
                        } else {
                            newHeight = picSize;
                            newWidth = Math.round(newHeight / ratio);
                        }

                        //System.out.println("new dimensions "+newWidth+"x"+newHeight);

                        Image resizedPicture = uploadedPicture.getScaledInstance(newWidth, newHeight,
                                Image.SCALE_SMOOTH);

                        xPos = Math.round((picSize - newWidth) / 2);
                        yPos = Math.round((picSize - newHeight) / 2);
                        BufferedImage bim = new BufferedImage(picSize, picSize, BufferedImage.TYPE_INT_RGB);
                        bim.createGraphics().setColor(Color.white);
                        bim.createGraphics().fillRect(0, 0, picSize, picSize);
                        bim.createGraphics().drawImage(resizedPicture, xPos, yPos, null);

                        File outputPicture = new File(profilePicturesPath, uploadedFileName + ".jpg");

                        ImageIO.write(bim, "jpg", outputPicture);

                        // Resize again for "thumb" size
                        if (uploadedPicture.getWidth() > uploadedPicture.getHeight()) {
                            newWidth = picThumbSize;
                            newHeight = Math.round(newWidth * ratio);
                        } else {
                            newHeight = picThumbSize;
                            newWidth = Math.round(newHeight / ratio);
                        }

                        //System.out.println("new dimensions "+newWidth+"x"+newHeight);

                        resizedPicture = uploadedPicture.getScaledInstance(newWidth, newHeight,
                                Image.SCALE_SMOOTH);

                        xPos = Math.round((picThumbSize - newWidth) / 2);
                        yPos = Math.round((picThumbSize - newHeight) / 2);
                        bim = new BufferedImage(picThumbSize, picThumbSize, BufferedImage.TYPE_INT_RGB);
                        bim.createGraphics().setColor(Color.white);
                        bim.createGraphics().fillRect(0, 0, picThumbSize, picThumbSize);
                        bim.createGraphics().drawImage(resizedPicture, xPos, yPos, null);

                        outputPicture = new File(profilePicturesPath, uploadedFileName + "_thumb.jpg");

                        ImageIO.write(bim, "jpg", outputPicture);

                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("File upload / resize unsuccessful.");
                    }
                    success = true;
                }
            }
        }
    }

    if (success) {

        // TODO: Perhaps introduce a redirection target as a parameter to the putProfile method and redirect to that URL (code 301/302) instead of just doing nothing.
        return null;

        /*
        try {
        String referer = con.getHeader("HTTP_REFERER");
        System.out.println("putPicture: Referer: " + referer);
        if (referer != null)
        return Response.status(Response.Status.SEE_OTHER).contentLocation(new URI(referer)).build();
        else
        return Response.ok().build();
        } catch (URISyntaxException ex) {
        Logger.getLogger(ProfileService.class.getName()).log(Level.SEVERE, null, ex);
        return Response.status(Response.Status.BAD_REQUEST).build();
        }
         */
    } else {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}

From source file:org.apache.struts.action.RequestProcessor.java

/**
 * <p>If this action is protected by security roles, make sure that the
 * current user possesses at least one of them.  Return <code>true</code>
 * to continue normal processing, or <code>false</code> if an appropriate
 * response has been created and processing should terminate.</p>
 *
 * @param request  The servlet request we are processing
 * @param response The servlet response we are creating
 * @param mapping  The mapping we are using
 * @return <code>true</code> to continue normal processing;
 *         <code>false</code> if a response has been created.
 * @throws IOException      if an input/output error occurs
 * @throws ServletException if a servlet exception occurs
 *//* ww  w  .  ja va  2  s .  c  om*/
protected boolean processRoles(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping)
        throws IOException, ServletException {
    // Is this action protected by role requirements?
    String[] roles = mapping.getRoleNames();

    if ((roles == null) || (roles.length < 1)) {
        return (true);
    }

    // Check the current user against the list of required roles
    for (int i = 0; i < roles.length; i++) {
        if (request.isUserInRole(roles[i])) {
            if (log.isDebugEnabled()) {
                log.debug(
                        " User '" + request.getRemoteUser() + "' has role '" + roles[i] + "', granting access");
            }

            return (true);
        }
    }

    // The current user is not authorized for this action
    if (log.isDebugEnabled()) {
        log.debug(" User '" + request.getRemoteUser() + "' does not have any required role, denying access");
    }

    response.sendError(HttpServletResponse.SC_FORBIDDEN,
            getInternal().getMessage("notAuthorized", mapping.getPath()));

    return (false);
}

From source file:org.apache.hadoop.fs.webdav.WebdavServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("/--------------------------------------------------");
    log.debug(request.getMethod() + " " + request.getRequestURL().toString());
    log.info(request.getMethod() + " " + request.getRequestURL().toString());
    log.info(request.getMethod() + " " + request.getRequestURI().toString());

    log.info("  RemoteHost: " + request.getRemoteHost());
    log.info("| ATTRIBUTES: ");
    Enumeration e1 = request.getAttributeNames();
    while (e1.hasMoreElements()) {
        String name = (String) e1.nextElement();
        log.info("|| " + name + ": ");
    }/*from w  ww .j  a  v a  2s . c o m*/

    log.info("| PARAMETERS: ");
    Enumeration e2 = request.getParameterNames();
    while (e2.hasMoreElements()) {
        String name = (String) e2.nextElement();
        log.info("|| " + name + ": ");
    }

    log.info("HEADERS: ");
    Enumeration e6 = request.getHeaderNames();
    while (e6.hasMoreElements()) {
        String name = (String) e6.nextElement();
        log.info("-- " + name + ": " + request.getHeader(name));
    }
    log.info("RemoteUser: " + request.getRemoteUser());
    log.info("AuthType: " + request.getAuthType());

    currentUserName = request.getRemoteUser();

    String roles = "";
    if (currentUserRoles != null) {
        for (String roleName : currentUserRoles) {
            roles += roleName + ", ";
        }
        if (roles.length() > 2) {
            roles = roles.substring(0, roles.length() - 2);
        }
    }
    log.debug("Roles: " + roles);

    try {
        super.service(request, response);
    } catch (Exception e) {
        if (e.getCause() instanceof AccessControlException) {
            log.info("EXCEPTION: Can't access to resource. You don't have permissions.");
            MultiStatusResponse msr = new MultiStatusResponse(request.getRequestURL().toString(), 401,
                    "Can't access to resource. You don't have permissions.");

            MultiStatus ms = new MultiStatus();
            ms.addResponse(msr);

            WebdavResponse webdavResponse = new WebdavResponseImpl(response);
            webdavResponse.sendMultiStatus(ms);
        } else
            new WebdavResponseImpl(response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    log.info("\\--------------------------------------------------");
}

From source file:edu.washington.iam.registry.ws.RelyingPartyController.java

private ModelAndView loginPage(HttpServletRequest request, HttpServletResponse response, int method) {
    String remoteUser = request.getRemoteUser();
    if (remoteUser == null && method == 0) { // social login
        String idp = (String) request.getAttribute("Shib-Identity-Provider");
        String mail = (String) request.getAttribute("mail");
        log.info("social login from " + idp + ", email = " + mail);
        if (idp.equals(googleIdentityProvider)) {
            remoteUser = mail;//ww  w .java 2 s .c o m
        } else {
            log.debug("invalid social login");
            return emptyMV("invalid social login");
        }
    }

    String methodKey = "P";
    if (method == 2)
        methodKey = "2";
    String aclass = (String) request.getAttribute("Shib-AuthnContext-Class");
    if (aclass != null && aclass.equals(SECURE_LOGIN_CLASS))
        methodKey = "2";
    log.debug("method = " + method + ", key = " + methodKey);

    if (remoteUser != null) {
        if (remoteUser.endsWith("@washington.edu")) {
            remoteUser = remoteUser.substring(0, remoteUser.lastIndexOf("@washington.edu"));
            log.info("dropped @washington.edu to get id = " + remoteUser);
        }

        if (remoteUser.endsWith("@uw.edu")) {
            // no longer allow google's @uw to be same as UW login
            // remoteUser = remoteUser.substring(0, remoteUser.lastIndexOf("@uw.edu"));
            // log.info("dropped @uw.edu to get id = " + remoteUser);
            ////return loginChooserMV(session, request, response);  // return to login chooser
            // until we can report some misuse
            return emptyMV("invalid social login");
        }

        double dbl = Math.random();
        long modtime = new Date().getTime(); // milliseconds
        log.debug("login: ck = ...;" + remoteUser + ";" + dbl + ";" + methodKey + ";" + modtime / 1000);
        String enc = RPCrypt.encode(Double.toString(modtime) + ";" + remoteUser + ";" + dbl + ";" + methodKey
                + ";" + modtime / 1000);
        log.debug("login: enc = " + enc);
        Cookie c = new Cookie(loginCookie, enc);
        c.setSecure(true);
        c.setPath("/");
        response.addCookie(c);
        try {
            String rp = request.getPathInfo();
            int sp = rp.indexOf("/", 2);
            log.debug("in path = " + rp);
            String red = browserRootPath + request.getServletPath();
            if (sp > 1)
                red = red + rp.substring(sp);
            if (request.getQueryString() != null)
                red = red + "?" + request.getQueryString();
            log.debug("logon ok, return to " + red);
            response.sendRedirect(red);
        } catch (IOException e) {
            log.error("redirect: " + e);
            return emptyMV("redirect error");
        }
    } else {
        // send login failed message
        ModelAndView mv = new ModelAndView("browser/nologin");
        mv.addObject("root", browserRootPath);
        mv.addObject("vers", request.getServletPath());
        mv.addObject("pageTitle", "login failed");
        mv.addObject("myEntityId", myEntityId);
        return mv;
    }
    return emptyMV();
}

From source file:com.almende.eve.transport.http.AgentServlet.java

/**
 * Send a JSON-RPC message to an agent Usage: POST /servlet/{agentId} With a
 * JSON-RPC request as body. Response will be a JSON-RPC response.
 * //from  ww  w .  j  a v a  2 s .  com
 * @param req
 *            the req
 * @param resp
 *            the resp
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             the servlet exception
 */
@Override
public void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws IOException, ServletException {

    // retrieve the agent url and the request body
    final String body = StringUtil.streamToString(req.getInputStream());

    final String agentUrl = req.getRequestURI();
    String agentId;
    try {
        agentId = httpTransport.getAgentId(new URI(agentUrl));
    } catch (URISyntaxException e) {
        throw new ServletException(AGENTURLWARNING, e);
    }
    if (agentId == null || agentId.equals("")) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No agentId found in url.");
        resp.flushBuffer();
        return;
    }

    if (host.hasPrivate(agentId) && !handleSession(req, resp)) {
        if (!resp.isCommitted()) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
        resp.flushBuffer();
        return;
    }

    // Attach the claimed senderId, or null if not given.
    String senderUrl = req.getHeader("X-Eve-SenderUrl");
    if (senderUrl == null || senderUrl.equals("")) {
        senderUrl = "web://" + req.getRemoteUser() + "@" + req.getRemoteAddr();
    }
    final String tag = new UUID().toString();

    final SyncCallback<String> callback = new SyncCallback<String>();

    final AsyncCallbackQueue<String> callbacks = host.getCallbackQueue("HttpTransport", String.class);
    callbacks.push(tag, "", callback);
    //TODO: check if it's base64 encoded data, decode to byte[] and call receive byte[].
    host.receive(agentId, body, URI.create(senderUrl), tag);

    try {
        final Object message = callback.get();
        // return response
        resp.addHeader("Content-Type", "application/json");
        resp.getWriter().println(message.toString());
        resp.getWriter().close();
    } catch (final Exception e) {
        LOG.log(Level.WARNING, "Http Sync receive raised exception.", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Receiver raised exception:" + e.getMessage());
    }
    resp.flushBuffer();
}

From source file:org.eclipse.orion.server.useradmin.servlets.UserHandlerV1.java

private boolean handleUserPut(HttpServletRequest req, HttpServletResponse resp, String userId)
        throws ServletException, IOException, CoreException, JSONException {
    JSONObject data = OrionServlet.readJSONRequest(req);

    IOrionCredentialsService userAdmin = null;
    User user = null;//  w w  w . j a v  a  2s .com
    if (getGuestUserAdmin() != null) {
        userAdmin = getGuestUserAdmin();
        user = userAdmin.getUser(UserConstants.KEY_UID, userId);
    }
    // Fallback to regular user admin
    if (user == null) {
        userAdmin = getUserAdmin();
        user = userAdmin.getUser(UserConstants.KEY_UID, userId);
    }

    if (user == null)
        return statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "User " + userId + " could not be found.", null));
    String emailConfirmationid = user.getConfirmationId();

    //users other than admin have to know the old password to set a new one
    if (!isAdmin(req.getRemoteUser())) {
        if (data.has(UserConstants.KEY_PASSWORD) && user.getPassword() != null
                && (!data.has(UserConstants.KEY_OLD_PASSWORD)
                        || !user.getPassword().equals(data.getString(UserConstants.KEY_OLD_PASSWORD)))) {
            return statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR,
                    HttpServletResponse.SC_BAD_REQUEST, "Invalid old password", null));
        }
    }

    if (data.has(UserConstants.KEY_OLD_PASSWORD) && (!data.has(UserConstants.KEY_PASSWORD)
            || data.getString(UserConstants.KEY_PASSWORD).length() == 0)) {
        return statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "Password cannot be empty", null));
    }
    if (data.has(UserConstants.KEY_LOGIN))
        user.setLogin(data.getString(UserConstants.KEY_LOGIN));
    if (data.has(ProtocolConstants.KEY_NAME))
        user.setName(data.getString(ProtocolConstants.KEY_NAME));
    if (data.has(UserConstants.KEY_PASSWORD))
        user.setPassword(data.getString(UserConstants.KEY_PASSWORD));
    if (data.has(UserConstants.KEY_EMAIL)) {
        user.setEmail(data.getString(UserConstants.KEY_EMAIL));
    }

    if (data.has(UserConstants.KEY_PROPERTIES)) {
        JSONObject propertiesObject = data.getJSONObject(UserConstants.KEY_PROPERTIES);
        Iterator<?> propertyIterator = propertiesObject.keys();
        while (propertyIterator.hasNext()) {
            String propertyKey = (String) propertyIterator.next();
            user.addProperty(propertyKey, propertiesObject.getString(propertyKey));
        }
    }
    IStatus status = userAdmin.updateUser(userId, user);
    if (!status.isOK()) {
        return statusHandler.handleRequest(req, resp, status);
    }

    IOrionUserProfileNode userNode = getUserProfileService().getUserProfileNode(userId, true)
            .getUserProfileNode(IOrionUserProfileConstants.GENERAL_PROFILE_PART);
    if (userNode != null) {
        if (data.has("GitMail"))
            userNode.put("GitMail", data.getString("GitMail"), false);
        if (data.has("GitName"))
            userNode.put("GitName", data.getString("GitName"), false);
        userNode.flush();
    }

    if (user.getConfirmationId() != null && !user.getConfirmationId().equals(emailConfirmationid)) {
        try {
            UserEmailUtil.getUtil().sendEmailConfirmation(req, user);
            return statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.INFO,
                    HttpServletResponse.SC_OK, "Confirmation email has been sent to " + user.getEmail(), null));
        } catch (Exception e) {
            LogHelper.log(new Status(IStatus.ERROR, Activator.PI_SERVER_SERVLETS, "Error while sending email"
                    + (e.getMessage() == null ? "" : ": " + e.getMessage())
                    + ". See http://wiki.eclipse.org/Orion/Server_admin_guide#Email_configuration for email configuration guide."));
            return statusHandler.handleRequest(req, resp,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                            "Could not send confirmation email to " + user.getEmail(), null));
        }
    }

    return true;
}

From source file:org.ngrinder.script.controller.SvnDavController.java

@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
private void logRequest(HttpServletRequest request) {
    StringBuilder logBuffer = new StringBuilder();
    logBuffer.append('\n');
    logBuffer.append("request.getAuthType(): " + request.getAuthType());
    logBuffer.append('\n');
    logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding());
    logBuffer.append('\n');
    logBuffer.append("request.getContentType(): " + request.getContentType());
    logBuffer.append('\n');
    logBuffer.append("request.getContextPath(): " + request.getContextPath());
    logBuffer.append('\n');
    logBuffer.append("request.getContentLength(): " + request.getContentLength());
    logBuffer.append('\n');
    logBuffer.append("request.getMethod(): " + request.getMethod());
    logBuffer.append('\n');
    logBuffer.append("request.getPathInfo(): " + request.getPathInfo());
    logBuffer.append('\n');
    logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated());
    logBuffer.append('\n');
    logBuffer.append("request.getQueryString(): " + request.getQueryString());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURI(): " + request.getRequestURI());
    logBuffer.append('\n');
    logBuffer.append("request.getServerName(): " + request.getServerName());
    logBuffer.append('\n');
    logBuffer.append("request.getServerPort(): " + request.getServerPort());
    logBuffer.append('\n');
    logBuffer.append("request.getServletPath(): " + request.getServletPath());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURL(): " + request.getRequestURL());
    LOGGER.trace(logBuffer.toString());//  w w w.j a va2  s  .  c  o  m
}

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

/**
 * shows the case form.//w w w.j  ava 2 s. c o m
 * 
 * @param filters
 *            the filters
 * @param request
 *            the request
 * @param response
 *            the response
 * @return ModelView
 * @throws Exception
 *             the exception
 * @see caseform.jsp
 */
@ModelAttribute("activeCard")
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView showForm(final CardFilterHolder filters, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    AlphaCard activeCard = null;
    User currentUser = null;
    final String caseId = request.getParameter("caseId");
    final String activeCardId = request.getParameter("activeCardId");

    final ModelAndView m = new ModelAndView("caseform");

    if (request.getParameter("isMyWorklist") != null) {
        m.addObject("isMyWorklist", true);
        filters.setContributor(CardFilterContributor.OWN);
        filters.setDataProvision(CardFilterDataProvision.NOTFULFILLED);

        filters.setContributorRole(CardFilterContributorRole.ALL);
        filters.setShowDeleted(CardFilterDeleted.NOTDELETED);
    }

    /**
     * Merge filters with Session
     */
    filters.mergeFiltersWithSession(request, response);

    if (!StringUtils.isBlank(caseId) && (caseId.equals("last") || this.caseManager.exists(caseId))) {

        currentUser = this.userManager.getUserByUsername(request.getRemoteUser());
        UserSession userSession;
        if (this.userSessionManager.exists(currentUser.getId())) {
            userSession = this.userSessionManager.get(currentUser.getId());
        } else {
            userSession = new UserSession();
            userSession.setUserId(currentUser.getId());
        }
        m.addObject("currentUserId", currentUser.getId());

        AlphaCase apCase = null;
        // show last viewed case
        if (caseId.equals("last")) {
            final String lastCaseId = userSession.getLastViewedCaseId();
            if (StringUtils.isBlank(lastCaseId) || !this.caseManager.exists(lastCaseId)) {
                // redirect to list
                response.sendRedirect("caseMenu");
            } else {
                apCase = this.caseManager.get(lastCaseId);
            }

        } else {
            apCase = this.caseManager.get(caseId);
            if ((apCase != null) && !StringUtils.isBlank(apCase.getCaseId())) {
                userSession.setLastViewedCaseId(apCase.getCaseId());
                this.userSessionManager.save(userSession);
            }
        }

        m.addObject("case", apCase);
        if (apCase != null) {
            this.setSuccessView("redirect:/caseform?caseId=" + apCase.getCaseId());
            m.addObject("cards", this.filterAlphaCards(apCase, filters, currentUser));

            m.addObject("participants", apCase.getListOfParticipants());

            final AlphaCardIdentifier activeCardIdentifier = new AlphaCardIdentifier(caseId, activeCardId);
            if (!StringUtils.isBlank(activeCardId)) {

                if (this.alphaCardManager.exists(activeCardIdentifier)) {
                    activeCard = this.alphaCardManager.get(activeCardIdentifier);
                    m.addObject("activeCard", activeCard);

                    final Adornment deletedAdornment = activeCard.getAlphaCardDescriptor()
                            .getAdornment(AdornmentType.Deleted.getName());
                    if (deletedAdornment != null) {
                        if (deletedAdornment.getValue().equals(AdornmentTypeDeleted.TRUE.value())) {
                            m.addObject("activeCardIsDeleted", true);
                        }
                    }

                    boolean hidePayload = false;

                    final Adornment contrbitorAdornment = activeCard.getAlphaCardDescriptor()
                            .getAdornment(AdornmentType.Contributor.getName());

                    final Adornment visibilityAdornment = activeCard.getAlphaCardDescriptor()
                            .getAdornment(AdornmentType.Visibility.getName());

                    if ((contrbitorAdornment != null) && (visibilityAdornment != null)) {
                        final String cId = contrbitorAdornment.getValue();
                        final String vis = visibilityAdornment.getValue();

                        if ((cId != null) && !cId.isEmpty()) {

                            final Long contributorID = Long.parseLong(activeCard.getAlphaCardDescriptor()
                                    .getAdornment(AdornmentType.Contributor.getName()).getValue());

                            if (vis.equals(AdornmentTypeVisibility.PRIVATE.value()) && (contributorID != null)
                                    && !(currentUser.getId() == contributorID)) {

                                hidePayload = true;
                            }
                        } else {

                            if (activeCard.getAlphaCardDescriptor()
                                    .getAdornment(AdornmentType.Visibility.getName()).getValue()
                                    .equals(AdornmentTypeVisibility.PRIVATE.value())) {

                                hidePayload = true;
                            }
                        }
                    }

                    m.addObject("hidePayload", hidePayload);

                    boolean currentUserMatchesContributorRole = false;
                    if (StringUtils.isBlank(activeCard.getAlphaCardDescriptor().getContributorRole())) {
                        currentUserMatchesContributorRole = true;
                    }
                    if (!currentUserMatchesContributorRole) {
                        final ContributorRole role = this.contributorRoleManager.getContributorRoleByName(
                                activeCard.getAlphaCardDescriptor().getContributorRole());
                        if (role == null) {
                            currentUserMatchesContributorRole = true;
                        } else if (this.userExtensionManager.exists(currentUser.getId())) {
                            final UserExtension ue = this.userExtensionManager.get(currentUser.getId());
                            if (ue != null) {
                                currentUserMatchesContributorRole = ue.hasRole(role);
                            }
                        }
                    }
                    m.addObject("currentUserMatchesContributorRole", currentUserMatchesContributorRole);
                    m.addObject("currentUserIsContributor",
                            currentUser.getId() == activeCard.getAlphaCardDescriptor().getContributor());

                    // new gui stuff
                    final Set<String> userRoleStrings = new HashSet<String>();
                    if (this.userExtensionManager.exists(currentUser.getId())) {
                        final Set<ContributorRole> UserRoles = this.userExtensionManager
                                .get(currentUser.getId()).getRoles();
                        for (final ContributorRole contributorRole : UserRoles) {
                            userRoleStrings.add(contributorRole.getName());
                        }
                    }
                    m.addObject("currentUserContributorRoles", userRoleStrings.toArray(new String[] {}));

                    this.setSuccessView("redirect:/caseform?caseId=" + apCase.getCaseId() + "&activeCardId="
                            + activeCardIdentifier.getCardId());

                } else if (activeCardId.equals("new")) {
                    m.addObject("activeCard", this.alphaCardManager.createAlphaCard(caseId));

                }
            }

        }

        // Filters
        m.addObject("filters", filters);

        // Essential Adornments
        final List<String> essential = new LinkedList<String>();
        essential.add(AdornmentType.Title.getName());
        essential.add(AdornmentType.Contributor.getName());
        essential.add(AdornmentType.ContributorRole.getName());
        m.addObject("essentialAdornments", essential.toArray(new String[] {}));

    } else {
        m.addObject("case", new AlphaCase());
    }
    return m;
}