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:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java

/**
 * Secure a service response before sending it to the client.
 * <p/>//from   www. j  ava2 s. c om
 * This method is called to transform the response message acquired by
 * calling getResponseMessage (on messageInfo) into the mechanism-specific
 * form to be sent by the runtime.
 * <p>
 * This method conveys the outcome of its message processing either by
 * returning an AuthStatus value or by throwing an AuthException.
 * 
 * @param messageInfo
 *            A contextual object that encapsulates the client request and
 *            server response objects, and that may be used to save state
 *            across a sequence of calls made to the methods of this
 *            interface for the purpose of completing a secure message
 *            exchange.
 * @param serviceSubject
 *            A Subject that represents the source of the service response,
 *            or null. It may be used by the method implementation to
 *            retrieve Principals and credentials necessary to secure the
 *            response. If the Subject is not null, the method
 *            implementation may add additional Principals or credentials
 *            (pertaining to the source of the service response) to the
 *            Subject.
 * @return An AuthStatus object representing the completion status of the
 *         processing performed by the method. The AuthStatus values that
 *         may be returned by this method are defined as follows:
 *         <p/>
 *         <ul>
 *         <li>AuthStatus.SEND_SUCCESS when the application response message
 *         was successfully secured. The secured response message may be
 *         obtained by calling getResponseMessage on messageInfo.
 *         <p/>
 *         <li>AuthStatus.SEND_CONTINUE to indicate that the application
 *         response message (within messageInfo) was replaced with a
 *         security message that should elicit a security-specific response
 *         (in the form of a request) from the peer.
 *         <p/>
 *         This status value serves to inform the calling runtime that (to
 *         successfully complete the message exchange) it will need to be
 *         capable of continuing the message dialog by processing at least
 *         one additional request/response exchange (after having sent the
 *         response message returned in messageInfo).
 *         <p/>
 *         When this status value is returned, the application response must
 *         be saved by the authentication module such that it can be
 *         recovered when the module's validateRequest message is called to
 *         process the elicited response.
 *         <p/>
 *         <li>AuthStatus.SEND_FAILURE to indicate that a failure occurred
 *         while securing the response message and that an appropriate
 *         failure response message is available by calling
 *         getResponseMeessage on messageInfo.
 *         </ul>
 * @throws AuthException When the message processing failed without
 *         establishing a failure response message (in messageInfo).
 */
public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException {

    final HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
    final Principal clientPrincipal = request.getUserPrincipal();
    // There should be a session as validate request created one at the end
    final HttpSession session = request.getSession(false);

    // As the session might have changed in the middle (for security
    // reason),
    // we make sure the settings are saved. Plus if coming from
    // SessionState.ESTABLISHED
    // on an existing session, we might have still something to set for the
    // next Filters
    updateSessionAndHeader(request, session, clientPrincipal);

    debug("secureResponse was called and session was updated");

    return AuthStatus.SEND_SUCCESS;
}

From source file:com.duroty.application.mail.actions.CreateIdentityAction.java

/**
 * DOCUMENT ME!/*from w w w.  ja  va  2 s.  c om*/
 *
 * @param mapping DOCUMENT ME!
 * @param form DOCUMENT ME!
 * @param request DOCUMENT ME!
 * @param response DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 */
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ActionMessages errors = new ActionMessages();

    try {
        Preferences preferencesInstance = getPreferencesInstance(request);

        PreferencesObj preferencesObj = preferencesInstance.getPreferences();

        DynaActionForm _form = (DynaActionForm) form;

        IdentityObj identityObj = new IdentityObj();

        identityObj.setEmail((String) _form.get("email"));

        Boolean important = (Boolean) _form.get("default");

        if (important == null) {
            important = new Boolean(false);
        }

        identityObj.setImportant(important.booleanValue());
        identityObj.setName((String) _form.get("name"));
        identityObj.setReplyTo((String) _form.get("replyTo"));

        String code = preferencesInstance.createIdentity(identityObj);

        String body = getEmailBody(request, preferencesObj.getLanguage());

        MessageResources message = getResources(request);
        String subject = message.getMessage("general.title");

        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + path + "/mail/preferences/validateIdentity.drt?user=" + request.getUserPrincipal() + "&code="
                + code;

        body = body.replaceAll("\\$\\{email\\}", identityObj.getEmail());
        body = body.replaceAll("\\$\\{url\\}", basePath);

        IdentityObj identityDefault = preferencesInstance.getIdentityDefault();

        Send sendInstance = getSendInstance(request);
        sendInstance.sendIdentity(identityDefault.getEmail(), identityObj.getEmail(), subject, body);
    } catch (Exception ex) {
        String errorMessage = ExceptionUtilities.parseMessage(ex);

        if (errorMessage == null) {
            errorMessage = "NullPointerException";
        }

        errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage));
        request.setAttribute("exception", errorMessage);
        doTrace(request, DLog.ERROR, getClass(), errorMessage);
    } finally {
    }

    if (errors.isEmpty()) {
        doTrace(request, DLog.INFO, getClass(), "OK");

        return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD);
    } else {
        saveErrors(request, errors);

        return mapping.findForward(Constants.ACTION_FAIL_FORWARD);
    }
}

