Example usage for javax.servlet.http Cookie setDomain

List of usage examples for javax.servlet.http Cookie setDomain

Introduction

In this page you can find the example usage for javax.servlet.http Cookie setDomain.

Prototype

public void setDomain(String domain) 

Source Link

Document

Specifies the domain within which this cookie should be presented.

Usage

From source file:com.adito.security.DefaultLogonController.java

private SessionInfo addLogonTicket(HttpServletRequest request, HttpServletResponse response, User user,
        InetAddress address, int sessionType) {
    String logonTicket = TicketGenerator.getInstance().generateUniqueTicket("SLX");
    if (log.isInfoEnabled())
        log.info("Adding logon ticket to session " + request.getSession().getId());
    request.getSession().setAttribute(Constants.LOGON_TICKET, logonTicket);
    request.setAttribute(Constants.LOGON_TICKET, logonTicket);
    String userAgent = request.getHeader("User-Agent");
    SessionInfo info = SessionInfo.nextSession(request.getSession(), logonTicket, user, address, sessionType,
            userAgent);/*from ww  w.  j  a v a 2  s .c  o m*/
    request.getSession().setAttribute(Constants.SESSION_INFO, info);
    try {
        String sessionIdentifier = SystemProperties.get("adito.cookie", "JSESSIONID");
        String sessionId = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equalsIgnoreCase(sessionIdentifier)) {
                sessionId = cookies[i].getValue();
                break;
            }
        }
        if (sessionId != null) {
            logonsBySessionId.put(sessionId, info);
        } else
            log.warn("Could not find session id using identifier " + sessionIdentifier + " in HTTP request");
    } catch (Exception ex) {
        log.warn("Failed to determine HTTP session id", ex);
    }
    logons.put(logonTicket, info);
    /**
     * Set the normal logon ticket without a domain - this works in almost
     * all circumstances
     */
    Cookie cookie = new Cookie(Constants.LOGON_TICKET, logonTicket);
    cookie.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    /**
     * Set a logon ticket for the domain - this is require to make active
     * dns work.
     */
    Cookie cookie2 = new Cookie(Constants.DOMAIN_LOGON_TICKET, logonTicket);
    cookie2.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie2.setPath("/");
    // We now set the domain on the cookie so the new Active DNS feature for
    // Reverse Proxy works correctly
    String host = request.getHeader("Host");
    if (host != null) {
        HostService hostService = new HostService(host);
        cookie2.setDomain(hostService.getHost());
    }
    cookie.setSecure(true);
    response.addCookie(cookie2);
    return info;
}

From source file:com.sslexplorer.security.DefaultLogonController.java

private SessionInfo addLogonTicket(HttpServletRequest request, HttpServletResponse response, User user,
        InetAddress address, int sessionType) {
    String logonTicket = TicketGenerator.getInstance().generateUniqueTicket("SLX");
    if (log.isInfoEnabled())
        log.info("Adding logon ticket to session " + request.getSession().getId());
    request.getSession().setAttribute(Constants.LOGON_TICKET, logonTicket);
    request.setAttribute(Constants.LOGON_TICKET, logonTicket);
    String userAgent = request.getHeader("User-Agent");
    SessionInfo info = SessionInfo.nextSession(request.getSession(), logonTicket, user, address, sessionType,
            userAgent);//from   ww  w .  j  a v  a 2  s  .c om
    request.getSession().setAttribute(Constants.SESSION_INFO, info);
    try {
        String sessionIdentifier = SystemProperties.get("sslexplorer.cookie", "JSESSIONID");
        String sessionId = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equalsIgnoreCase(sessionIdentifier)) {
                sessionId = cookies[i].getValue();
                break;
            }
        }
        if (sessionId != null) {
            logonsBySessionId.put(sessionId, info);
        } else
            log.warn("Could not find session id using identifier " + sessionIdentifier + " in HTTP request");
    } catch (Exception ex) {
        log.warn("Failed to determine HTTP session id", ex);
    }
    logons.put(logonTicket, info);
    /**
     * Set the normal logon ticket without a domain - this works in almost
     * all circumstances
     */
    Cookie cookie = new Cookie(Constants.LOGON_TICKET, logonTicket);
    cookie.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    /**
     * Set a logon ticket for the domain - this is require to make active
     * dns work.
     */
    Cookie cookie2 = new Cookie(Constants.DOMAIN_LOGON_TICKET, logonTicket);
    cookie2.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie2.setPath("/");
    // We now set the domain on the cookie so the new Active DNS feature for
    // Reverse Proxy works correctly
    String host = request.getHeader("Host");
    if (host != null) {
        HostService hostService = new HostService(host);
        cookie2.setDomain(hostService.getHost());
    }
    cookie.setSecure(true);
    response.addCookie(cookie2);
    return info;
}

From source file:com.adito.security.DefaultLogonController.java

