Example usage for javax.servlet.http HttpServletResponse SC_FORBIDDEN

List of usage examples for javax.servlet.http HttpServletResponse SC_FORBIDDEN

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_FORBIDDEN.

Prototype

int SC_FORBIDDEN

To view the source code for javax.servlet.http HttpServletResponse SC_FORBIDDEN.

Click Source Link

Document

Status code (403) indicating the server understood the request but refused to fulfill it.

Usage

From source file:contestWebsite.AdminPanel.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets");
    ve.init();//w  w  w  . jav a2  s  .com
    VelocityContext context = new VelocityContext();
    Pair<Entity, UserCookie> infoAndCookie = init(context, req);

    UserCookie userCookie = infoAndCookie.y;
    boolean loggedIn = (boolean) context.get("loggedIn");

    String updated = req.getParameter("updated");
    if (updated != null && updated.equals("1") && !loggedIn) {
        resp.sendRedirect("/adminPanel?updated=1");
    }
    context.put("updated", req.getParameter("updated"));

    if (loggedIn && userCookie.isAdmin()) {
        Entity contestInfo = infoAndCookie.x;
        context.put("contestInfo", contestInfo);

        String confPassError = req.getParameter("confPassError");
        context.put("confPassError",
                confPassError != null && confPassError.equals("1") ? "Those passwords didn't match, try again."
                        : null);
        String passError = req.getParameter("passError");
        context.put("passError",
                passError != null && passError.equals("1") ? "That password is incorrect, try again." : null);

        context.put("middleSubjects", Test.getTests(Level.MIDDLE));
        context.put("Level", Level.class);
        context.put("subjects", Subject.values());

        String[] defaultEmails = { "forgotPass", "question", "registration" };
        for (String defaultEmail : defaultEmails) {
            String email;
            if (contestInfo.hasProperty(defaultEmail + "Email")) {
                email = ((Text) contestInfo.getProperty(defaultEmail + "Email")).getValue();
            } else {
                InputStream emailStream = getServletContext()
                        .getResourceAsStream("/html/email/" + defaultEmail + ".html");
                email = CharStreams.toString(new InputStreamReader(emailStream, Charsets.UTF_8));
                emailStream.close();
            }
            context.put(defaultEmail + "Email", email);
        }

        try {
            context.put("awardCriteria", Retrieve.awardCriteria(contestInfo));
            context.put("qualifyingCriteria", Retrieve.qualifyingCriteria(contestInfo));
            context.put("clientId", contestInfo.getProperty("OAuth2ClientId"));
        } catch (Exception e) {
            System.err.println("Surpressing exception while loading admin panel");
            e.printStackTrace();
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+6"));

        try {
            Date endDate = dateFormat.parse((String) contestInfo.getProperty("editEndDate"));
            Date startDate = dateFormat.parse((String) contestInfo.getProperty("editStartDate"));
            if (new Date().after(endDate) || new Date().before(startDate)) {
                context.put("regEditClosed", true);
            }
        } catch (Exception e) {
            context.put("regEditClosed", true);
        }

        try {
            Date endDate = dateFormat.parse((String) contestInfo.getProperty("endDate"));
            Date startDate = dateFormat.parse((String) contestInfo.getProperty("startDate"));
            if (new Date().after(endDate) || new Date().before(startDate)) {
                context.put("regClosed", true);
            }
        } catch (Exception e) {
            context.put("regClosed", true);
        }

        MemcacheService memCache = MemcacheServiceFactory.getMemcacheService();
        memCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(java.util.logging.Level.INFO));
        byte[] tabulationTaskStatusBytes = (byte[]) memCache.get("tabulationTaskStatus");
        if (tabulationTaskStatusBytes != null) {
            String[] tabulationTaskStatus = new String(tabulationTaskStatusBytes).split("_");
            context.put("tabulationTaskStatus", tabulationTaskStatus[0]);
            List<String> tabulationTaskStatusTime = new ArrayList<String>();
            long timeAgo = new Date().getTime() - new Date(Long.parseLong(tabulationTaskStatus[1])).getTime();
            List<Pair<TimeUnit, String>> timeUnits = new ArrayList<Pair<TimeUnit, String>>() {
                {
                    add(new Pair<TimeUnit, String>(TimeUnit.DAYS, "day"));
                    add(new Pair<TimeUnit, String>(TimeUnit.HOURS, "hour"));
                    add(new Pair<TimeUnit, String>(TimeUnit.MINUTES, "minute"));
                    add(new Pair<TimeUnit, String>(TimeUnit.SECONDS, "second"));
                }
            };
            for (Pair<TimeUnit, String> entry : timeUnits) {
                if (entry.getX().convert(timeAgo, TimeUnit.MILLISECONDS) > 0) {
                    long numUnit = entry.getX().convert(timeAgo, TimeUnit.MILLISECONDS);
                    tabulationTaskStatusTime.add(numUnit + " " + entry.getY() + (numUnit == 1 ? "" : "s"));
                    timeAgo -= TimeUnit.MILLISECONDS.convert(numUnit, entry.getX());
                }
            }
            if (tabulationTaskStatusTime.size() >= 1) {
                context.put("tabulationTaskStatusTime", StringUtils.join(tabulationTaskStatusTime, ", "));
            } else {
                context.put("tabulationTaskStatusTime", timeAgo + " milliseconds");
            }
        }

        close(context, ve.getTemplate("adminPanel.html"), resp);
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Contest Administrator privileges required for that operation");
    }
}