From source file:com.salesmanBuddy.Controllers.SalesmanBuddy.java

@Path("stockNumbers")
@PUT/*from  ww  w.j  ava 2  s  .co m*/
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response newStockNumber(@Context HttpServletRequest request, StockNumbers stockNumber,
        @DefaultValue("0") @QueryParam("dealershipId") Integer dealershipId,
        @DefaultValue("") @QueryParam("stockNumber") String stockNumberNumber,
        @DefaultValue("-1") @QueryParam("status") Integer status) {
    String googleUserId = request.getUserPrincipal().getName();
    Users user = this.dao.getUserByGoogleId(googleUserId);
    if (dealershipId == 0)
        dealershipId = user.getDealershipId();

    if (user.getType() > 2
            || (user.getDealershipId() == stockNumber.getDealershipId() && user.getType() == 2)) {
        if (dealershipId != 0 && stockNumberNumber.length() > 0) {
            stockNumber = new StockNumbers();
            stockNumber.setDealershipId(dealershipId);
            stockNumber.setStockNumber(stockNumberNumber);
            stockNumber.setStatus((status == -1) ? 0 : status);
            stockNumber.setCreatedBy(user.getId());
        }
        return Response.ok().entity(this.dao.newStockNumber(stockNumber)).build();
    }
    return Response.status(400)
            .entity(new ErrorMessage("You must be an sb employee or belong to this dealership to do this"))
            .build();
}