public void addCookies(RequestHandlerRequest request, RequestHandlerResponse response, String logonTicket,
        SessionInfo session) {/* w w  w  .j a va2  s  .com*/

    if (request.getAttribute("sslx.logon.cookie") != null)
        return;

    /**
     * Set the normal logon ticket without a domain - this works in almost
     * all circumstances
     */
    Cookie cookie = new Cookie(Constants.LOGON_TICKET, logonTicket);
    cookie.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    /**
     * Set a logon ticket for the domain - this is require to make active
     * dns work.
     */
    Cookie cookie2 = new Cookie(Constants.DOMAIN_LOGON_TICKET, logonTicket);
    cookie2.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie2.setPath("/");
    // We now set the domain on the cookie so the new Active DNS feature for
    // Reverse Proxy works correctly
    String host = request.getField("Host");
    if (host != null) {
        HostService hostService = new HostService(host);
        cookie2.setDomain(hostService.getHost());
    }
    cookie2.setSecure(true);
    response.addCookie(cookie2);

    request.setAttribute("sslx.logon.cookie", new Object());

    /**
     * LDP - This code was not setting the domain on the ticket. I've
     * converted to the new format of having two seperate tickets to ensure
     * tickets are sent across domains
     */
    /*
     * Cookie cookie = new Cookie(Constants.LOGON_TICKET, logonTicket); try {
     * cookie.setMaxAge(Integer.parseInt(CoreServlet.getServlet().getPropertyDatabase().getProperty(0,
     * null, "security.session.maxCookieAge"))); if
     * ("true".equals(CoreServlet.getServlet().getPropertyDatabase().getProperty(0,
     * null, "security.session.lockSessionOnBrowserClose"))) { if
     * (log.isInfoEnabled()) log.info("New session - will force the user to
     * authenticate again"); // initialiseSession(request.getSession(),
     * user); // List profiles = //
     * CoreServlet.getServlet().getPropertyDatabase().getPropertyProfiles(user.getUsername(), //
     * false); // request.getSession().setAttribute(Constants.PROFILES, //
     * profiles);
     * request.getSession().setAttribute(Constants.SESSION_LOCKED, user); } }
     * catch (Exception e) { log.error(e); cookie.setMaxAge(900); }
     * cookie.setPath("/"); cookie.setSecure(true);
     * response.addCookie(cookie);
     */
    //
}

From source file:com.google.gsa.Kerberos.java

/**
 * Setting the authentication cookie and the user session
 * //from   ww w .j  a v  a 2 s .  c om
 * @param username username
 * @param creationTime creation time
 * @param encodedSessionID encoded session id
 * 
 * @return if the setting process was successful
 */
private boolean settingSession(UserSession userSession, Cookie gsaAuthCookie, Credentials creds,
        String username, KerberosAuthenticationProcess krbAuthN, long creationTime, String encodedSessionID,
        Vector<Cookie> krbCookies, Vector<Cookie> nonKrbCookies) {

    boolean result = false;

    logger.debug("Creating auth cookie with value: " + encodedSessionID);

    // Instantiate authentication cookie with default value
    gsaAuthCookie = new Cookie(authCookieName, encodedSessionID);

    // Set cookie domain
    gsaAuthCookie.setDomain(authCookieDomain);

    // Set cookie path
    gsaAuthCookie.setPath(authCookiePath);

    // Set expiration time
    gsaAuthCookie.setMaxAge(authMaxAge);

    logger.debug("Creating Session");

    userSession.setUserName(username);
    userSession.setSessionCreationTime(creationTime);
    userSession.setSessionLastAccessTime(creationTime);
    userSession.setUserCredentials(creds);

    //Cookies
    settingSessionCookies(krbCookies, nonKrbCookies, gsaAuthCookie, userSession);

    if (krbAuthN.getUserSubject() != null) {
        logger.debug("Kerberos Subject exists");

        userSession.setKerberosCredentials(krbAuthN.getUserSubject());

        result = true;

    } else {
        // Log error
        logger.error("Kerberos Subject has not been created properly");

        // Return
        return result;

    }

    return result;
}

From source file:org.sakaiproject.util.RequestFilter.java

/**
 * Filter a request / response./*  w  w  w . j  a  v a 2s  .  c o  m*/
 */