From source file:org.apache.shindig.social.core.oauth2.OAuth2NormalizedRequest.java

private void normalizeBody(String body) throws OAuth2Exception {
    if (body == null || body.length() == 0) {
        return;/*from   w ww .j  a v  a 2 s .c o  m*/
    }
    List<NameValuePair> params;
    try {
        params = URLEncodedUtils.parse(new URI("http://localhost:8080?" + body), "UTF-8");
        for (NameValuePair param : params) {
            put(param.getName(), param.getValue());
        }
    } catch (URISyntaxException e) {
        OAuth2NormalizedResponse response = new OAuth2NormalizedResponse();
        response.setError(ErrorType.INVALID_REQUEST.toString());
        response.setErrorDescription("The message body's syntax is incorrect");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        throw new OAuth2Exception(response);
    }
}

From source file:jipdbs.web.processors.PlayerPenaltyProcessor.java

/**
 * //from   www.j  a  va2  s  .c om
 * @param req
 * @param penalty
 * @param type
 * @param reason
 * @param duration
 * @param durationType
 * @param redirect
 * @param player
 * @param server
 * @param currentPlayer
 * @return
 * @throws HttpError
 */
private String createPenalty(HttpServletRequest req, Penalty penalty, String type, String reason,
        String duration, String durationType, String redirect, Player player, Server server,
        Player currentPlayer) throws HttpError {

    penalty.setReason(reason);
    penalty.setPlayer(player.getKey());

    if (currentPlayer != null)
        penalty.setAdmin(currentPlayer.getKey());

    if (type.equals("notice")) {
        if (!UserServiceFactory.getUserService().hasPermission(server.getKey(),
                server.getPermission(RemotePermissions.ADD_NOTICE))) {
            Flash.error(req, MessageResource.getMessage("forbidden"));
            throw new HttpError(HttpServletResponse.SC_FORBIDDEN);
        }
        penalty.setType(Penalty.NOTICE);
        if ((server.getRemotePermission() & RemotePermissions.ADD_NOTICE) == RemotePermissions.ADD_NOTICE) {
            penalty.setSynced(false);
            penalty.setActive(false);
            Flash.info(req, MessageResource.getMessage("local_action_pending"));
        } else {
            penalty.setSynced(true);
            penalty.setActive(true);
            Flash.warn(req, MessageResource.getMessage("local_action_only"));
        }
    } else {
        if (!UserServiceFactory.getUserService().hasPermission(server.getKey(),
                server.getPermission(RemotePermissions.ADD_BAN))) {
            Flash.error(req, MessageResource.getMessage("forbidden"));
            throw new HttpError(HttpServletResponse.SC_FORBIDDEN);
        }
        Long dm = Functions.time2minutes(duration + durationType);
        if (dm > server.getBanPermission(currentPlayer.getLevel())) {
            Flash.warn(req, MessageResource.getMessage("duration_fixed"));
            dm = server.getBanPermission(currentPlayer.getLevel());
        }
        if (dm.equals(0)) {
            Flash.error(req, MessageResource.getMessage("duration_field_required"));
            return redirect;
        }
        if ((server.getRemotePermission() & RemotePermissions.ADD_BAN) == RemotePermissions.ADD_BAN) {
            penalty.setSynced(false);
            penalty.setActive(false);
            Flash.info(req, MessageResource.getMessage("local_action_pending"));
        } else {
            Flash.error(req, MessageResource.getMessage("remote_action_not_available"));
            return redirect;
        }
        penalty.setType(Penalty.BAN);
        penalty.setDuration(dm);
    }
    return null;
}