From source file:com.francelabs.datafari.servlets.URL.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)// w w  w. java 2s .  c  o  m
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    final String protocol = request.getScheme() + ":";

    final Map<String, String[]> requestMap = new HashMap<>();
    requestMap.putAll(request.getParameterMap());
    final IndexerQuery query = IndexerServerManager.createQuery();
    query.addParams(requestMap);
    // get the AD domain
    String domain = "";
    HashMap<String, String> h;
    try {
        h = RealmLdapConfiguration.getConfig(request);

        if (h.get(RealmLdapConfiguration.ATTR_CONNECTION_NAME) != null) {
            final String userBase = h.get(RealmLdapConfiguration.ATTR_DOMAIN_NAME).toLowerCase();
            final String[] parts = userBase.split(",");
            domain = "";
            for (int i = 0; i < parts.length; i++) {
                if (parts[i].indexOf("dc=") != -1) { // Check if the current
                    // part is a domain
                    // component
                    if (!domain.isEmpty()) {
                        domain += ".";
                    }
                    domain += parts[i].substring(parts[i].indexOf('=') + 1);
                }
            }
        }

        // Add authentication
        if (request.getUserPrincipal() != null) {
            String AuthenticatedUserName = request.getUserPrincipal().getName().replaceAll("[^\\\\]*\\\\", "");
            if (AuthenticatedUserName.contains("@")) {
                AuthenticatedUserName = AuthenticatedUserName.substring(0, AuthenticatedUserName.indexOf("@"));
            }
            if (!domain.equals("")) {
                AuthenticatedUserName += "@" + domain;
            }
            query.setParam("AuthenticatedUserName", AuthenticatedUserName);
        }
    } catch (final Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    StatsPusher.pushDocument(query, protocol);

    // String surl = URLDecoder.decode(request.getParameter("url"),
    // "ISO-8859-1");
    final String surl = request.getParameter("url");

    if (ScriptConfiguration.getProperty("ALLOWLOCALFILEREADING").equals("true")
            && !surl.startsWith("file://///")) {

        final int BUFSIZE = 4096;
        String fileName = null;

        /**
         * File Display/Download --> <!-- Written by Rick Garcia -->
         */
        if (SystemUtils.IS_OS_LINUX) {
            // try to open the file locally
            final String fileNameA[] = surl.split(":");
            fileName = URLDecoder.decode(fileNameA[1], "UTF-8");

        } else if (SystemUtils.IS_OS_WINDOWS) {
            fileName = URLDecoder.decode(surl, "UTF-8").replaceFirst("file:/", "");
        }

        final File file = new File(fileName);
        int length = 0;
        final ServletOutputStream outStream = response.getOutputStream();
        final ServletContext context = getServletConfig().getServletContext();
        String mimetype = context.getMimeType(fileName);

        // sets response content type
        if (mimetype == null) {
            mimetype = "application/octet-stream";

        }
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());

        // sets HTTP header
        response.setHeader("Content-Disposition", "inline; fileName=\"" + fileName + "\"");

        final byte[] byteBuffer = new byte[BUFSIZE];
        final DataInputStream in = new DataInputStream(new FileInputStream(file));

        // reads the file's bytes and writes them to the response stream
        while (in != null && (length = in.read(byteBuffer)) != -1) {
            outStream.write(byteBuffer, 0, length);
        }

        in.close();
        outStream.close();
    } else {

        final RequestDispatcher rd = request.getRequestDispatcher(redirectUrl);
        rd.forward(request, response);
    }
}

From source file:org.nuxeo.ecm.platform.ui.web.shield.ErrorPageForwarder.java

private String getRequestDump(HttpServletRequest request) {
    StringBuilder builder = new StringBuilder();
    builder.append("\nParameter:\n");
    Map<String, String[]> m = request.getParameterMap();
    for (Map.Entry<String, String[]> entry : m.entrySet()) {
        builder.append(entry.getKey()).append(":");
        if (entry.getValue() == null) {
            continue;
        }/* w w w .j a  v a  2s  . c om*/
        for (String s : entry.getValue()) {
            builder.append(s).append(",");
        }
        builder.deleteCharAt(builder.length() - 1);
        builder.append("\n");
    }
    builder.append("\n");
    Enumeration<String> names = request.getAttributeNames();
    builder.append("Attributes:\n");
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        if (name.equals(SEAM_MESSAGES)) {
            continue;
        }
        Object obj = request.getAttribute(name);
        builder.append(name).append(": ").append(obj.toString()).append("\n");
    }
    builder.append("\n");
    Collection<RegistrationInfo> infos = Framework.getRuntime().getComponentManager().getRegistrations();
    builder.append("Components:\n");
    for (RegistrationInfo info : infos) {
        builder.append(info.getComponent().getName()).append(",")
                .append(info.isActivated() ? "activated" : "not activated").append("\n");
    }
    nuxeoErrorLog.trace("User Principal: " + request.getUserPrincipal() + "\n" + builder.toString());
    return builder.toString();
}

From source file:au.edu.uq.cmm.paul.servlet.WebUIController.java