public void doFilter(ServletRequest requestObj, ServletResponse responseObj, FilterChain chain)
        throws IOException, ServletException {
    StringBuffer sb = null;
    long startTime = System.currentTimeMillis();

    // bind some preferences as "current"
    Boolean curRemoteUser = (Boolean) ThreadLocalManager.get(CURRENT_REMOTE_USER);
    Integer curHttpSession = (Integer) ThreadLocalManager.get(CURRENT_HTTP_SESSION);
    String curContext = (String) ThreadLocalManager.get(CURRENT_CONTEXT);
    ServletRequest curRequest = (ServletRequest) ThreadLocalManager.get(CURRENT_HTTP_REQUEST);
    ServletResponse curResponse = (ServletResponse) ThreadLocalManager.get(CURRENT_HTTP_RESPONSE);
    boolean cleared = false;

    // keep track of temp files with this request that need to be deleted on the way out
    List<FileItem> tempFiles = new ArrayList<FileItem>();

    try {
        ThreadLocalManager.set(CURRENT_REMOTE_USER, Boolean.valueOf(m_sakaiRemoteUser));
        ThreadLocalManager.set(CURRENT_HTTP_SESSION, Integer.valueOf(m_sakaiHttpSession));
        ThreadLocalManager.set(CURRENT_CONTEXT, m_contextId);

        // make the servlet context available
        ThreadLocalManager.set(CURRENT_SERVLET_CONTEXT, m_servletContext);

        // we are expecting HTTP stuff
        if (!((requestObj instanceof HttpServletRequest) && (responseObj instanceof HttpServletResponse))) {
            // if not, just pass it through
            chain.doFilter(requestObj, responseObj);
            return;
        }

        HttpServletRequest req = (HttpServletRequest) requestObj;
        HttpServletResponse resp = (HttpServletResponse) responseObj;

        // knl-640
        // The AppDomain should reject:
        // 1) all GET URL's starting with contentPaths
        //
        // The FileDomain should only accept:
        // 1) any URL's in loginPath. We have to accept POST methods here
        //    as well so folks can log in on this node.
        // 2) any GET URL's from contentPaths (POST's any other methods not
        //    allowed.
        if (useContentHostingDomain) {
            String requestURI = req.getRequestURI();
            if (req.getQueryString() != null)
                requestURI += "?" + req.getQueryString();
            if (startsWithAny(requestURI, contentPaths) && "GET".equalsIgnoreCase(req.getMethod())) {
                if (!req.getServerName().equals(chsDomain) && !(startsWithAny(requestURI, contentExceptions))) {
                    resp.sendRedirect(chsUrl + requestURI);
                    return;
                }
            } else {
                if (req.getServerName().equals(chsDomain)
                        && !(startsWithAny(requestURI, contentPaths)
                                && !"GET".equalsIgnoreCase(req.getMethod()))
                        && !(startsWithAny(requestURI, loginPaths))) {
                    resp.sendRedirect(appUrl + requestURI);
                    return;
                }
            }
        }

        // check on file uploads and character encoding BEFORE checking if
        // this request has already been filtered, as the character encoding
        // and file upload handling are configurable at the tool level.
        // so the 2nd invokation of the RequestFilter (at the tool level)
        // may actually cause character encoding and file upload parsing
        // to happen.

        // handle character encoding
        handleCharacterEncoding(req, resp);

        // handle file uploads
        req = handleFileUpload(req, resp, tempFiles);

        // if we have already filtered this request, pass it on
        if (req.getAttribute(ATTR_FILTERED) != null) {
            // set the request and response for access via the thread local
            ThreadLocalManager.set(CURRENT_HTTP_REQUEST, req);
            ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, resp);

            chain.doFilter(req, resp);
        }

        // filter the request
        else {
            if (M_log.isDebugEnabled()) {
                sb = new StringBuffer("http-request: ");
                sb.append(req.getMethod());
                sb.append(" ");
                sb.append(req.getRequestURL());
                if (req.getQueryString() != null) {
                    sb.append("?");
                    sb.append(req.getQueryString());
                }
                M_log.debug(sb);
            }

            try {
                // mark the request as filtered to avoid re-filtering it later in the request processing
                req.setAttribute(ATTR_FILTERED, ATTR_FILTERED);

                // some useful info
                ThreadLocalManager.set(ServerConfigurationService.CURRENT_SERVER_URL, serverUrl(req));

                // make sure we have a session
                Session s = assureSession(req, resp);

                // pre-process request
                req = preProcessRequest(s, req);

                // detect a tool placement and set the current tool session
                detectToolPlacement(s, req);

                // pre-process response
                resp = preProcessResponse(s, req, resp);

                // set the request and response for access via the thread local
                ThreadLocalManager.set(CURRENT_HTTP_REQUEST, req);
                ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, resp);

                // set the portal into thread local
                if (m_contextId != null && m_contextId.length() > 0) {
                    ThreadLocalManager.set(ServerConfigurationService.CURRENT_PORTAL_PATH, "/" + m_contextId);
                }

                // Only synchronize on session for Terracotta. See KNL-218, KNL-75.
                if (TERRACOTTA_CLUSTER) {
                    synchronized (s) {
                        // Pass control on to the next filter or the servlet
                        chain.doFilter(req, resp);

                        // post-process response
                        postProcessResponse(s, req, resp);
                    }
                } else {
                    // Pass control on to the next filter or the servlet
                    chain.doFilter(req, resp);

                    // post-process response
                    postProcessResponse(s, req, resp);
                }

                // Output client cookie if requested to do so
                if (s != null && req.getAttribute(ATTR_SET_COOKIE) != null) {

                    // check for existing cookie
                    String suffix = getCookieSuffix();
                    Cookie c = findCookie(req, cookieName, suffix);

                    // the cookie value we need to use
                    String sessionId = s.getId() + DOT + suffix;

                    // set the cookie if necessary
                    if ((c == null) || (!c.getValue().equals(sessionId))) {
                        c = new Cookie(cookieName, sessionId);
                        c.setPath("/");
                        c.setMaxAge(-1);
                        if (cookieDomain != null) {
                            c.setDomain(cookieDomain);
                        }
                        if (req.isSecure() == true) {
                            c.setSecure(true);
                        }
                        addCookie(resp, c);
                    }
                }

            } catch (ClosingException se) {
                closingRedirect(req, resp);
            } catch (RuntimeException t) {
                M_log.error("", t);
                throw t;
            } catch (IOException ioe) {
                M_log.error("", ioe);
                throw ioe;
            } catch (ServletException se) {
                M_log.error(se.getMessage(), se);
                throw se;
            } finally {
                // clear any bound current values
                ThreadLocalManager.clear();
                cleared = true;
            }
        }

    } finally {
        if (!cleared) {
            // restore the "current" bindings
            ThreadLocalManager.set(CURRENT_REMOTE_USER, curRemoteUser);
            ThreadLocalManager.set(CURRENT_HTTP_SESSION, curHttpSession);
            ThreadLocalManager.set(CURRENT_CONTEXT, curContext);
            ThreadLocalManager.set(CURRENT_HTTP_REQUEST, curRequest);
            ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, curResponse);
        }

        // delete any temp files
        deleteTempFiles(tempFiles);

        if (M_log.isDebugEnabled() && sb != null) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            M_log.debug("request timing (ms): " + elapsedTime + " for " + sb);
        }
    }
}

