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:net.lightbody.bmp.proxy.jetty.http.HttpRequest.java

/**
 * Extract received cookies from a header.
 * /*from w  w  w . j  a v a2 s . c  om*/
 * @return Array of Cookies.
 */
public Cookie[] getCookies() {
    if (_cookies != null && _cookiesExtracted)
        return _cookies;

    try {
        // Handle no cookies
        if (!_header.containsKey(HttpFields.__Cookie)) {
            _cookies = __noCookies;
            _cookiesExtracted = true;
            _lastCookies = null;
            return _cookies;
        }

        // Check if cookie headers match last cookies
        if (_lastCookies != null) {
            int last = 0;
            Enumeration enm = _header.getValues(HttpFields.__Cookie);
            while (enm.hasMoreElements()) {
                String c = (String) enm.nextElement();
                if (last >= _lastCookies.length || !c.equals(_lastCookies[last])) {
                    _lastCookies = null;
                    break;
                }
                last++;
            }
            if (_lastCookies != null) {
                _cookiesExtracted = true;
                return _cookies;
            }
        }

        // Get ready to parse cookies (Expensive!!!)
        Object cookies = null;
        Object lastCookies = null;

        int version = 0;
        Cookie cookie = null;

        // For each cookie header
        Enumeration enm = _header.getValues(HttpFields.__Cookie);
        while (enm.hasMoreElements()) {
            // Save a copy of the unparsed header as cache.
            String hdr = enm.nextElement().toString();
            lastCookies = LazyList.add(lastCookies, hdr);

            // Parse the header
            QuotedStringTokenizer tok = new QuotedStringTokenizer(hdr, ",;", false, false);
            tok.setSingle(false);
            while (tok.hasMoreElements()) {
                String c = (String) tok.nextElement();
                if (c == null)
                    continue;
                c = c.trim();

                try {
                    String n;
                    String v;
                    int e = c.indexOf('=');
                    if (e > 0) {
                        n = c.substring(0, e);
                        v = c.substring(e + 1);
                    } else {
                        n = c;
                        v = "";
                    }

                    // Handle quoted values
                    if (version > 0)
                        v = StringUtil.unquote(v);

                    // Ignore $ names
                    if (n.startsWith("$")) {
                        if ("$version".equalsIgnoreCase(n))
                            version = Integer.parseInt(QuotedStringTokenizer.unquoteDouble(v));
                        else if ("$path".equalsIgnoreCase(n) && cookie != null)
                            cookie.setPath(v);
                        else if ("$domain".equalsIgnoreCase(n) && cookie != null)
                            cookie.setDomain(v);
                        continue;
                    }

                    v = URI.decodePath(v);
                    cookie = new Cookie(n, v);
                    if (version > 0)
                        cookie.setVersion(version);
                    cookies = LazyList.add(cookies, cookie);
                } catch (Exception ex) {
                    LogSupport.ignore(log, ex);
                }
            }
        }

        int l = LazyList.size(cookies);
        if (_cookies == null || _cookies.length != l)
            _cookies = new Cookie[l];
        for (int i = 0; i < l; i++)
            _cookies[i] = (Cookie) LazyList.get(cookies, i);
        _cookiesExtracted = true;

        l = LazyList.size(lastCookies);
        _lastCookies = new String[l];
        for (int i = 0; i < l; i++)
            _lastCookies[i] = (String) LazyList.get(lastCookies, i);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    return _cookies;
}

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

public void addOrUpdateRecentProductToCookie(final HttpServletRequest request,
        final HttpServletResponse response, final String catalogCode, final String virtualCategoryCode,
        final String productMarketingCode, final String productSkuCode) throws Exception {
    Cookie info = null;
    String cookieProductValue = catalogCode + Constants.SEMI_COLON + virtualCategoryCode + Constants.SEMI_COLON
            + productMarketingCode + Constants.SEMI_COLON + productSkuCode;
    Cookie[] cookies = request.getCookies();
    Boolean found = false;/*from   w w w. j  av  a 2s .com*/
    String domain = request.getServerName();
    if (cookies != null) {
        for (Cookie cooky : cookies) {
            info = cooky;
            if (getRecentProductsCookieName().equals(info.getName())) {
                found = true;
                break;
            }
        }
    }
    if (found) {
        Boolean flag = false;
        String value = URLDecoder.decode(info.getValue(), Constants.UTF8);
        if (value.contains(Constants.PIPE)) {
            String[] splits = value.split(Constants.PIPE);
            for (String cookieProductValueIt : splits) {
                if (cookieProductValueIt.contains(Constants.SEMI_COLON)) {
                    if (cookieProductValueIt.contains(cookieProductValue)) {
                        flag = true;
                    }
                } else {
                    // VALUE DOESN'T CONTAIN SEMI COLON : CLEAN THE COOKIE - NON COMPATIBLE VALUE
                    info.setValue("");
                    info.setPath("/");
                    info.setMaxAge(Constants.COOKIES_LENGTH);
                    info.setDomain(domain);
                    response.addCookie(info);
                }
            }
        } else {
            if (value.contains(Constants.SEMI_COLON)) {
                if (value.contains(cookieProductValue)) {
                    flag = true;
                }
            } else {
                // VALUE DOESN'T CONTAIN SEMI COLON : CLEAN THE COOKIE - NON COMPATIBLE VALUE
                value = "";
                info.setValue("");
                info.setPath("/");
                info.setMaxAge(Constants.COOKIES_LENGTH);
                info.setDomain(domain);
                response.addCookie(info);
            }
        }
        if (!flag) {
            String values = value;
            if (StringUtils.isNotEmpty(values)) {
                values += Constants.PIPE;
            }
            values += cookieProductValue;
            info.setValue(URLEncoder.encode(values, Constants.UTF8));
            info.setPath("/");
            info.setMaxAge(Constants.COOKIES_LENGTH);
            info.setDomain(domain);
            response.addCookie(info);
        }
    } else {
        info = new Cookie(getRecentProductsCookieName(), cookieProductValue);
        info.setPath("/");
        info.setMaxAge(Constants.COOKIES_LENGTH);
        info.setDomain(domain);
        response.addCookie(info);
    }
}

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

/**
 * PAIA core services: Prfe jeweils die scopes und liefere die Daten
 *///w w w .j  av  a 2  s.  c  o  m
private void provideService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String patronid, String service, String format, String language, String redirect_url,
        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();

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

        try {
            IntegratedLibrarySystem integratedLibrarySystem = Lookup.lookup(IntegratedLibrarySystem.class);
            // init ILS
            integratedLibrarySystem.init(this.config);

            switch (service) {

            case "patron": {

                Patron patron = integratedLibrarySystem.patron(patronid, false);

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_patron");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    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("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(patron, parameters));
                            } catch (TransformationException e) {
                                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(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(patron, 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(), patron);
                    }
                } 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_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 "fullpatron": {

                Patron patron = integratedLibrarySystem.patron(patronid, true);

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_patron");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    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("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(patron, parameters));
                            } catch (TransformationException e) {
                                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(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(patron, 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(), patron);
                    }
                } 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_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 "items": {

                DocumentList documentList = integratedLibrarySystem.items(patronid, "all");

                if (documentList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    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("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                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(DocumentList.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(documentList, 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(), documentList);
                    }
                } 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_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 "items/borrowed": {

                DocumentList documentList = integratedLibrarySystem.items(patronid, "borrowed");

                if (documentList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    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("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                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(DocumentList.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(documentList, 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(), documentList);
                    }
                } 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_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 "items/borrowed/ill": {

                DocumentList documentList = integratedLibrarySystem.items(patronid, "borrowed", "ill");

                if (documentList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    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("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                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(DocumentList.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(documentList, 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(), documentList);
                    }
                } 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_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 "items/borrowed/renewed": {

                DocumentList documentList = integratedLibrarySystem.items(patronid, "borrowed", "renewed");

                if (documentList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    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("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                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(DocumentList.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(documentList, 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(), documentList);
                    }
                } 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_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 "items/borrowed/recalled": {

                DocumentList documentList = integratedLibrarySystem.items(patronid, "borrowed", "recalled");

                if (documentList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    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("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                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(DocumentList.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(documentList, 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(), documentList);
                    }
                } 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_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 "items/ordered": {

                DocumentList documentList = integratedLibrarySystem.items(patronid, "ordered");

                if (documentList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    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("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                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(DocumentList.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(documentList, 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(), documentList);
                    }
                } 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_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 "items/reserved": {

                DocumentList documentList = integratedLibrarySystem.items(patronid, "reserved");

                if (documentList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    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("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                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(DocumentList.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(documentList, 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(), documentList);
                    }
                } 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_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 "request": {

                DocumentList documentList = integratedLibrarySystem.request(patronid, documents);

                if (documentList != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    // set Cookie with new value for 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);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

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

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

                            this.logger.info("redirect_url = " + redirect_url);
                            if (!redirect_url.equals("")) {

                                httpServletResponse.sendRedirect(redirect_url);
                            } else {

                                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("service", service);

                                    httpServletResponse.setContentType("text/html;charset=UTF-8");
                                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                    httpServletResponse.getWriter()
                                            .println(htmlTransformation.transform(documentList, parameters));
                                } catch (TransformationException e) {
                                    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(DocumentList.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(documentList, 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(), documentList);
                    }
                } 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_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 "renew": {

                DocumentList documentList = integratedLibrarySystem.renew(patronid, documents);

                if (documentList != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    // delete DocumentList cookie
                    Cookie cookie = new Cookie("PaiaServiceDocumentList", 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);
                    httpServletResponse.addCookie(cookie);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    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("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                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(DocumentList.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(documentList, 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(), documentList);
                    }
                } 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_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 "cancel": {

                DocumentList documentList = integratedLibrarySystem.cancel(patronid, documents);

                if (documentList != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    // delete DocumentList cookie
                    Cookie cookie = new Cookie("PaiaServiceDocumentList", 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);
                    httpServletResponse.addCookie(cookie);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    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("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                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(DocumentList.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(documentList, 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(), documentList);
                    }
                } 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_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 "fees": {

                FeeList feeList = integratedLibrarySystem.fees(patronid);

                if (feeList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, feeList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_fees");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    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("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(feeList, parameters));
                            } catch (TransformationException e) {
                                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(FeeList.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(feeList, 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(), feeList);
                    }
                } 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_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;
            }
            }
        } catch (ILSException e) {

            StringWriter json = new StringWriter();

            // TODO Frage nach "570-unknown patron" ist nicht gut! Lsung: Welche Typen von ILSExceptions treten auf? Erzeuge fr jeden Typ eine eigene Exception!
            if (e.getMessage().contains("570-unknown patron")) {

                this.logger.error("[" + this.config.getProperty("service.name") + "] "
                        + HttpServletResponse.SC_NOT_FOUND + ": '" + patronid + "'");

                // 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_NOT_FOUND);
                }

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

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

                this.logger.error("[" + this.config.getProperty("service.name") + "] "
                        + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                // 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);
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    } else {

        this.logger.error("[" + this.config.getProperty("service.name") + "] "
                + 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);
    }
}

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

/**
 * Make sure we have a Sakai session.//from  w w  w.  ja  va 2  s .  co m
 *
 * @param req
 *        The request object.
 * @param res
 *        The response object.
 * @return The Sakai Session object.
 */
protected Session assureSession(HttpServletRequest req, HttpServletResponse res) {
    Session s = null;
    String sessionId = null;
    boolean allowSetCookieEarly = true;
    Cookie c = null;

    // automatic, i.e. not from user activity, request?
    boolean auto = req.getParameter(PARAM_AUTO) != null;

    // session id provided in a request parameter?
    boolean reqsession = m_sessionParamAllow && req.getParameter(ATTR_SESSION) != null;

    String suffix = getCookieSuffix();

    // try finding a non-cookie session based on the remote user / principal
    // Note: use principal instead of remote user to avoid any possible confusion with the remote user set by single-signon
    // auth.
    // Principal is set by our Dav interface, which this is designed to cover. -ggolden

    Principal principal = req.getUserPrincipal();

    if (m_checkPrincipal && (principal != null) && (principal.getName() != null)) {
        // set our session id to the remote user id
        sessionId = SessionManager.makeSessionId(req, principal);

        // don't supply this cookie to the client
        allowSetCookieEarly = false;

        // find the session
        s = SessionManager.getSession(sessionId);

        // if not found, make a session for this user
        if (s == null) {
            s = SessionManager.startSession(sessionId);
        }

        // Make these sessions expire after 10 minutes
        s.setMaxInactiveInterval(10 * 60);
    }

    // if no principal, check request parameter and cookie
    if (sessionId == null || s == null) {
        if (m_sessionParamAllow) {
            sessionId = req.getParameter(ATTR_SESSION);
        }

        // find our session id from our cookie
        c = findCookie(req, cookieName, suffix);

        if (sessionId == null && c != null) {
            // get our session id
            sessionId = c.getValue();
        }

        if (sessionId != null) {
            // remove the server id suffix
            final int dotPosition = sessionId.indexOf(DOT);
            if (dotPosition > -1) {
                sessionId = sessionId.substring(0, dotPosition);
            }
            if (M_log.isDebugEnabled()) {
                M_log.debug("assureSession found sessionId in cookie: " + sessionId);
            }

            // find the session
            s = SessionManager.getSession(sessionId);
        }

        // ignore the session id provided in a request parameter
        // if the session is not authenticated
        if (reqsession && s != null && s.getUserId() == null) {
            s = null;
        }
    }

    // if found and not automatic, mark it as active
    if ((s != null) && (!auto)) {
        synchronized (s) {
            s.setActive();
        }
    }
    if (s == null && sessionId != null) {
        // check to see if this session has already been built.  If not, rebuild
        RebuildBreakdownService rebuildBreakdownService = (RebuildBreakdownService) ComponentManager
                .get(RebuildBreakdownService.class);
        if (rebuildBreakdownService != null) {
            s = SessionManager.startSession(sessionId);
            if (!rebuildBreakdownService.rebuildSession(s)) {
                s.invalidate();
                s = null;
            }
        }
    }

    // if missing, make one
    if (s == null) {
        s = SessionManager.startSession();

        // if we have a cookie, but didn't find the session and are creating a new one, mark this
        if (c != null) {
            ThreadLocalManager.set(SessionManager.CURRENT_INVALID_SESSION,
                    SessionManager.CURRENT_INVALID_SESSION);
        }
    }

    // put the session in the request attribute
    req.setAttribute(ATTR_SESSION, s);

    // set this as the current session
    SessionManager.setCurrentSession(s);

    // Now that we know the session exists, regardless of whether it's new or not, lets see if there
    // is a UsageSession.  If so, we want to check it's serverId
    UsageSession us = null;
    // FIXME synchronizing on a changing value is a bad practice plus it is possible for s to be null according to the visible code -AZ
    synchronized (s) {
        us = (UsageSession) s.getAttribute(UsageSessionService.USAGE_SESSION_KEY);
        if (us != null) {
            // check the server instance id
            ServerConfigurationService configService = org.sakaiproject.component.cover.ServerConfigurationService
                    .getInstance();
            String serverInstanceId = configService.getServerIdInstance();
            if ((serverInstanceId != null) && (!serverInstanceId.equals(us.getServer()))) {
                // Log that the UsageSession server value is changing
                M_log.info("UsageSession: Server change detected: Old Server=" + us.getServer()
                        + "    New Server=" + serverInstanceId);
                // set the new UsageSession server value
                us.setServer(serverInstanceId);
            }
        }
    }

    // if we had a cookie and we have no session, clear the cookie TODO: detect closed session in the request
    if ((s == null) && (c != null)) {
        // remove the cookie
        c = new Cookie(cookieName, "");
        c.setPath("/");
        c.setMaxAge(0);
        if (cookieDomain != null) {
            c.setDomain(cookieDomain);
        }
        addCookie(res, c);
    }

    // if we have a session and had no cookie,
    // or the cookie was to another session id, set the cookie
    if ((s != null) && allowSetCookieEarly) {
        // the cookie value we need to use
        sessionId = s.getId() + DOT + suffix;

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

    return s;
}