@RequestMapping(value = "/manageDatasets", method = RequestMethod.POST)
public String manageDatasets(Model model, HttpServletRequest request, HttpServletResponse response,
        @RequestParam(required = false) String[] ids, @RequestParam(required = false) String userName,
        @RequestParam(required = false) String slice, @RequestParam(required = false) String confirmed,
        @RequestParam String action, @RequestParam(required = false) String facilityName)
        throws IOException, QueueFileException, InterruptedException {
    GenericPrincipal principal = (GenericPrincipal) request.getUserPrincipal();
    if (principal == null) {
        LOG.error("No principal ... can't proceed");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }// www .j a  v  a  2 s  . c o m
    if (!principal.hasRole("ROLE_ADMIN")) {
        model.addAttribute("message", "Only an administrator can manage datasets");
        return "failed";
    }
    Slice s = inferSlice(slice);
    model.addAttribute("facilityName", facilityName);
    model.addAttribute("slice", s);
    model.addAttribute("returnTo", inferReturnTo(request));
    if (action.equals("deleteAll")) {
        return deleteAll(model, request, s, facilityName, true, confirmed);
    } else if (action.equals("archiveAll")) {
        return deleteAll(model, request, s, facilityName, false, confirmed);
    } else if (action.equals("expire")) {
        return expire(model, request, s, facilityName, confirmed);
    }
    QueueManager qm = getQueueManager();
    if (ids == null) {
        return retryManage(model, "Check the checkboxes for the Datasets you want to " + action, qm, s,
                facilityName);
    }
    try {
        int nosChanged;
        switch (action) {
        case "archive":
            nosChanged = qm.delete(ids, Removal.ARCHIVE);
            model.addAttribute("message", verbiage(nosChanged, "dataset", "datasets", "archived"));
            return "ok";
        case "delete":
            nosChanged = qm.delete(ids, Removal.DELETE);
            model.addAttribute("message", verbiage(nosChanged, "dataset", "datasets", "deleted"));
            return "ok";
        case "assign":
            try {
                // Check the name is known
                getUserDetailsManager().lookupUser(userName, false);
            } catch (UserDetailsException ex) {
                return retryManage(model, "User '" + userName + "' is not known.", qm, s, facilityName);
            }
            nosChanged = qm.changeUser(ids, userName, true);
            model.addAttribute("message", verbiage(nosChanged, "dataset", "datasets", "assigned"));
            return "ok";
        default:
            LOG.debug("Rejected request with unrecognized action");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return null;
        }
    } catch (NumberFormatException ex) {
        LOG.debug("Rejected request with bad entry id(s)");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }
}

From source file:com.salesmanBuddy.Controllers.SalesmanBuddy.java

@Path("licenses") // works 10/13
@GET//from  w  ww  .  j  a  v  a  2s.  c  o m
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getAllLicensesForUserId(@Context HttpServletRequest request,
        @DefaultValue("") @QueryParam("googleUserId") String requestedGoogleUserId,
        @DefaultValue("0") @QueryParam("dealershipId") Integer dealershipId,
        @DefaultValue("false") @QueryParam("all") boolean getAll,
        @DefaultValue("true") @QueryParam("getSubData") boolean getSubData) {
    String googleUserId = request.getUserPrincipal().getName();
    if (getAll) {
        Users user = this.dao.getUserByGoogleId(googleUserId);
        if (user.getType() > 2) {
            List<LicensesListElement> list = this.dao.getAllLicenses();
            this.dao.addQuestionsAndAnswersToLicenseListElements(list);
            GenericEntity<List<LicensesListElement>> entity = new GenericEntity<List<LicensesListElement>>(
                    list) {
            };
            return Response.ok(entity).build();
        }
        return Response.status(400).entity(new ErrorMessage("You must be an SB employee to see all licenses"))
                .build();
    } else if (dealershipId != 0) {
        Users user = this.dao.getUserByGoogleId(googleUserId);
        if (user.getType() > 2 || (user.getDealershipId() == dealershipId && user.getType() == 2)) {// SB employee OR manager type for the requested dealership
            List<LicensesListElement> list = this.dao.getLicensesListElementForDealershipId(dealershipId);
            if (getSubData)
                this.dao.addSubDataToLicensesListElement(list);
            GenericEntity<List<LicensesListElement>> entity = new GenericEntity<List<LicensesListElement>>(
                    list) {
            };
            return Response.ok(entity).build();
        }
        return Response.status(400).entity(new ErrorMessage(
                "You must be an SB employee OR specify a valid dealershipId that is the same as your own and have your type be a manager"))
                .build();
    } else if (requestedGoogleUserId.length() != 0) {
        Users user = this.dao.getUserByGoogleId(googleUserId);
        if (user.getType() > 2 || (user.getType() == 2 && this.dao.getUserByGoogleId(requestedGoogleUserId)
                .getDealershipId() == user.getDealershipId())) {// SB employee OR manager type for the same dealership as the requested user
            List<LicensesListElement> list = this.dao.getLicensesForGoogleUserId(googleUserId);
            this.dao.addSubDataToLicensesListElement(list);
            GenericEntity<List<LicensesListElement>> entity = new GenericEntity<List<LicensesListElement>>(
                    list) {
            };
            return Response.ok(entity).build();
        }
        return Response.status(400).entity(new ErrorMessage(
                "You must be an SB employee OR be a manager at the same dealership as the user you are requesting"))
                .build();
    } else {
        // must be for themselves
        GenericEntity<List<LicensesListElement>> entity = new GenericEntity<List<LicensesListElement>>(
                this.dao.getLicensesForGoogleUserId(googleUserId)) {
        };
        return Response.ok(entity).build();
    }
}