From source file:com.sammyun.controller.console.CommonController.java

/**
 * ??//from  w w w . j av a2s . c om
 */
@RequestMapping("/unauthorized")
public String unauthorized(HttpServletRequest request, HttpServletResponse response) {
    String requestType = request.getHeader("X-Requested-With");
    if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
        response.addHeader("loginStatus", "unauthorized");
        try {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    return "/console/common/unauthorized";
}

From source file:com.ecyrd.jspwiki.attachment.AttachmentServlet.java

/**
 *  Serves a GET with two parameters: 'wikiname' specifying the wikiname
 *  of the attachment, 'version' specifying the version indicator.
 *  //w ww .j  av a 2 s .c  o  m
 *  {@inheritDoc}
 */

// FIXME: Messages would need to be localized somehow.
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    WikiContext context = m_engine.createContext(req, WikiContext.ATTACH);

    String version = req.getParameter(HDR_VERSION);
    String nextPage = req.getParameter("nextpage");

    String msg = "An error occurred. Ouch.";
    int ver = WikiProvider.LATEST_VERSION;

    AttachmentManager mgr = m_engine.getAttachmentManager();
    AuthorizationManager authmgr = m_engine.getAuthorizationManager();

    String page = context.getPage().getName();

    if (page == null) {
        log.info("Invalid attachment name.");
        res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    OutputStream out = null;
    InputStream in = null;

    try {
        log.debug("Attempting to download att " + page + ", version " + version);
        if (version != null) {
            ver = Integer.parseInt(version);
        }

        Attachment att = mgr.getAttachmentInfo(page, ver);

        if (att != null) {
            //
            //  Check if the user has permission for this attachment
            //

            Permission permission = PermissionFactory.getPagePermission(att, "view");
            if (!authmgr.checkPermission(context.getWikiSession(), permission)) {
                log.debug("User does not have permission for this");
                res.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }

            //
            //  Check if the client already has a version of this attachment.
            //
            if (HttpUtil.checkFor304(req, att)) {
                log.debug("Client has latest version already, sending 304...");
                res.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }

            String mimetype = getMimeType(context, att.getFileName());

            res.setContentType(mimetype);

            //
            //  We use 'inline' instead of 'attachment' so that user agents
            //  can try to automatically open the file.
            //

            res.addHeader("Content-Disposition", "inline; filename=\"" + att.getFileName() + "\";");

            res.addDateHeader("Last-Modified", att.getLastModified().getTime());

            if (!att.isCacheable()) {
                res.addHeader("Pragma", "no-cache");
                res.addHeader("Cache-control", "no-cache");
            }

            // If a size is provided by the provider, report it.
            if (att.getSize() >= 0) {
                // log.info("size:"+att.getSize());
                res.setContentLength((int) att.getSize());
            }

            out = res.getOutputStream();
            in = mgr.getAttachmentStream(context, att);

            int read = 0;
            byte[] buffer = new byte[BUFFER_SIZE];

            while ((read = in.read(buffer)) > -1) {
                out.write(buffer, 0, read);
            }

            if (log.isDebugEnabled()) {
                msg = "Attachment " + att.getFileName() + " sent to " + req.getRemoteUser() + " on "
                        + req.getRemoteAddr();
                log.debug(msg);
            }
            if (nextPage != null)
                res.sendRedirect(nextPage);

            return;
        }

        msg = "Attachment '" + page + "', version " + ver + " does not exist.";

        log.info(msg);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        return;
    } catch (ProviderException pe) {
        msg = "Provider error: " + pe.getMessage();

        log.debug("Provider failed while reading", pe);
        //
        //  This might fail, if the response is already committed.  So in that
        //  case we just log it.
        //
        try {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        } catch (IllegalStateException e) {
        }
        return;
    } catch (NumberFormatException nfe) {
        msg = "Invalid version number (" + version + ")";
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    } catch (SocketException se) {
        //
        //  These are very common in download situations due to aggressive
        //  clients.  No need to try and send an error.
        //
        log.debug("I/O exception during download", se);
        return;
    } catch (IOException ioe) {
        //
        //  Client dropped the connection or something else happened.
        //  We don't know where the error came from, so we'll at least
        //  try to send an error and catch it quietly if it doesn't quite work.
        //
        msg = "Error: " + ioe.getMessage();
        log.debug("I/O exception during download", ioe);

        try {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        } catch (IllegalStateException e) {
        }
        return;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }

        //
        //  Quite often, aggressive clients close the connection when they have
        //  received the last bits.  Therefore, we close the output, but ignore
        //  any exception that might come out of it.
        //

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:eu.dasish.annotation.backend.rest.CachedRepresentationResource.java

/**
 * /*from ww  w  .j  ava 2s  .c  o m*/
 * @param cachedIdentifier the external UUID of a cached representation.
 * @param multiPart a {@link MultiPart} object containing two parts: a {@link CachedRepresentationInfo} object for the cached-representation's metadata, and its blob.
 * @return a message about how many rows in "cached_representation" table have been updated; "1" if updated, and "0" otherwisee.
 * @throws IOException if sending an error fails.
 */
@PUT
@Consumes("multipart/mixed")
@Produces(MediaType.APPLICATION_XML)
@Path("{cachedid: " + BackendConstants.regExpIdentifier + "}/stream")
public String updateCachedBlob(@PathParam("cachedid") String cachedIdentifier, MultiPart multiPart)
        throws IOException {
    Map params = new HashMap();
    BodyPartEntity bpe = (BodyPartEntity) multiPart.getBodyParts().get(0).getEntity();
    params.put("stream", bpe.getInputStream());
    try {
        Integer result = (Integer) (new RequestWrappers(this)).wrapRequestResource(params,
                new UpdateCachedBlob(), Resource.CACHED_REPRESENTATION, Access.WRITE, cachedIdentifier);
        if (result != null) {
            return result + "rows are updated";
        } else {
            return "Nothing is updated. ";
        }
    } catch (NotInDataBaseException e1) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage());
        return e1.getMessage();
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return e2.getMessage();
    }

}