From source file:de.tu_dortmund.ub.api.paia.core.PaiaCoreEndpoint.java

/**
 *
 * @param httpServletRequest//from   w w w  .j  a  v a 2  s .  co m
 * @param httpServletResponse
 * @throws IOException
 */
private void authorize(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String format, DocumentList documents) throws IOException {

    httpServletResponse.setHeader("Access-Control-Allow-Origin",
            config.getProperty("Access-Control-Allow-Origin"));
    httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control"));

    ObjectMapper mapper = new ObjectMapper();

    // Error handling mit suppress_response_codes=true
    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    }
    // Error handling mit suppress_response_codes=false (=default)
    else {
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }

    // Json fr Response body
    RequestError requestError = new RequestError();
    requestError.setError(
            this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED)));
    requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED);
    requestError.setDescription(this.config
            .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description"));
    requestError.setErrorUri(
            this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri"));

    // XML-Ausgabe mit JAXB
    if (format.equals("xml")) {

        try {

            JAXBContext context = JAXBContext.newInstance(RequestError.class);
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            // Write to HttpResponse
            httpServletResponse.setContentType("application/xml;charset=UTF-8");
            m.marshal(requestError, httpServletResponse.getWriter());

        } catch (JAXBException e) {
            this.logger.error(e.getMessage(), e.getCause());
            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Internal Server Error: Error while rendering the results.");
        }
    }

    // JSON-Ausgabe mit Jackson
    if (format.equals("json")) {

        httpServletResponse.setContentType("application/json;charset=UTF-8");
        mapper.writeValue(httpServletResponse.getWriter(), requestError);
    }

    // html > redirect zu "PAIA auth - login" mit redirect_url = "PAIA core - service"
    if (format.equals("html")) {

        httpServletResponse.setContentType("text/html;charset=UTF-8");

        if (documents != null) {
            // set Cookie with urlencoded DocumentList-JSON
            StringWriter stringWriter = new StringWriter();
            mapper.writeValue(stringWriter, documents);
            Cookie cookie = new Cookie("PaiaServiceDocumentList",
                    URLEncoder.encode(stringWriter.toString(), "UTF-8"));
            if (this.config.getProperty("service.cookie.domain") != null
                    && !this.config.getProperty("service.cookie.domain").equals("")) {
                cookie.setDomain(this.config.getProperty("service.cookie.domain"));
            }
            cookie.setMaxAge(-1);
            cookie.setPath("/");
            httpServletResponse.addCookie(cookie);
        }

        //String redirect_url = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.core") + httpServletRequest.getPathInfo();
        String redirect_url = this.config.getProperty("service.base_url")
                + this.config.getProperty("service.endpoint.core") + httpServletRequest.getPathInfo();
        if (httpServletRequest.getQueryString() != null && !httpServletRequest.getQueryString().equals("")) {
            redirect_url += "?" + httpServletRequest.getQueryString();
        }
        this.logger.info("redirect_url = " + redirect_url);

        //String login_url = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.auth") + "/login?redirect_url=" + redirect_url;
        String login_url = this.config.getProperty("service.base_url")
                + this.config.getProperty("service.endpoint.auth") + "/login?redirect_url=" + redirect_url;
        this.logger.info("login_url = " + login_url);

        httpServletResponse.sendRedirect(login_url);
    }
}

From source file:org.ireland.jnetty.http.HttpServletRequestImpl.java

/**
 * Extracte cookies.//w  ww.  j  a  v  a2 s  .co m
 */
protected void extracteCookie() {
    _cookiesExtracted = true;

    // Decode the cookie.
    String cookieString = headers.get(HttpHeaders.Names.COOKIE);
    if (cookieString != null) {
        Set<io.netty.handler.codec.http.Cookie> _cookies = CookieDecoder.decode(cookieString);

        this.cookies = new Cookie[_cookies.size()];

        int i = 0;

        // Convent netty's Cookie to Servlet's Cookie
        for (io.netty.handler.codec.http.Cookie c : _cookies) {
            Cookie cookie = new Cookie(c.getName(), c.getValue());

            cookie.setComment(c.getComment());

            if (c.getDomain() != null)
                cookie.setDomain(c.getDomain());

            cookie.setHttpOnly(c.isHttpOnly());
            cookie.setMaxAge((int) c.getMaxAge());
            cookie.setPath(c.getPath());
            cookie.setSecure(c.isSecure());
            cookie.setVersion(c.getVersion());

            this.cookies[i] = cookie;
            i++;
        }
    }
}

From source file:de.tu_dortmund.ub.api.paia.auth.PaiaAuthEndpoint.java

/**
 * PAIAauth services: Prfe jeweils die scopes und liefere die Daten
 *///w  w w.j a  v a 2 s.c o m
private void provideService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String service, String access_token, String requestBody, String format, String language,
        String redirect_url) throws IOException {

    ObjectMapper mapper = new ObjectMapper();

    switch (service) {

    case "login": {

        if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) {

            AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class);
            // init Authorization Service
            authorizationInterface.init(this.config);

            // if access_token not equals "" >> delete token + new login
            if (!access_token.equals("")) {

                // AuthorizationInterface.revokeToken()
                try {

                    boolean isRevoked = authorizationInterface.revokeToken(access_token);
                } catch (AuthorizationException e) {

                    // TODO correct error handling
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!");
                }

                // delete cookie
                Cookie cookie = new Cookie("PaiaService", null);
                if (this.config.getProperty("service.cookie.domain") != null
                        && !this.config.getProperty("service.cookie.domain").equals("")) {
                    cookie.setDomain(this.config.getProperty("service.cookie.domain"));
                }
                cookie.setMaxAge(0);
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);

                // cleanup variable
                access_token = "";
            }

            // analyse on request data
            LoginRequest loginRequest = null;
            try {

                loginRequest = mapper.readValue(requestBody, LoginRequest.class);

                if (httpServletRequest.getParameter("redirect_url") != null
                        && !httpServletRequest.getParameter("redirect_url").equals("")) {

                    redirect_url = httpServletRequest.getParameter("redirect_url");
                }
            } catch (Exception e) {

                if (requestBody != null && !requestBody.equals("")) {

                    String[] params = requestBody.split("&");

                    if (params.length > 1) {

                        loginRequest = new LoginRequest();

                        for (String param : params) {

                            if (param.startsWith("grant_type")) {
                                loginRequest.setGrant_type(param.split("=")[1]);
                            } else if (param.startsWith("username")) {
                                loginRequest.setUsername(param.split("=")[1]);
                            } else if (param.startsWith("password")) {
                                loginRequest.setPassword(param.split("=")[1]);
                            } else if (param.startsWith("scope")) {
                                loginRequest.setScope(param.split("=")[1]);
                            } else if (param.startsWith("format")) {
                                format = param.split("=")[1];
                                this.logger.info("format = " + format);
                            } else if (param.startsWith("redirect_url")) {
                                redirect_url = URLDecoder.decode(param.split("=")[1], "UTF-8");
                                this.logger.info("redirect_url = " + redirect_url);
                            } else {
                                // Tu nix
                            }
                        }
                    }
                } else if (httpServletRequest.getParameter("grant_type") != null
                        && !httpServletRequest.getParameter("grant_type").equals("")
                        && httpServletRequest.getParameter("username") != null
                        && !httpServletRequest.getParameter("username").equals("")
                        && httpServletRequest.getParameter("password") != null
                        && !httpServletRequest.getParameter("password").equals("")) {

                    loginRequest = new LoginRequest();
                    loginRequest.setGrant_type(httpServletRequest.getParameter("grant_type"));
                    loginRequest.setUsername(httpServletRequest.getParameter("username"));
                    loginRequest.setPassword(httpServletRequest.getParameter("password"));
                    if (httpServletRequest.getParameter("scope") != null
                            && !httpServletRequest.getParameter("scope").equals("")) {
                        loginRequest.setScope(httpServletRequest.getParameter("scope"));
                    }
                    if (httpServletRequest.getParameter("redirect_url") != null
                            && !httpServletRequest.getParameter("redirect_url").equals("")) {

                        redirect_url = httpServletRequest.getParameter("redirect_url");
                    }
                } else {
                    loginRequest = null;
                }
            }

            // do login
            if (loginRequest != null && loginRequest.getUsername() != null && loginRequest.getPassword() != null
                    && loginRequest.getGrant_type() != null
                    && loginRequest.getGrant_type().equals("password")) {

                String scope = "read_patron read_fees read_items write_items"; // TODO config-properties
                if (loginRequest.getScope() != null && !loginRequest.getScope().equals("")) {

                    scope = loginRequest.getScope();
                }

                // AuthorizationInterface.getToken()
                String responseJson = "";
                try {

                    responseJson = authorizationInterface.getToken(scope, loginRequest.getUsername(),
                            loginRequest.getPassword());
                } catch (AuthorizationException e) {

                    // TODO correct error handling
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!");
                }

                if (!responseJson.equals("")) {

                    LoginResponse loginResponse = mapper.readValue(responseJson, LoginResponse.class);

                    // anpassen des loginResponse
                    loginResponse.setRefresh_token(null);
                    loginResponse.setRefresh_expires_in(null);
                    loginResponse.setPatron(loginRequest.getUsername());

                    httpServletResponse.setHeader("Access-Control-Allow-Origin",
                            this.config.getProperty("Access-Control-Allow-Origin"));
                    httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control"));
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    // add cookie
                    StringWriter stringWriter = new StringWriter();
                    mapper.writeValue(stringWriter, loginResponse);
                    Cookie cookie = new Cookie("PaiaService",
                            URLEncoder.encode(stringWriter.toString(), "UTF-8"));
                    if (this.config.getProperty("service.cookie.domain") != null
                            && !this.config.getProperty("service.cookie.domain").equals("")) {
                        cookie.setDomain(this.config.getProperty("service.cookie.domain"));
                    }
                    cookie.setMaxAge(-1);
                    cookie.setPath("/");
                    httpServletResponse.addCookie(cookie);

                    // extent redirect_url
                    this.logger.info("redirect_url: " + redirect_url);
                    if (redirect_url.startsWith(this.config.getProperty("service.base_url") + "/core")) {

                        if (redirect_url.endsWith("core/")) {
                            redirect_url += loginResponse.getPatron();
                        } else if (redirect_url.endsWith("core")) {
                            redirect_url += "/" + loginResponse.getPatron();
                        } else if (redirect_url.contains("/patronid/")) {

                            redirect_url = redirect_url.replaceAll("/patronid/",
                                    "/" + loginResponse.getPatron() + "/");
                        } else {
                            // nix
                        }
                    }
                    this.logger.info("redirect_url: " + redirect_url);

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(LoginResponse.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(loginResponse, httpServletResponse.getWriter());
                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), loginResponse);
                    }

                    // html >> redirect
                    if (format.equals("html")) {

                        // if QueryString contains redirect_url and value of it contains /paia/core/ >> expand URL with username
                        if (redirect_url.contains("/paia/core/")) {

                            // TODO redirect_url += loginResponse.getPatron();
                        }
                        this.logger.info("redirect_url = " + redirect_url);

                        httpServletResponse.sendRedirect(redirect_url);
                    }
                } else {

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config
                            .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2"));
                    requestError.setCode(HttpServletResponse.SC_FORBIDDEN);
                    requestError.setDescription(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.uri"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }
            }
            // else Baue HTML-Seite mit login-Formular mittels XSLT
            else {

                httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAIA auth\"");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.setHeader("Access-Control-Allow-Origin",
                        config.getProperty("Access-Control-Allow-Origin"));
                httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control"));

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                }

                // Json fr Response body
                RequestError requestError = new RequestError();
                requestError.setError(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2"));
                requestError.setCode(HttpServletResponse.SC_FORBIDDEN);
                requestError.setDescription(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.description"));
                requestError.setErrorUri(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.uri"));

                if (format.equals("html")) {

                    if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) {

                        try {
                            ObjectToHtmlTransformation htmlTransformation = Lookup
                                    .lookup(ObjectToHtmlTransformation.class);
                            // init transformator
                            htmlTransformation.init(this.config);

                            HashMap<String, String> parameters = new HashMap<String, String>();
                            parameters.put("lang", language);
                            parameters.put("redirect_url", redirect_url);

                            //String provider = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.auth") + "/" + service;
                            String provider = this.config.getProperty("service.base_url")
                                    + this.config.getProperty("service.endpoint.auth") + "/" + service;
                            parameters.put("formURL", provider);

                            httpServletResponse.setContentType("text/html;charset=UTF-8");
                            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                            httpServletResponse.getWriter()
                                    .println(htmlTransformation.transform(new Document(), parameters));
                        } catch (TransformationException e) {
                            e.printStackTrace();
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering a HTML message.");
                        }
                    } else {
                        this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                        format = "json";
                    }
                }

                // XML-Ausgabe mit JAXB
                if (format.equals("xml")) {

                    try {

                        JAXBContext context = JAXBContext.newInstance(RequestError.class);
                        Marshaller m = context.createMarshaller();
                        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                        // Write to HttpResponse
                        httpServletResponse.setContentType("application/xml;charset=UTF-8");
                        m.marshal(requestError, httpServletResponse.getWriter());
                    } catch (JAXBException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    }
                }

                // JSON-Ausgabe mit Jackson
                if (format.equals("json")) {

                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    mapper.writeValue(httpServletResponse.getWriter(), requestError);
                }
            }
        } else {

            this.logger.error(HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": Config Error!");

            // Error handling mit suppress_response_codes=true
            if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            }
            // Error handling mit suppress_response_codes=false (=default)
            else {
                httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            }

            // Json fr Response body
            RequestError requestError = new RequestError();
            requestError.setError(this.config
                    .getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
            requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            requestError.setDescription(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
            requestError.setErrorUri(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

            this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
        }

        break;
    }
    case "logout": {

        if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) {

            AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class);
            // init Authorization Service
            authorizationInterface.init(this.config);

            if (!access_token.equals("")) {

                // AuthorizationInterface.revokeToken()
                try {

                    boolean isRevoked = authorizationInterface.revokeToken(access_token);
                } catch (AuthorizationException e) {

                    // TODO correct error handling
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!");
                }
            }

            httpServletResponse.setHeader("Access-Control-Allow-Origin",
                    config.getProperty("Access-Control-Allow-Origin"));
            httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control"));
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);

            // delete cookie
            Cookie cookie = new Cookie("PaiaService", null);
            if (this.config.getProperty("service.cookie.domain") != null
                    && !this.config.getProperty("service.cookie.domain").equals("")) {
                cookie.setDomain(this.config.getProperty("service.cookie.domain"));
            }
            cookie.setMaxAge(0);
            cookie.setPath("/");
            httpServletResponse.addCookie(cookie);

            // html >> redirect
            if (format.equals("html")) {

                if (httpServletRequest.getParameter("redirect_url") != null
                        && !httpServletRequest.getParameter("redirect_url").equals("")) {

                    redirect_url = httpServletRequest.getParameter("redirect_url");
                } else {

                    redirect_url = this.config.getProperty("service.auth.logout.redirect.default");
                }

                httpServletResponse.sendRedirect(redirect_url);
            }

            if (format.equals("json")) {
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                httpServletResponse.getWriter().println("{\"logged out\":\"true\"}");
            }

            if (format.equals("xml")) {
                httpServletResponse.setContentType("application/xml;charset=UTF-8");
                httpServletResponse.getWriter().println(
                        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><logout status=\"true\" />");
            }

        } else {

            this.logger.error(HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": Config Error!");

            // Error handling mit suppress_response_codes=true
            if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            }
            // Error handling mit suppress_response_codes=false (=default)
            else {
                httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            }

            // Json fr Response body
            RequestError requestError = new RequestError();
            requestError.setError(this.config
                    .getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
            requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            requestError.setDescription(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
            requestError.setErrorUri(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

            this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
        }

        break;
    }
    case "change": {

        // build ChangeRequest object
        ChangeRequest changeRequest = mapper.readValue(requestBody, ChangeRequest.class);

        // check token ...
        boolean isAuthorized = false;

        if (access_token != null && !access_token.equals("")) {

            if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) {

                AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class);
                // init Authorization Service
                authorizationInterface.init(this.config);

                try {

                    isAuthorized = authorizationInterface.isTokenValid(httpServletResponse, service,
                            changeRequest.getPatron(), access_token);
                } catch (AuthorizationException e) {

                    // TODO correct error handling
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!");
                }
            } else {

                // TODO correct error handling
                this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": "
                        + "Authorization Interface not implemented!");
            }
        }

        this.logger.debug("Authorization: " + access_token + " - " + isAuthorized);

        if (!isAuthorized) {

            // Authorization
            this.authorize(httpServletRequest, httpServletResponse, format);
        } else {

            if (Lookup.lookupAll(LibraryManagementSystem.class).size() > 0) {

                LibraryManagementSystem libraryManagementSystem = Lookup.lookup(LibraryManagementSystem.class);
                // init ILS
                libraryManagementSystem.init(this.config);

                // exists patron?
                // use LibraryManagementSystem.patron(): failed = Exception!
                try {

                    Patron patron = libraryManagementSystem.patron(changeRequest.getPatron(), false);

                    boolean isChanged = libraryManagementSystem.changePassword(changeRequest);

                    if (isChanged) {

                        // E-Mail to user
                        Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));

                        try {

                            if (this.config.getProperty("isTestMode") != null
                                    && !Boolean.parseBoolean(this.config.getProperty("isTestMode"))) {
                                mailer.postMail(patron.getEmail(),
                                        this.config.getProperty("service.mailer.change.subject"),
                                        this.config.getProperty("service.mailer.change.message"));
                            } else {
                                mailer.postMail(this.config.getProperty("service.mailer.change.subject"),
                                        this.config.getProperty("service.mailer.change.message"));
                            }

                        } catch (MessagingException e1) {

                            this.logger.error(e1.getMessage(), e1.getCause());
                        }

                        this.logger.info("Password changed. Mail send to '" + patron.getEmail() + "'.");

                        // 200 OK
                        if (format.equals("html")) {

                            format = "json"; // TODO or what else?
                        }

                        Patron responsePatron = new Patron();
                        responsePatron.setUsername(patron.getUsername());
                        responsePatron.setStatus(patron.getStatus());
                        responsePatron.setEmail(new InternetAddress(patron.getEmail()));

                        if (format.equals("json")) {

                            httpServletResponse.setContentType("application/json;charset=UTF-8");
                            mapper.writeValue(httpServletResponse.getWriter(), responsePatron);
                        }

                        if (format.equals("xml")) {

                            JAXBContext context = JAXBContext.newInstance(Patron.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(responsePatron, httpServletResponse.getWriter());
                        }
                    } else {

                        // 401 UNAUTHORIZED
                        this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": Wrong old password!");

                        // Error handling mit suppress_response_codes=true
                        if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        }
                        // Error handling mit suppress_response_codes=false (=default)
                        else {
                            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        }

                        // Json fr Response body
                        RequestError requestError = new RequestError();
                        requestError.setError(this.config
                                .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED)));
                        requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED);
                        requestError.setDescription(this.config.getProperty("error."
                                + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description"));
                        requestError.setErrorUri(this.config.getProperty(
                                "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri"));

                        this.sendRequestError(httpServletResponse, requestError, format, language,
                                redirect_url);
                    }
                } catch (LibraryManagementSystemException e) {

                    // 401 UNAUTHORIZED
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": " + e.getMessage());

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config
                            .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED)));
                    requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED);
                    requestError.setDescription(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                } catch (Exception e) {

                    this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
                    requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description"));
                    requestError.setErrorUri(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }
            } else {

                this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }

                // Json fr Response body
                RequestError requestError = new RequestError();
                requestError.setError(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
                requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                requestError.setDescription(this.config.getProperty("error."
                        + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description"));
                requestError.setErrorUri(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri"));

                this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
            }
        }

        break;
    }
    case "renew": {

        if (Lookup.lookupAll(LibraryManagementSystem.class).size() > 0) {

            LibraryManagementSystem libraryManagementSystem = Lookup.lookup(LibraryManagementSystem.class);
            // init ILS
            libraryManagementSystem.init(this.config);

            // exists patron?
            // use LibraryManagementSystem.patron(): failed = Exception!
            try {

                // build NewPasswordRequest object
                NewPasswordRequest newPasswordRequest = mapper.readValue(requestBody, NewPasswordRequest.class);

                Patron patron = libraryManagementSystem.patron(newPasswordRequest.getPatron(), true);

                if (patron.getEmail() != null && !patron.getEmail().equals("")) {

                    boolean isRenewed = libraryManagementSystem.renewPassword(newPasswordRequest, patron);

                    if (isRenewed) {

                        // E-Mail to user
                        Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));

                        try {

                            if (this.config.getProperty("isTestMode") != null
                                    && !Boolean.parseBoolean(this.config.getProperty("isTestMode"))) {
                                mailer.postMail(patron.getEmail(),
                                        this.config.getProperty("service.mailer.renew.subject"),
                                        this.config.getProperty("service.mailer.renew.message"));
                            } else {
                                mailer.postMail(this.config.getProperty("service.mailer.renew.subject"),
                                        this.config.getProperty("service.mailer.renew.message"));
                            }

                        } catch (MessagingException e1) {

                            this.logger.error(e1.getMessage(), e1.getCause());
                        }

                        this.logger.info("Password resetted. Mail send to '" + patron.getEmail() + "'.");

                        // 200 OK
                        if (format.equals("html")) {

                            format = "json"; // TODO or what else?
                        }

                        Patron responsePatron = new Patron();
                        responsePatron.setUsername(patron.getUsername());
                        responsePatron.setStatus(patron.getStatus());
                        responsePatron.setEmail(new InternetAddress(patron.getEmail()));

                        if (format.equals("json")) {

                            httpServletResponse.setContentType("application/json;charset=UTF-8");
                            mapper.writeValue(httpServletResponse.getWriter(), responsePatron);
                        }

                        if (format.equals("xml")) {

                            JAXBContext context = JAXBContext.newInstance(Patron.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(responsePatron, httpServletResponse.getWriter());
                        }
                    } else {

                        // 401 SC_UNAUTHORIZED
                        this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": Wrong usergroup!");

                        // Error handling mit suppress_response_codes=true
                        if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        }
                        // Error handling mit suppress_response_codes=false (=default)
                        else {
                            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        }

                        // Json fr Response body
                        RequestError requestError = new RequestError();
                        requestError.setError(this.config
                                .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED)));
                        requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED);
                        requestError.setDescription(this.config.getProperty("error."
                                + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description"));
                        requestError.setErrorUri(this.config.getProperty(
                                "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri"));

                        this.sendRequestError(httpServletResponse, requestError, format, language,
                                redirect_url);
                    }
                } else {

                    // 401 SC_UNAUTHORIZED
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": No E-Mail-Address exists!");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config
                            .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED)));
                    requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED);
                    requestError.setDescription(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }
            } catch (LibraryManagementSystemException e) {

                e.printStackTrace();

                // 400 SC_BAD_REQUEST
                this.logger.error(HttpServletResponse.SC_BAD_REQUEST + ": " + e.getMessage());

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                }

                // Json fr Response body
                RequestError requestError = new RequestError();
                requestError.setError(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST)));
                requestError.setCode(HttpServletResponse.SC_BAD_REQUEST);
                requestError.setDescription(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description"));
                requestError.setErrorUri(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri"));

                this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
            } catch (Exception e) {

                this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }

                // Json fr Response body
                RequestError requestError = new RequestError();
                requestError.setError(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
                requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                requestError.setDescription(this.config.getProperty("error."
                        + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description"));
                requestError.setErrorUri(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri"));

                this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
            }
        } else {

            this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

            // Error handling mit suppress_response_codes=true
            if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            }
            // Error handling mit suppress_response_codes=false (=default)
            else {
                httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }

            // Json fr Response body
            RequestError requestError = new RequestError();
            requestError.setError(this.config
                    .getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
            requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            requestError.setDescription(this.config.getProperty("error."
                    + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description"));
            requestError.setErrorUri(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri"));

            this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
        }

        break;
    }
    default: {

        this.logger.error(HttpServletResponse.SC_BAD_REQUEST + "Unknown function! (" + service + ")");

        // Error handling mit suppress_response_codes=true
        if (httpServletRequest.getParameter("suppress_response_codes") != null
                && !httpServletRequest.getParameter("suppress_response_codes").equals("")) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        }
        // Error handling mit suppress_response_codes=false (=default)
        else {
            httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

        // Json fr Response body
        RequestError requestError = new RequestError();
        requestError.setError(
                this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST)));
        requestError.setCode(HttpServletResponse.SC_BAD_REQUEST);
        requestError.setDescription(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description"));
        requestError.setErrorUri(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri"));

        this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
    }
    }
}

From source file:org.hoteia.qalingo.core.web.util.impl.RequestUtilImpl.java

@Override
public void addOrUpdateRecentProductToCookie(final Long productId, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    Cookie info = null;
    Cookie[] cookies = request.getCookies();
    Boolean found = false;/* w  w  w.  j a  v  a2  s.c  om*/
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            info = cookies[i];
            if (Constants.COOKIE_RECENT_PRODUCT_COOKIE_NAME.equals(info.getName())) {
                found = true;
                break;
            }
        }
    }
    if (found) {
        Boolean flag = false;
        String[] splits = info.getValue().split(" ");
        for (String value : splits) {
            if (value.equals(Long.toString(productId))) {
                flag = true;
            }
        }
        if (!flag) {
            String values = info.getValue();
            values += " " + Long.toString(productId);
            info.setValue(values);
            info.setPath("/");
            info.setMaxAge(Constants.COOKIES_LENGTH);
            info.setDomain(request.getServerName());
            response.addCookie(info);
        }
    } else {
        info = new Cookie(Constants.COOKIE_RECENT_PRODUCT_COOKIE_NAME, Long.toString(productId));
        info.setMaxAge(Constants.COOKIES_LENGTH);
        info.setPath("/");
        info.setDomain(request.getServerName());
        response.addCookie(info);
    }
}