From source file:org.appcelerator.transport.AjaxServiceTransportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ////from   www.j av a  2 s  .com
    // make sure we check the integrity of the request before we continue
    //
    if (!validate(req, resp)) {
        LOG.warn("security validation failed for request=" + req + " from " + req.getRemoteAddr());
        return;
    }

    String type = req.getContentType();
    int idx = type.indexOf(';');

    if (idx > 0) {
        type = type.substring(0, idx);
    }

    try {
        // decode the incoming request
        ArrayList<Message> requests = new ArrayList<Message>(1);
        ArrayList<Message> responses = new ArrayList<Message>(1);

        ServiceMarshaller.getMarshaller(type).decode(req.getInputStream(), requests);

        if (requests.isEmpty()) {
            // no incoming messages, just return accepted header
            resp.setHeader("Content-Length", "0");
            resp.setContentType("text/plain;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }

        HttpSession session = req.getSession();
        InetAddress address = InetAddress.getByName(req.getRemoteAddr());
        //String instanceid = req.getParameter("instanceid");

        for (Message request : requests) {
            request.setUser(req.getUserPrincipal());
            request.setSession(session);
            request.setAddress(address);
            request.setServletRequest(req);

            //FIXME => refactor this out
            if (request.getType().equals(MessageType.APPCELERATOR_STATUS_REPORT)) {
                IMessageDataObject data = (IMessageDataObject) request.getData();
                data.put("remoteaddr", req.getRemoteAddr());
                data.put("remotehost", req.getRemoteHost());
                data.put("remoteuser", req.getRemoteUser());
            }

            ServiceRegistry.dispatch(request, responses);
        }

        if (responses.isEmpty()) {
            // no response messages, just return accepted header
            resp.setHeader("Content-Length", "0");
            resp.setContentType("text/plain;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }

        // setup the response
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setHeader("Connection", "Keep-Alive");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-control", "no-cache, no-store, private, must-revalidate");
        resp.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");

        // encode the responses
        ServletOutputStream output = resp.getOutputStream();
        ByteArrayOutputStream bout = new ByteArrayOutputStream(1000);
        String responseType = ServiceMarshaller.getMarshaller(type).encode(responses, req.getSession().getId(),
                bout);
        byte buf[] = bout.toByteArray();
        ByteArrayInputStream bin = new ByteArrayInputStream(buf);

        resp.setContentType(responseType);

        // do gzip encoding if browser supports it and if length > 1000 bytes
        String ae = req.getHeader("accept-encoding");
        if (ae != null && ae.indexOf("gzip") != -1 && buf.length > 1000) {
            resp.setHeader("Content-Encoding", "gzip");
            //a Vary: Accept-Encoding HTTP response header to alert proxies that a cached response should be sent only to 
            //clients that send the appropriate Accept-Encoding request header. This prevents compressed content from being sent 
            //to a client that will not understand it.
            resp.addHeader("Vary", "Accept-Encoding");
            GZIPOutputStream gzip = new GZIPOutputStream(output, buf.length);
            Util.copy(bin, gzip);
            gzip.flush();
            gzip.finish();
        } else {
            resp.setContentLength(buf.length);
            Util.copy(bin, output);
        }
        output.flush();
    } catch (Throwable e) {
        LOG.error("Error handling incoming POST request", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.salesmanBuddy.Controllers.SalesmanBuddy.java

@Path("users/{googleUserId}")
@POST//from ww  w .jav  a 2 s .c  o m
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) // TODO this may need a body object
public Response updateUserToType(@Context HttpServletRequest request,
        @DefaultValue("") @PathParam("googleUserId") String googleUserId,
        @DefaultValue("0") @QueryParam("type") int type,
        @DefaultValue("") @QueryParam("dealershipcode") String dealershipCode) {

    if (dealershipCode.length() != 0) {
        if (googleUserId.length() == 0)// assume that they are changing themselves
            googleUserId = request.getUserPrincipal().getName();

        Users user = null;
        if (type > 0)
            user = this.dao.updateUserToDealershipCodeType(googleUserId, dealershipCode, type);
        else
            user = this.dao.updateUserToDealershipCode(googleUserId, dealershipCode);
        return Response.ok(user).build();
    } else if (type > 0) {
        if (googleUserId.length() == 0)// assume that they are changing themselves, I dont do this anywhere right now
            googleUserId = request.getUserPrincipal().getName();

        int yourType = this.dao.getUserByGoogleId(request.getUserPrincipal().getName()).getType();
        if (type > yourType)
            return Response.status(401).entity(new ErrorMessage("You cannot set a type higher than your own"))
                    .build();
        return Response.ok(this.dao.updateUserToType(googleUserId, type)).build();
    }
    return Response.status(400).entity(new ErrorMessage(
            "You are missing required query params, type: " + type + ", dealershipCode: " + dealershipCode))
            .build();
}

From source file:au.edu.uq.cmm.paul.servlet.WebUIController.java

@RequestMapping(value = "/facilityLogin")
public String facilityLogin(@RequestParam String facilityName,
        @RequestParam(required = false) String startSession,
        @RequestParam(required = false) String endOldSession, @RequestParam(required = false) String userName,
        @RequestParam(required = false) String account, Model model, HttpServletResponse response,
        HttpServletRequest request) throws IOException {
    FacilityStatusManager fsm = getFacilityStatusManager();
    facilityName = tidy(facilityName);/* w ww .  jav a2 s .  c o  m*/
    model.addAttribute("facilityName", facilityName);
    model.addAttribute("facilities", getFacilities());
    model.addAttribute("returnTo", inferReturnTo(request));

    userName = tidy(userName);
    String password = tidy(request.getParameter("password"));
    if (startSession == null) {
        GenericPrincipal principal = (GenericPrincipal) request.getUserPrincipal();
        if (principal != null && principal.hasRole("ROLE_ACLS_USER") && principal.getPassword() != null
                && !principal.getPassword().isEmpty()) {
            userName = principal.getName();
            password = principal.getPassword();
        }
    }
    model.addAttribute("userName", userName);
    model.addAttribute("password", password);
    if (userName.isEmpty() || password.isEmpty()) {
        // Phase 1 - user must fill in user name and password
        model.addAttribute("message", "Fill in the username and password fields");
        return "facilityLogin";
    }
    try {
        if (account == null) {
            // Phase 2 - validate user credentials and get accounts list
            List<String> accounts = null;
            if (endOldSession != null) {
                LOG.debug("Attempting old session logout");
                fsm.logoutFacility(facilityName);
                LOG.debug("Logout succeeded");
            }
            LOG.debug("Attempting login");
            accounts = fsm.login(facilityName, userName, password);
            LOG.debug("Login succeeded");
            // If there is only one account, select immediately.
            if (accounts != null) {
                if (accounts.size() == 1) {
                    fsm.selectAccount(facilityName, userName, accounts.get(0));
                    LOG.debug("Account selection succeeded");
                    ;
                    return "facilityLoggedIn";
                } else {
                    model.addAttribute("accounts", accounts);
                    model.addAttribute("message", "Select an account to complete the login");
                }
            }
        } else {
            // Phase 3 - after user has selected an account
            fsm.selectAccount(facilityName, userName, account);
            LOG.debug("Account selection succeeded");
            return "facilityLoggedIn";
        }
    } catch (AclsAuthenticationException ex) {
        model.addAttribute("message", "Login failed: " + ex.getMessage());
    } catch (AclsInUseException ex) {
        model.addAttribute("message", "Instrument " + ex.getFacilityName()
                + " is currently logged in under the name of " + ex.getUserName());
        model.addAttribute("inUse", true);
    }
    return "facilityLogin";
}