From source file:gov.nih.nci.security.cgmm.authenticators.CaGridFormAuthenticator.java

/**
 * Authenticate the user making this request, based on the specified
 * login configuration.  Return <code>true</code> if any specified
 * constraint has been satisfied, or <code>false</code> if we have
 * created a response challenge already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param config    Login configuration describing how authentication
 *              should be performed//from   ww  w  .ja va2s .  co  m
 *
 * @exception IOException if an input/output error occurs
 */
public boolean authenticate(Request request, Response response, LoginConfig config) throws IOException {

    // References to objects we will need later
    Session session = null;

    // Have we already authenticated someone?
    Principal principal = request.getUserPrincipal();
    String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
    if (principal != null) {
        if (log.isDebugEnabled())
            log.debug("Already authenticated '" + principal.getName() + "'");
        // Associate the session with any existing SSO session
        if (ssoId != null)
            associate(ssoId, request.getSessionInternal(true));
        return (true);
    }

    // Is there an SSO session against which we can try to reauthenticate?
    if (ssoId != null) {
        if (log.isDebugEnabled())
            log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication");
        // Try to reauthenticate using data cached by SSO.  If this fails,
        // either the original SSO logon was of DIGEST or SSL (which
        // we can't reauthenticate ourselves because there is no
        // cached username and password), or the realm denied
        // the user's reauthentication for some reason.
        // In either case we have to prompt the user for a logon */
        if (reauthenticateFromSSO(ssoId, request))
            return true;
    }

    // Have we authenticated this user before but have caching disabled?
    if (!cache) {
        session = request.getSessionInternal(true);
        if (log.isDebugEnabled())
            log.debug("Checking for reauthenticate in session " + session);
        String username = (String) session.getNote(Constants.SESS_USERNAME_NOTE);
        String password = (String) session.getNote(Constants.SESS_PASSWORD_NOTE);
        if ((username != null) && (password != null)) {
            if (log.isDebugEnabled())
                log.debug("Reauthenticating username '" + username + "'");
            principal = context.getRealm().authenticate(username, password);
            if (principal != null) {
                session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
                if (!matchRequest(request)) {
                    register(request, response, principal, Constants.FORM_METHOD, username, password);
                    return (true);
                }
            }
            if (log.isDebugEnabled())
                log.debug("Reauthentication failed, proceed normally");
        }
    }

    // Is this the re-submit of the original request URI after successful
    // authentication?  If so, forward the *original* request instead.
    if (matchRequest(request)) {
        session = request.getSessionInternal(true);
        if (log.isDebugEnabled())
            log.debug("Restore request from session '" + session.getIdInternal() + "'");
        principal = (Principal) session.getNote(Constants.FORM_PRINCIPAL_NOTE);
        register(request, response, principal, Constants.FORM_METHOD,
                (String) session.getNote(Constants.SESS_USERNAME_NOTE),
                (String) session.getNote(Constants.SESS_PASSWORD_NOTE));
        // If we're caching principals we no longer need the username
        // and password in the session, so remove them
        if (cache) {
            session.removeNote(Constants.SESS_USERNAME_NOTE);
            session.removeNote(Constants.SESS_PASSWORD_NOTE);
        }
        if (restoreRequest(request, session)) {
            if (log.isDebugEnabled())
                log.debug("Proceed to restored request");
            return (true);
        } else {
            if (log.isDebugEnabled())
                log.debug("Restore of original request failed");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return (false);
        }
    }

    // Acquire references to objects we will need to evaluate
    MessageBytes uriMB = MessageBytes.newInstance();
    CharChunk uriCC = uriMB.getCharChunk();
    uriCC.setLimit(-1);
    String contextPath = request.getContextPath();
    String requestURI = request.getDecodedRequestURI();
    response.setContext(request.getContext());

    // Is this the action request from the login page?
    boolean loginAction = requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION);

    // No -- Save this request and redirect to the form login page
    if (!loginAction) {
        session = request.getSessionInternal(true);
        if (log.isDebugEnabled())
            log.debug("Save request in session '" + session.getIdInternal() + "'");
        try {
            saveRequest(request, session);
        } catch (IOException ioe) {
            log.debug("Request body too big to save during authentication");
            response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    sm.getString("authenticator.requestBodyTooBig"));
            return (false);
        }

        //Make sure Authentication Source is available.          
        try {
            CGMMManager cgmmManager = new CGMMManagerImpl();
            request.setAttribute("AUTHENTICATION_SOURCE_MAP", cgmmManager.getAuthenticationServiceURLMap());
            if (log.isDebugEnabled())
                log.debug("Successfully retrieved Authentication Source Map from CGMM in session '"
                        + session.getIdInternal() + "'");
        } catch (CGMMConfigurationException e) {
            if (log.isDebugEnabled())
                log.debug("Unable to retrieve Authentication Source Map from CGMM in session '"
                        + session.getIdInternal() + "'");

        }

        forwardToLoginPage(request, response, config);
        return (false);
    }

    // Custom Authenticate for CGMM-caGrid-CSM.

    boolean isPerformDefaultFormAuthentication = false;
    String username = request.getParameter(Constants.FORM_USERNAME);
    String password = request.getParameter(Constants.FORM_PASSWORD);
    String authenticationServiceURL = request.getParameter("authenticationServiceURL");
    if (null == authenticationServiceURL) {
        // AuthenticationServiceURL is not available. 
        // Check if Default Form Authenticator functionality is requested.
        String performDefaultFormAuthentication = request.getParameter("performDefaultFormAuthentication");
        if (null == performDefaultFormAuthentication) {
            isPerformDefaultFormAuthentication = false;
        } else {
            if (performDefaultFormAuthentication.equalsIgnoreCase("YES")) {
                isPerformDefaultFormAuthentication = true;
                if (log.isDebugEnabled())
                    log.debug(
                            "CaGridFormAuthenticator: Default Form Authenticator functionality is requested.");
            }
        }
    } else {
        // Resume caGrid Authentication

    }

    // Authenticate caGrid User
    GlobusCredential gc;

    if (!isPerformDefaultFormAuthentication) {

        try {
            CGMMManager cgmmManager = new CGMMManagerImpl();
            principal = new GenericPrincipal(context.getRealm(), username, password);
            gc = cgmmManager.performGridLogin(username, password, authenticationServiceURL);
            if (log.isDebugEnabled())
                log.debug("CaGridFormAuthenticator: Successfully performed Grid Login ");
        } catch (CGMMConfigurationException e) {
            if (log.isDebugEnabled())
                log.debug("CGMMConfigurationException: " + e.getMessage());
            forwardToErrorPage(request, response, config);
            return (false);
        } catch (CGMMInputException e) {
            if (log.isDebugEnabled())
                log.debug("CGMMInputException: " + e.getMessage());
            forwardToErrorPage(request, response, config);
            return (false);
        } catch (CGMMGridDorianException e) {
            if (log.isDebugEnabled())
                log.debug("CGMMGridDorianException: " + e.getMessage());
            forwardToErrorPage(request, response, config);
            return (false);
        } catch (CGMMGridAuthenticationServiceException e) {
            if (log.isDebugEnabled())
                log.debug("CGMMGridAuthenticationServiceException: " + e.getMessage());
            forwardToErrorPage(request, response, config);
            return (false);
        } catch (CGMMAuthenticationURLException e) {
            if (log.isDebugEnabled())
                log.debug("CGMMAuthenticationURLException: " + e.getMessage());
            forwardToErrorPage(request, response, config);
            return (false);
        }

        if (gc == null) {
            if (log.isDebugEnabled())
                log.debug("Unable to obtain the Grid Credentials. Forwarding to error page.");
            forwardToErrorPage(request, response, config);
            return (false);
        } else {
            // Set the Grid ID as the Username for LoginModule(s).
            username = gc.getIdentity();
        }

    }

    // Yes -- Validate the specified credentials and redirect
    // to the error page if they are not correct
    Realm realm = context.getRealm();

    if (characterEncoding != null) {
        request.setCharacterEncoding(characterEncoding);
    }
    if (log.isDebugEnabled())
        log.debug("Authenticating username '" + username + "'");

    principal = realm.authenticate(username, password);
    if (principal == null) {
        forwardToErrorPage(request, response, config);
        return (false);
    }

    if (log.isDebugEnabled())
        log.debug("Authentication of '" + username + "' was successful");

    if (session == null)
        session = request.getSessionInternal(false);
    if (session == null) {
        if (containerLog.isDebugEnabled())
            containerLog.debug("User took so long to log on the session expired");
        response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT,
                sm.getString("authenticator.sessionExpired"));
        return (false);
    }

    // Save the authenticated Principal in our session
    session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);

    // Save the username and password as well
    session.setNote(Constants.SESS_USERNAME_NOTE, username);
    session.setNote(Constants.SESS_PASSWORD_NOTE, password);

    // Redirect the user to the original request URI (which will cause
    // the original request to be restored)
    requestURI = savedRequestURL(session);
    if (log.isDebugEnabled())
        log.debug("Redirecting to original '" + requestURI + "'");
    if (requestURI == null)
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, sm.getString("authenticator.formlogin"));
    else
        response.sendRedirect(response.encodeRedirectURL(requestURI));
    return (false);

}

From source file:org.dataconservancy.ui.api.ProjectController.java

/**
 * Handles a request of getting all the collections in the project of the
 * given id. Not yet implemented.// w w  w . j  a v  a2s .  com
 * 
 * @param idpart
 * @param mimeType
 * @param modifiedSince
 * @param request
 * @throws IOException
 */
@RequestMapping(value = "/{idpart}/collections", method = { RequestMethod.GET })
public void handleProjectCollectionsGetRequest(@PathVariable String idpart,
        @RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DATE_TIME) Date modifiedSince,
        HttpServletRequest request, HttpServletResponse resp) throws IOException, BizPolicyException {

    Person user = getAuthenticatedUser();
    if (user == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } else {

        String id = util.buildRequestUrl(request);

        //The ID will come back with collections on the end of it since it's part of the request. 
        //It needs to be removed. 
        id = id.substring(0, id.length() - 12);

        Project project = projectService.get(id);

        if (project != null) {
            if (authorizationService.canReadProject(user, project)) {
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("text/xml");
                Set<Collection> collections = projectBizService.getCollectionsForProject(project, user);
                Bop bop = new Bop();
                bop.setCollections(collections);
                objectBuilder.buildBusinessObjectPackage(bop, resp.getOutputStream());
            } else {
                resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        } else {
            try {
                resp.setStatus(HttpStatus.SC_NOT_FOUND);
                resp.getWriter().print("Could not find project with id: " + idpart);
                resp.getWriter().flush();
                resp.getWriter().close();
            } catch (Exception ee) {
                log.debug("Handling exception", ee);
            }
        }
    }
}