Example usage for javax.servlet.http HttpServletResponse addCookie

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

Introduction

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

Prototype

public void addCookie(Cookie cookie);

Source Link

Document

Adds the specified cookie to the response.

Usage

From source file:de.hska.ld.etherpad.controller.DocumentEtherpadController.java

@Secured(Core.ROLE_USER)
@RequestMapping(method = RequestMethod.GET, value = "/edit/{documentId}")
//@Transactional(readOnly = true)
public Callable editDocumentContent(HttpServletResponse response, @PathVariable Long documentId) {
    return () -> {
        Document document = documentService.findById(documentId);
        boolean readOnly = false;

        // check if the User is allowed to access the current Document
        if (document != null) {
            documentService.checkPermission(document, Access.Permission.READ);
            try {
                documentService.checkPermission(document, Access.Permission.WRITE);
            } catch (Exception e) {
                readOnly = true;//  w  w w.  j a va 2s  .co  m
            }
        } else {
            throw new NotFoundException("id");
        }

        // for the given User check whether there is an AuthorId registered in Etherpad
        UserEtherpadInfo firstUserEtherPadInfoCheck = userEtherpadInfoService
                .getUserEtherpadInfoForCurrentUser();
        String authorId = null;
        if (firstUserEtherPadInfoCheck != null) {
            authorId = firstUserEtherPadInfoCheck.getAuthorId();
        }

        //  look up if there is an existing AuthorId associated with the current user
        if (authorId == null) {

            // if there is no AuthorId present register an AuthorId for the current User
            authorId = etherpadClient.createAuthor(Core.currentUser().getFullName());
            userEtherpadInfoService.storeAuthorIdForCurrentUser(authorId);
        }

        // is the GroupPad available for the Document :
        String groupPadId = documentEtherpadInfoService.getGroupPadIdForDocument(document);
        if (groupPadId == null && !"".equals(groupPadId)) {
            //  otherwise create a GroupPad
            String groupId = etherpadClient.createGroup();
            Attachment mainContent = document.getAttachmentList().get(0);
            byte[] mainSource = mainContent.getSource();
            try {
                //String urlEncodedDocumentTitle = URLEncoder.encode(URLEncoder.encode(document.getTitle(), "UTF-8"), "UTF-8");
                String groupPadTitle = UUID.randomUUID().toString();//StringUtils.left(urlEncodedDocumentTitle, 50);
                while (groupPadTitle.endsWith("%")) {
                    groupPadTitle = groupPadTitle.substring(0, groupPadTitle.length() - 1);
                }
                if (mainSource != null) {
                    String discussionText = new String(mainSource, "UTF-8");
                    if (!"".equals(discussionText)) {
                        groupPadId = etherpadClient.createGroupPad(groupId, groupPadTitle);
                        //groupPadId = etherpadClient.createGroupPad(groupId, document.getTitle(), discussionText);
                        etherpadClient.setGroupPadContent(groupPadId, discussionText);
                        //setHTML(padID, html)
                    } else {
                        groupPadId = etherpadClient.createGroupPad(groupId, groupPadTitle);
                    }
                } else {
                    groupPadId = etherpadClient.createGroupPad(groupId, groupPadTitle);
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            //  groupPad is available associate GroupPadId for the Document
            documentEtherpadInfoService.storeGroupPadIdForDocument(groupPadId, document);
        }

        String readOnlyId = null;
        if (readOnly) {
            readOnlyId = documentEtherpadInfoService.getReadOnlyIdForDocument(document);
            if (readOnlyId == null) {
                readOnlyId = etherpadClient.getReadOnlyID(groupPadId);
                if (readOnlyId == null) {
                    throw new ValidationException("Read only id is null"); // TODO change exception type
                } else {
                    documentEtherpadInfoService.storeReadOnlyIdForDocument(readOnlyId, document);
                }
            }
        }

        // create a session between Author and GroupPad
        String groupId = groupPadId.split("\\$")[0];
        long currentTime = System.currentTimeMillis() / 1000L; // current time
        long validUntil = currentTime + 86400L;

        String sessionId = null;
        UserEtherpadInfo userEtherpadInfo = userEtherpadInfoService.getUserEtherpadInfoForCurrentUser();
        sessionId = userEtherpadInfo.getSessionId();
        Long currentValidUntil = userEtherpadInfo.getValidUntil();

        // retrieve sessionID from db if available
        boolean newSessionRequired = false;
        if (sessionId == null) {
            newSessionRequired = true;
        } else {
            boolean isStillValid = false;
            // check if valid until is still valid for more than 3h
            // check if sessionID is still valid (valid for more than 3h)
            /*boolean sameGroupId = userEtherpadInfo.getGroupId().equals(groupId);
            if (sameGroupId && userEtherpadInfo.getGroupId().equals(groupId) && currentValidUntil - currentTime >= 10800) {
            // if sessionID is still valid longer than 3h
            // then send the sessionID to the client
            isStillValid = true;
            } else if (currentValidUntil - currentTime < 10800) {
            newSessionRequired = true;
            } else if (isStillValid) {*/
            // check if the session still exists on the etherpad server (GET)
            isStillValid = etherpadClient.checkIfSessionStillValid(currentTime, sessionId, groupId);
            if (!isStillValid) {
                newSessionRequired = true;
            }
            //}
        }
        if (newSessionRequired) {
            sessionId = etherpadClient.createSession(groupId, authorId, validUntil);

            // store the sessionID into UserEtherpadInfo object
            // store the validUntil value also
            User currentUser = Core.currentUser();
            User dbUser = userService.findById(currentUser.getId());
            userEtherpadInfoService.storeSessionForUser(sessionId, groupId, validUntil, userEtherpadInfo);
        }

        // we need return types, cookie with sessionId and the URL of Etherpads Pad
        javax.servlet.http.Cookie myCookie = new javax.servlet.http.Cookie("sessionID", sessionId);
        myCookie.setPath("/");
        if (!"localhost".equals(env.getProperty("module.core.oidc.server.endpoint.main.domain"))) {
            myCookie.setDomain(env.getProperty("module.core.oidc.server.endpoint.main.domain"));
        }
        response.addCookie(myCookie);
        // return Etherpad URL path
        String padURL = null;
        if (readOnly) {
            padURL = etherpadEndpointExternal + "/p/" + readOnlyId;
        } else {
            padURL = etherpadEndpointExternal + "/p/" + groupPadId;
        }

        return new ResponseEntity<>(padURL, HttpStatus.CREATED);
    };
}

From source file:es.pode.visualizador.presentacion.modificarPerfil.ModificarPerfilControllerImpl.java

/**
 * @see es.pode.administracion.presentacion.adminusuarios.modificarPerfil.ModificarPerfilController#modificarUsuarioMismo(org.apache.struts.action.ActionMapping,
 *      es.pode.administracion.presentacion.adminusuarios.modificarPerfil.ModificarUsuarioMismoForm,
 *      javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//*  ww  w .  j  a v  a 2s. c o  m*/
public final void modificarUsuarioMismo(ActionMapping mapping,
        es.pode.visualizador.presentacion.modificarPerfil.ModificarUsuarioMismoForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    String resultado = null;
    try {
        //String idiomaSelected = LdapUserDetailsUtils.getIdioma();
        String nombre = request.getParameter("nombre");
        String apellido1 = request.getParameter("apellido1");
        Long id = Long.valueOf(request.getParameter("id"));
        String apellido2 = request.getParameter("apellido2");
        String email = request.getParameter("email");
        String idioma = request.getParameter("idioma");
        String idiomaBusqueda = request.getParameter("idiomaBusqueda");
        String tipoEmpaquetador = request.getParameter("tipoEmpaquetador");
        String clave = request.getParameter("clave");
        String openIdUrl = request.getParameter("openIdUrl");
        String repitaClave = request.getParameter("repitaClave");
        String tipoCatalogador = request.getParameter("tipoCatalogador");
        long cuota = 0;
        Matcher matcher = null;
        if (request.getParameter("cuota").length() > 0) {
            Pattern maskNum = Pattern.compile("[0-9]+");
            matcher = maskNum.matcher(request.getParameter("cuota"));
            if (!matcher.matches()) {
                if (log.isDebugEnabled())
                    log.debug("cuota caracter ilegal");
                throw new ValidatorException("{errors.modificarusuario.cuota}");
            }
            cuota = Long.valueOf(request.getParameter("cuota")).longValue();
            cuota = cuota * 1024 * 1024;
        }

        UsuarioVO usuarioVO = this.getSrvAdminUsuariosService().descripcionUsuario(id);
        // Validaciones de los campos que recogemos del formulario
        Pattern mask = Pattern.compile("[^\\\\?\\\\!\\>\\#\\&\\<\\@\\$\\/\\\'\\\"]+");
        // Validaciones para password
        Pattern maskPwd = Pattern.compile("[^\\\\?\\\\!\\>\\#\\&\\<\\@\\$\\/\\\'\\\"]+");

        if (nombre.length() <= 0) {
            log("nombre.length() <= 0");
            throw new ValidatorException("{errors.modificarusuario.nombre}");
        }
        matcher = mask.matcher(nombre);
        if (!matcher.matches()) {
            log("nombre caracter ilegal");

            throw new ValidatorException("{errors.modificarusuario.nombre.caracterIlegal}");
        }

        if (apellido1.length() <= 0) {
            log("apellido1.length() <= 0");

            throw new ValidatorException("{errors.modificarusuario.apellido1}");
        }
        matcher = mask.matcher(apellido1);
        if (!matcher.matches()) {
            log("apellido1 caracter ilegal");
            throw new ValidatorException("{errors.modificarusuario.apellido1.caracterIlegal}");
        }
        if (apellido2.length() > 0) {
            matcher = mask.matcher(apellido2);
            if (!matcher.matches()) {
                log("apellido2 caracter ilegal");
                throw new ValidatorException("{errors.modificarusuario.apellido2.caracterIlegal}");
            }
        }
        /*
         * if (apellido2.length() <= 0) { log("apellido2.length() <=
         * 0");
         * 
         * throw new
         * ValidatorException("{errors.modificarusuario.apellido2}"); }
         * matcher = mask.matcher(apellido2); if (!matcher.matches()) {
         * log("apellido2 caracter ilegal"); throw new
         * ValidatorException("{errors.altausuario.modificarusuario.caracterIlegal}"); }
         */
        if (email.length() <= 0) {
            log("email.length() <= 0");
            throw new ValidatorException("{errors.modificarusuario.email}");
        }
        if (!((email.indexOf("@") > 0) && (email.indexOf(".") > 0))) {
            throw new ValidatorException("{errors.modificarusuario.emailIncorrecto}");
        }

        if ((clave == null) || (clave.equalsIgnoreCase(""))) {
            log("No se modifica la clave");
        } else {
            if (clave.length() < 7) {
                log("clave .length() <= 7");
                throw new ValidatorException("{errors.modificarusuario.clave}");
            }

            matcher = maskPwd.matcher(clave);
            if (!matcher.matches()) {
                log("contrasea caracter ilegal");
                throw new ValidatorException("{errors.modificarusuario.clave.caracterIlegal}");
            }

            if (!(clave.equalsIgnoreCase(repitaClave))) {
                throw new ValidatorException("{errors.modificarusuario.claveDistintas}");
            }
            usuarioVO.setClave(clave);
        }
        if (openIdUrl != null && openIdUrl.length() > 0) {
            UsuarioVO usuariovo = this.getSrvAdminUsuariosService().obtenerUsuarioConOpenId(openIdUrl);
            if (usuariovo != null && !usuariovo.getUsuario().equals(usuarioVO.getUsuario())) {
                if (log.isDebugEnabled())
                    log.debug("Ese identificador de openId ya existe en la base de datos");
                throw new ValidatorException("{errors.altausuario.existe.openId}");
            }

        }
        if (idiomaBusqueda == null) {
            throw new ValidatorException("{errors.modificarusuario.idiomaBusqueda}");
        }
        if (idiomaBusqueda.length() <= 0) {
            log("empaquetador .length() <= 0");
            throw new ValidatorException("{errors.modificarusuario.idiomaBusqueda}");
        }

        if (idioma == null) {
            throw new ValidatorException("{errors.modificarusuario.idioma}");
        }
        if (idioma.length() <= 0) {
            log("empaquetador .length() <= 0");
            throw new ValidatorException("{errors.modificarusuario.idioma}");
        }

        if (tipoEmpaquetador == null) {
            throw new ValidatorException("{errors.modificarusuario.tipoEmpaquetador}");
        }
        if (tipoEmpaquetador.length() <= 0) {
            log("empaquetador .length() <= 0");
            throw new ValidatorException("{errors.modificarusuario.tipoEmpaquetador}");
        }

        // /////Fin de validaciones de campo //////////

        usuarioVO.setNombre(nombre);
        usuarioVO.setApellido1(apellido1);
        usuarioVO.setApellido2(apellido2);
        usuarioVO.setEmail(email);
        usuarioVO.setTipoEmpaquetador(tipoEmpaquetador);
        usuarioVO.setIdioma(idioma);
        usuarioVO.setIdiomaBusqueda(idiomaBusqueda);
        usuarioVO.setTipoCatalogador(tipoCatalogador);
        usuarioVO.setCuota(new Long(cuota));
        usuarioVO.setOpenIdUrl(openIdUrl);

        usuarioVO.setId(id);
        resultado = this.getSrvAdminUsuariosService().modificarUsuario(usuarioVO);
        // Fijamos la cookie de modificarPerfil
        String cookiesPerfil = this.getPropertyValue("cookieModificarPerfil");
        Long tiempo = new Long(System.currentTimeMillis());
        Cookie cookie = new Cookie(cookiesPerfil, tiempo.toString());
        cookie.setPath("/");
        response.addCookie(cookie);
        log("se ha creado la cookie MODIFICAR_PERFIL " + tiempo);
    } catch (ValidatorException ve) {
        log.error("se ha producido una validatorException");
        resultado = "FALLO.MODIFICARUSUARIO";
        throw ve;
    } catch (Exception e) {
        log.error("Error: " + e);
        resultado = "FALLO.MODIFICARUSUARIO";
        throw new ValidatorException("{modificarUsuario.error}");

    } finally {

        // /Elimino de la sesion la descripcion del grupo

        form.setResultadoModificacion(resultado);
    }

}

From source file:com.qut.middleware.spep.filter.SPEPFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    if (!(servletRequest instanceof HttpServletRequest)) {
        throw new ServletException(Messages.getString("SPEPFilter.0")); //$NON-NLS-1$
    }/*  www  . j  av  a  2 s .  co  m*/
    if (!(servletResponse instanceof HttpServletResponse)) {
        throw new ServletException(Messages.getString("SPEPFilter.1")); //$NON-NLS-1$
    }

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String resource, decodedResource, requested, redirectURL;
    URL serviceHost;

    ServletContext spepContext = this.filterConfig.getServletContext().getContext(this.spepContextName);

    // Get servlet context.
    if (spepContext == null) {
        throw new ServletException(Messages.getString("SPEPFilter.2") + " " + this.spepContextName); //$NON-NLS-1$ //$NON-NLS-2$
    }

    // Establish SPEPProxy object.
    SPEPProxy spep;
    try {
        spep = Initializer.init(spepContext);
    } catch (Exception e) {
        this.logger.error(
                "Unable to process request to acces resource, SPEP is not responding, check cross context configuration is enabled \n"
                        + e.getLocalizedMessage());
        throw new ServletException(Messages.getString("SPEPFilter.3"), e); //$NON-NLS-1$
    }

    // Ensure SPEP startup.
    if (!spep.isStarted()) {
        // Don't allow anything to occur if SPEP hasn't started correctly.
        this.logger.error("Unable to process request to acces resource, SPEP is not initialized correcty ");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new ServletException(Messages.getString("SPEPFilter.4")); //$NON-NLS-1$
    }

    // Get SPEP cookie.
    Cookie spepCookie = null;
    Cookie globalESOECookie = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(spep.getTokenName())) {
                spepCookie = cookie;
                this.logger.debug("Located spep cookie with value of " + spepCookie.getValue());
            }
            if (cookie.getName().equals(spep.getEsoeGlobalTokenName())) {
                globalESOECookie = cookie;
                this.logger
                        .debug("Located globalESOECookie cookie with value of " + globalESOECookie.getValue());
            }
        }
    }

    // value for re-determining session status after Authz request
    boolean validSession = false;

    // Check SPEP session is valid.
    if (spepCookie != null) {
        String sessionID = spepCookie.getValue();

        this.logger.info("Attempting to retrieve data for session with ID of " + sessionID);
        PrincipalSession PrincipalSession = spep.verifySession(sessionID);

        if (PrincipalSession != null) {
            this.logger.info("Located session with ID of " + sessionID);

            if (request.getSession().getAttribute(ATTRIBUTES) == null) {
                // over write with new data if it exists
                WORMHashMap<String, List<Object>> attributeMap = new WORMHashMap<String, List<Object>>();
                attributeMap.putAll(PrincipalSession.getAttributes());
                attributeMap.close();

                request.getSession().setAttribute(ATTRIBUTES, attributeMap);
                request.getSession().setAttribute(SPEP_SESSIONID, sessionID);
            }

            /*
             * This section of code is critical, we must pass the PEP an exact representation of what the user is
             * attempting to access additionally the PEP expects that the string is not in encoded form as it will
             * do exact matching, so we decode before passing our request to it.
             */
            resource = request.getRequestURI();
            if (request.getQueryString() != null)
                resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$

            decodedResource = decode(resource);

            SPEPProxy.decision authzDecision = spep.makeAuthzDecision(sessionID, decodedResource);

            // the authz processor may destroy the session if the PDP determines that the client
            // session is no longer valid, so we have to check it again
            if ((PrincipalSession = spep.verifySession(sessionID)) != null)
                validSession = true;

            if (validSession) {
                if (authzDecision == SPEPProxy.decision.permit) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was permissable");
                    chain.doFilter(request, response);
                    return;
                } else if (authzDecision == SPEPProxy.decision.deny) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was denied, forcing response of"
                            + HttpServletResponse.SC_FORBIDDEN);
                    response.setStatus(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN);
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                } else if (authzDecision == SPEPProxy.decision.error) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was in error, forcing response of"
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    throw new ServletException(Messages.getString("SPEPFilter.6")); //$NON-NLS-1$
                } else {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was undetermined, forcing response of"
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    throw new ServletException(Messages.getString("SPEPFilter.7")); //$NON-NLS-1$
                }
            }
        }

        /* Clear the local session object the supplied request is invalid */
        this.logger.debug("Invalidating session for ID of " + sessionID);
        request.getSession().invalidate();
    }

    /*
     * If we get to this stage, the user has not got a session established with this SPEP. We proceed to clear the
     * cookies configured by the SPEP to be cleared upon logout, since this is potentially the first time they have
     * come back to the SPEP since logging out.
     */
    List<Cookie> clearCookies = new Vector<Cookie>();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (spep.getLogoutClearCookies() != null) {
                for (Cookie clearCookie : spep.getLogoutClearCookies()) {
                    if (cookie.getName().equalsIgnoreCase(clearCookie.getName())) {
                        Cookie clearCookieCloneInsecure = (Cookie) clearCookie.clone();
                        clearCookieCloneInsecure.setMaxAge(0);
                        clearCookieCloneInsecure.setSecure(false);

                        clearCookies.add(clearCookieCloneInsecure);

                        // Don't need to process the inner loop again for this cookie.
                        break;
                    }
                }
            }
        }
    }

    /* Add the cookies to be cleared into the response object. */
    for (Cookie c : clearCookies)
        response.addCookie(c);

    /*
     * Remove any principal object details which may be in the session, this state can occur if the user has removed
     * their spepSession cookie but retained their jsessionid cookie
     */
    request.getSession().removeAttribute(ATTRIBUTES);

    /*
     * At this stage a determination needs to be made about allowing the request to pass SPEP without being hindered
     * due to lazy session initialization being configured if it isn't or we won't allow the request to pass for the
     * logical reasons below they will be forced to authenticate.
     */
    if (spep.isLazyInit()) {
        this.logger.info(
                "Lazy init is enabled on this SPEP instance, determining if request should be interrogated by SPEP");

        /*
         * We are being lazy in starting sessions, determine if user has already authenticated with an IDP (the
         * ESOE), if so we enforce a session (value is not important just that the cookie exists), if not figure out
         * if user is accessing something that has been configured to force a session to be established before it is
         * accessible
         */
        if (globalESOECookie == null) {
            this.logger.debug("globalESOECookie was not set for this request");

            boolean matchedLazyInitResource = false;
            resource = request.getRequestURI();
            if (request.getQueryString() != null)
                resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$

            decodedResource = decode(resource);

            for (String lazyInitResource : spep.getLazyInitResources()) {
                if (decodedResource.matches(lazyInitResource)) {
                    matchedLazyInitResource = true;
                    this.logger.info("Lazy session init attempt matched initialization query of "
                            + lazyInitResource + " from request of " + decodedResource);
                } else
                    this.logger.debug("Lazy session init attempt failed to match initialization query of "
                            + lazyInitResource + " from request of " + decodedResource);
            }

            // If we still have no reason to engage spep functionality for this request let the request pass
            if (matchedLazyInitResource) {
                if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.deny)) {
                    this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource
                            + " could be determined due to lazyInit, forwarding request to application");
                    chain.doFilter(request, response);
                    return;
                }
            } else {
                if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.permit)) {
                    this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource
                            + " could be determined due to lazyInit, forwarding request to application");
                    chain.doFilter(request, response);
                    return;
                }
            }
        }
    }

    /*
     * All attempts to provide resource access have failed, invoke SPEP to provide secure session establishment
     * Current request is B64 encoded and appended to request for SPEP to redirect users back to content dynamically
     */
    this.logger.debug("Failed all avenues to provide access to content");
    if (request.getQueryString() != null)
        requested = request.getRequestURI() + "?" + request.getQueryString();
    else
        requested = request.getRequestURI();

    /*
     * Determine if the request was directed to the service URL, if so redirect to that point. If not redirect to
     * the local node.
     */
    serviceHost = new URL(spep.getServiceHost());

    String ssoRedirect = spep.getSsoRedirect();
    String timestampParameter;
    if (ssoRedirect.indexOf('?') > -1) {
        timestampParameter = "&ts=" + System.currentTimeMillis();
    } else {
        timestampParameter = "?ts=" + System.currentTimeMillis();
    }

    if (request.getServerName().equals(serviceHost.getHost())) {
        /* Ensures that SSL offloading in Layer 7 environments is correctly handled */
        requested = spep.getServiceHost() + requested;
        String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes()));
        redirectURL = MessageFormat.format(spep.getServiceHost() + spep.getSsoRedirect(),
                new Object[] { base64RequestURI + timestampParameter });
    } else {
        String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes()));
        redirectURL = MessageFormat.format(spep.getSsoRedirect(),
                new Object[] { base64RequestURI + timestampParameter });
    }

    this.logger.debug("Redirecting to " + redirectURL + " to establish secure session");
    response.sendRedirect(redirectURL);
}

From source file:nl.strohalm.cyclos.utils.LoginHelper.java

/**
 * Perform the login itself/*from ww w.ja  v a 2s.co  m*/
 */
public User login(final Class<? extends User> requiredUserClass, final String principalTypeString,
        final String memberUsername, final String principal, final String password, final String channel,
        final HttpServletRequest request, final HttpServletResponse response) throws LoginException {
    final String remoteAddress = request.getRemoteAddr();

    final PrincipalType principalType = channelService.resolvePrincipalType(channel, principalTypeString);

    // Validate the user
    String usernameToVerify = principal;
    if (principalType.getPrincipal() != Principal.USER) {
        try {
            Member member;
            member = elementService.loadByPrincipal(principalType, principal, Element.Relationships.USER,
                    Element.Relationships.GROUP);
            usernameToVerify = member.getUsername();
        } catch (final EntityNotFoundException e) {
            usernameToVerify = "";
        }
    }
    final User user = accessService.verifyLogin(memberUsername, usernameToVerify, remoteAddress);
    if (!requiredUserClass.isInstance(user)) {
        throw new AccessDeniedException();
    }

    // Find the user nature
    final Group group = user.getElement().getGroup();
    final boolean isAdmin = group instanceof AdminGroup;
    final boolean isMember = group instanceof MemberGroup;
    final boolean isBroker = group instanceof BrokerGroup;
    final boolean isOperator = group instanceof OperatorGroup;
    final boolean isPosWeb = RequestHelper.isPosWeb(request);

    final AccessSettings accessSettings = settingsService.getAccessSettings();

    // Check if the administrator is allowed to login
    if (isAdmin && !accessSettings.getAdministrationWhitelistValidator().isAllowed(request.getRemoteHost(),
            request.getRemoteAddr())) {
        throw new AccessDeniedException();
    }

    // According to the cyclos.properties flag, create a new session or use the current one
    HttpSession session;
    if (newSessionAfterLogin) {
        session = createNewSessionForlogin(request);
    } else {
        session = request.getSession();
    }

    // Login the user
    accessService.login(user, password, channel, isPosWeb, remoteAddress, session.getId());

    // Apply the session timeout
    final TimePeriod timeout = isPosWeb ? accessSettings.getPoswebTimeout()
            : isMember ? accessSettings.getMemberTimeout() : accessSettings.getAdminTimeout();
    int timeoutSeconds = (int) timeout.getValueIn(TimePeriod.Field.SECONDS);
    if (timeoutSeconds <= 0) {
        timeoutSeconds = -1;
    }
    session.setMaxInactiveInterval(timeoutSeconds);

    // If is a member, determine if the member has accounts, documents, loan groups and memberPos
    boolean hasAccounts = false;
    boolean singleAccount = false;
    boolean hasDocuments = false;
    boolean hasLoanGroups = false;
    boolean hasGeneralReferences = false;
    boolean hasTransactionFeedbacks = false;
    boolean hasPin = false;
    boolean hasExternalChannels = false;
    boolean hasCards = false;
    boolean hasPos = false;
    boolean hasCommissionContracts = false;
    if (isMember || isOperator) {
        Member member;
        if (isMember) {
            member = ((MemberUser) user).getMember();

            // Get the accessible channels
            final MemberGroup memberGroup = groupService.load(member.getMemberGroup().getId(),
                    MemberGroup.Relationships.CHANNELS);
            hasPin = groupService.usesPin(memberGroup);
            for (final Channel current : memberGroup.getChannels()) {
                if (!Channel.WEB.equals(current.getInternalName())) {
                    hasExternalChannels = true;
                    break;
                }
            }

            if (!member.getPosDevices().isEmpty()) {
                hasPos = true;
                if (member.getPosDevices().size() == 1) {
                    final Collection<MemberPos> memberPos = member.getPosDevices();
                    for (final MemberPos mpos : memberPos) {
                        session.setAttribute("uniqueMemberPosId ", mpos.getPos().getId());
                    }
                }
            }

        } else {
            member = ((OperatorUser) user).getOperator().getMember();
        }
        // Fetch broker
        member = elementService.load(member.getId(), Member.Relationships.BROKER);
        final MemberGroup memberGroup = member.getMemberGroup();

        // Check if the member has accounts
        final List<? extends Account> accounts = accountService.getAccounts(member);
        hasAccounts = !accounts.isEmpty();
        singleAccount = accounts.size() == 1;
        if (isMember) {
            // Check if the member has documents
            if (permissionService.hasPermission(MemberPermission.DOCUMENTS_VIEW)) {
                hasDocuments = true;
            } else {
                final DocumentQuery documentQuery = new DocumentQuery();
                documentQuery.setNatures(Collections.singleton(Document.Nature.MEMBER));
                documentQuery.setMember(member);
                documentQuery.setPageForCount();
                hasDocuments = PageHelper.hasResults(documentService.search(documentQuery));
            }
            // Check if the member has loan groups
            final LoanGroupQuery lgq = new LoanGroupQuery();
            lgq.setPageForCount();
            lgq.setMember(member);
            hasLoanGroups = PageHelper.hasResults(loanGroupService.search(lgq));

            // Check if the member has commission contracts
            hasCommissionContracts = commissionService.hasBrokerCommissionContracts();
        }
        // Check if the user has references
        final Collection<Nature> referenceNatures = referenceService.getNaturesByGroup(memberGroup);
        hasGeneralReferences = referenceNatures.contains(Nature.GENERAL);
        hasTransactionFeedbacks = referenceNatures.contains(Nature.TRANSACTION);

        // Check if the user can have guarantees
        try {
            final Collection<GuaranteeType.Model> guaranteeModels = guaranteeService
                    .getRelatedGuaranteeModels();
            session.setAttribute("loggedMemberHasGuarantees", guaranteeModels.size() > 0);
        } catch (final Exception e) {
            // Ignore
        }

        // Check if the user has cards
        hasCards = member.getCards().isEmpty() ? false : true;
    }

    if (isAdmin || isBroker) {
        // Retrieve the member record types the logged user can see on the menu
        final MemberRecordTypeQuery query = new MemberRecordTypeQuery();
        if (isAdmin) {
            query.setViewableByAdminGroup((AdminGroup) group);
        } else {
            query.setViewableByBrokerGroup((BrokerGroup) group);
        }
        query.setShowMenuItem(true);
        final List<MemberRecordType> types = memberRecordTypeService.search(query);
        session.setAttribute("memberRecordTypesInMenu", types);
    }

    // When a receipt printer cookie is set, and the printer no longer exists, or belongs to someone else, clear the cookie
    final String receiptPrinterId = RequestHelper.getCookieValue(request, "receiptPrinterId");
    if (StringUtils.isNotEmpty(receiptPrinterId)) {
        final Long id = IdConverter.instance().valueOf(receiptPrinterId);
        if (!receiptPrinterSettingsService.belongsToTheLoggedUser(id)) {
            final Cookie cookie = new Cookie("receiptPrinterId", "");
            cookie.setPath(request.getContextPath());
            response.addCookie(cookie);
        }
    }

    final String actionPrefix = "/" + (isAdmin ? "admin" : isMember ? "member" : "operator");

    // Set the request attributes
    request.setAttribute("loggedUser", user);
    request.setAttribute("loggedElement", user.getElement());

    // Set the session attributes
    session.setAttribute("loggedUserId", user.getId());
    session.setAttribute("isAdmin", isAdmin);
    session.setAttribute("isMember", isMember);
    session.setAttribute("isBroker", isBroker);
    session.setAttribute("isOperator", isOperator);
    session.setAttribute("isBuyer", guaranteeService.isBuyer());
    session.setAttribute("isSeller", guaranteeService.isSeller());
    session.setAttribute("isIssuer", guaranteeService.isIssuer());
    session.setAttribute("loggedMemberHasAccounts", hasAccounts);
    session.setAttribute("loggedMemberHasSingleAccount", singleAccount);
    session.setAttribute("loggedMemberHasDocuments", hasDocuments);
    session.setAttribute("loggedMemberHasLoanGroups", hasLoanGroups);
    session.setAttribute("loggedMemberHasGeneralReferences", hasGeneralReferences);
    session.setAttribute("loggedMemberHasTransactionFeedbacks", hasTransactionFeedbacks);
    session.setAttribute("hasPin", hasPin);
    session.setAttribute("hasCards", hasCards);
    session.setAttribute("hasPos", hasPos);
    session.setAttribute("hasCommissionContracts", hasCommissionContracts);
    session.setAttribute("hasExternalChannels", hasExternalChannels);
    session.setAttribute("actionPrefix", actionPrefix);
    session.setAttribute("pathPrefix", "/do" + actionPrefix);
    session.setAttribute("navigation", Navigation.get(session));

    // Return the logged user
    return user;
}

From source file:contestWebsite.AdminPanel.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    UserCookie userCookie = UserCookie.getCookie(req);
    boolean loggedIn = userCookie != null && userCookie.authenticate();
    if (loggedIn && userCookie.isAdmin()) {
        Map<String, String[]> params = req.getParameterMap();

        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
        try {/*from w w  w  .  j a  va 2  s  . c o  m*/
            Entity info = Retrieve.contestInfo();
            Entity contestInfo = info != null ? info : new Entity("contestInfo");
            String view = params.get("view")[0];

            boolean testingMode;
            if (view.equals("general")) {
                testingMode = params.get("testing") != null && !params.containsKey("changePass");
            } else if (contestInfo.hasProperty("testingMode")) {
                testingMode = (boolean) contestInfo.getProperty("testingMode");
            } else {
                testingMode = false;
            }

            String[] stringPropNames = {}, textPropNames = {};

            if (view.equals("general")) {
                contestInfo.setProperty("levels", StringUtils.join(params.get("levels"), "+"));
                contestInfo.setProperty("price", Integer.parseInt(params.get("price")[0]));
                contestInfo.setProperty("testingMode", testingMode);
                contestInfo.setProperty("complete", params.get("complete") != null);
                contestInfo.setProperty("hideFullNames", params.get("fullnames") != null);

                stringPropNames = new String[] { "title", "endDate", "startDate", "editStartDate",
                        "editEndDate", "classificationQuestion", "testDownloadURL" };
            } else if (view.equals("tabulation")) {
                for (Level level : Level.values()) {
                    String[] docNames = params.get("doc" + level.getName());
                    if (docNames != null) {
                        contestInfo.setProperty("doc" + level.getName(), docNames[0]);
                    }

                    String[] schoolGroupsParam = params.get(level.toString() + "SchoolGroups");
                    if (schoolGroupsParam != null) {
                        try {
                            Yaml yaml = new Yaml();
                            Map<String, List<String>> schoolGroups = (Map<String, List<String>>) yaml
                                    .load(schoolGroupsParam[0]);
                            Map<String, String> schoolGroupNames = new HashMap<String, String>();
                            if (schoolGroups == null) {
                                schoolGroups = new HashMap<String, List<String>>();
                            }
                            for (Entry<String, List<String>> schoolGroupEntry : schoolGroups.entrySet()) {
                                for (String school : schoolGroupEntry.getValue()) {
                                    schoolGroupNames.put(school, schoolGroupEntry.getKey());
                                }
                            }
                            contestInfo.setProperty(level.toString() + "SchoolGroups",
                                    new Text(schoolGroupsParam[0]));
                            contestInfo.setProperty(level.toString() + "SchoolGroupsNames",
                                    new Text(new Yaml().dump(schoolGroupNames)));
                        } catch (Exception e) {
                            e.printStackTrace();
                            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString());
                            return;
                        }
                    }
                }

                for (Subject subject : Subject.values()) {
                    String[] subjectColors = params.get("color" + subject.getName());
                    if (subjectColors != null) {
                        contestInfo.setProperty("color" + subject.getName(), subjectColors[0]);
                    }
                }

                if (params.get("submitType")[0].equals("enqueueTabulationTask")) {
                    Queue queue = QueueFactory.getDefaultQueue();
                    TaskOptions options = withUrl("/tabulate")
                            .retryOptions(RetryOptions.Builder.withTaskRetryLimit(0));

                    for (Level level : Level.values()) {
                        String[] docNames = params.get("doc" + level.getName());
                        if (docNames != null) {
                            options.param("doc" + level.getName(), docNames[0]);
                        }
                    }

                    queue.add(options);
                }
            } else if (view.equals("content")) {
                GeoPt location = new GeoPt(Float.parseFloat(params.get("location_lat")[0]),
                        Float.parseFloat(params.get("location_long")[0]));
                contestInfo.setProperty("location", location);

                Yaml yaml = new Yaml();
                String[] mapPropNames = { "schedule", "directions" };
                for (String propName : mapPropNames) {
                    String text = params.get(propName)[0];

                    try {
                        @SuppressWarnings("unused")
                        HashMap<String, String> map = (HashMap<String, String>) yaml.load(text);
                        contestInfo.setProperty(propName, new Text(text));
                    } catch (Exception e) {
                        e.printStackTrace();
                        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString());
                        return;
                    }
                }

                String slideshowText = params.get("slideshow")[0];
                try {
                    @SuppressWarnings("unused")
                    ArrayList<ArrayList<String>> list = (ArrayList<ArrayList<String>>) yaml.load(slideshowText);
                    contestInfo.setProperty("slideshow", new Text(slideshowText));
                } catch (Exception e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString());
                    return;
                }

                stringPropNames = new String[] { "school", "address" };
                textPropNames = new String[] { "aboutText" };
            } else if (view.equals("awards")) {
                JSONObject awardCriteria = new JSONObject(), qualifyingCriteria = new JSONObject();
                ;
                for (Entry<String, String[]> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("counts_")) {
                        awardCriteria.put(entry.getKey().replace("counts_", ""),
                                Integer.parseInt(entry.getValue()[0]));
                    } else if (entry.getKey().startsWith("qualifying_")) {
                        if (!entry.getValue()[0].isEmpty()) {
                            qualifyingCriteria.put(entry.getKey().replace("qualifying_", ""),
                                    Integer.parseInt(entry.getValue()[0]));
                        }
                    }
                }
                contestInfo.setProperty("awardCriteria", new Text(awardCriteria.toString()));
                contestInfo.setProperty("qualifyingCriteria", new Text(qualifyingCriteria.toString()));
            } else if (view.equals("emails")) {
                stringPropNames = new String[] { "email", "account" };
                textPropNames = new String[] { "forgotPassEmail", "questionEmail", "registrationEmail" };
            } else if (view.equals("apis")) {
                stringPropNames = new String[] { "OAuth2ClientSecret", "OAuth2ClientId", "siteVerification",
                        "publicKey", "privateKey" };
                textPropNames = new String[] { "googleAnalytics" };
            }

            for (String propName : stringPropNames) {
                contestInfo.setProperty(propName, params.get(propName)[0]);
            }

            for (String propName : textPropNames) {
                contestInfo.setProperty(propName, new Text(params.get(propName)[0]));
            }

            datastore.put(contestInfo);

            Query query = new Query("user")
                    .setFilter(new FilterPredicate("user-id", FilterOperator.EQUAL, "admin"));
            Entity user = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)).get(0);
            String hash = (String) user.getProperty("hash");
            String salt = (String) user.getProperty("salt");

            if (testingMode) {
                String newHash = Password.getSaltedHash("password");
                resp.addCookie(new Cookie("user-id",
                        URLEncoder.encode("admin" + "$" + newHash.split("\\$")[1], "UTF-8")));

                user.setProperty("salt", newHash.split("\\$")[0]);
                user.setProperty("hash", newHash.split("\\$")[1]);
                datastore.put(user);
                resp.sendRedirect("/adminPanel?updated=1");
            } else if (params.containsKey("changePass")) {
                String curPassword = params.get("curPassword")[0];
                String confPassword = params.get("confPassword")[0];
                String newPassword = params.get("newPassword")[0];

                if (Password.check(curPassword, salt + "$" + hash)) {
                    if (confPassword.equals(newPassword)) {
                        String newHash = Password.getSaltedHash(newPassword);
                        resp.addCookie(new Cookie("user-id",
                                URLEncoder.encode("admin" + "$" + newHash.split("\\$")[1], "UTF-8")));

                        user.setProperty("salt", newHash.split("\\$")[0]);
                        user.setProperty("hash", newHash.split("\\$")[1]);
                        datastore.put(user);
                        resp.sendRedirect("/adminPanel?updated=1");
                    } else {
                        resp.sendRedirect("/adminPanel?confPassError=1");
                    }
                } else {
                    resp.sendRedirect("/adminPanel?passError=1");
                }
            } else {
                resp.sendRedirect("/adminPanel?updated=1");
            }
            txn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        } finally {
            if (txn.isActive()) {
                txn.rollback();
            }
        }
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Contest Administrator privileges required for that operation");
    }
}

From source file:net.yacy.http.servlets.YaCyDefaultServlet.java

/**
 * Handles a YaCy servlet template, reads the template and replaces the template
 * items with actual values. Because of supported server side includes target 
 * might not be the same as request.getPathInfo
 * //from www .j a  v a  2 s .  co m
 * @param target the path to the template
 * @param request the remote servlet request
 * @param response
 * @throws IOException
 * @throws ServletException
 */
protected void handleTemplate(String target, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Switchboard sb = Switchboard.getSwitchboard();

    String localeSelection = sb.getConfig("locale.language", "browser");
    if (localeSelection.endsWith("browser")) {
        String lng = request.getLocale().getLanguage();
        if (lng.equalsIgnoreCase("en")) { // because en is handled as "default" in localizer
            localeSelection = "default";
        } else {
            localeSelection = lng;
        }
    }
    File targetFile = getLocalizedFile(target, localeSelection);
    File targetClass = rewriteClassFile(_resourceBase.addPath(target).getFile());
    String targetExt = target.substring(target.lastIndexOf('.') + 1);

    long now = System.currentTimeMillis();
    if (target.endsWith(".css")) {
        response.setDateHeader(HeaderFramework.LAST_MODIFIED, now);
        response.setDateHeader(HeaderFramework.EXPIRES, now + 3600000); // expires in 1 hour (which is still often, others use 1 week, month or year)
    } else if (target.endsWith(".png")) {
        // expires in 1 minute (reduce heavy image creation load)
        if (response.containsHeader(HeaderFramework.LAST_MODIFIED)) {
            response.getHeaders(HeaderFramework.LAST_MODIFIED).clear();
        }
        response.setHeader(HeaderFramework.CACHE_CONTROL, "public, max-age=" + Integer.toString(60));
    } else {
        response.setDateHeader(HeaderFramework.LAST_MODIFIED, now);
        response.setDateHeader(HeaderFramework.EXPIRES, now); // expires now
    }

    if ((targetClass != null)) {
        serverObjects args = new serverObjects();
        Enumeration<String> argNames = request.getParameterNames(); // on ssi jetty dispatcher merged local ssi query parameters
        while (argNames.hasMoreElements()) {
            String argName = argNames.nextElement();
            // standard attributes are just pushed as string
            args.put(argName, request.getParameter(argName));
        }
        RequestHeader legacyRequestHeader = generateLegacyRequestHeader(request, target, targetExt);
        // add multipart-form fields to parameter
        if (ServletFileUpload.isMultipartContent(request)) {
            final String bodyEncoding = request.getHeader(HeaderFramework.CONTENT_ENCODING);
            if (HeaderFramework.CONTENT_ENCODING_GZIP.equalsIgnoreCase(bodyEncoding)) {
                parseMultipart(new GZIPRequestWrapper(request), args);
            } else {
                parseMultipart(request, args);
            }
        }
        // eof modification to read attribute
        Object tmp;
        try {
            if (args.isEmpty()) {
                // yacy servlets typically test for args != null (but not for args .isEmpty())
                tmp = invokeServlet(targetClass, legacyRequestHeader, null);
            } else {
                tmp = invokeServlet(targetClass, legacyRequestHeader, args);
            }
        } catch (InvocationTargetException e) {
            if (e.getCause() instanceof InvalidURLLicenceException) {
                /* A non authaurized user is trying to fetch a image with a bad or already released license code */
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getCause().getMessage());
                return;
            }
            if (e.getCause() instanceof TemplateMissingParameterException) {
                /* A template is used but miss some required parameter */
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getCause().getMessage());
                return;
            }
            ConcurrentLog.logException(e);
            throw new ServletException(targetFile.getAbsolutePath());
        } catch (IllegalArgumentException | IllegalAccessException e) {
            ConcurrentLog.logException(e);
            throw new ServletException(targetFile.getAbsolutePath());
        }

        if (tmp instanceof RasterPlotter || tmp instanceof EncodedImage || tmp instanceof Image) {

            net.yacy.cora.util.ByteBuffer result = null;

            if (tmp instanceof RasterPlotter) {
                final RasterPlotter yp = (RasterPlotter) tmp;
                // send an image to client
                result = RasterPlotter.exportImage(yp.getImage(), "png");
            } else if (tmp instanceof EncodedImage) {
                final EncodedImage yp = (EncodedImage) tmp;
                result = yp.getImage();
                /** When encodedImage is empty, return a code 500 rather than only an empty response 
                 * as it is better handled across different browsers */
                if (result == null || result.length() == 0) {
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    result.close();
                    return;
                }
                if (yp.isStatic()) { // static image never expires
                    response.setDateHeader(HeaderFramework.EXPIRES, now + 3600000); // expires in 1 hour
                }
            } else if (tmp instanceof Image) {
                final Image i = (Image) tmp;

                // generate an byte array from the generated image
                int width = i.getWidth(null);
                if (width < 0) {
                    width = 96; // bad hack
                }
                int height = i.getHeight(null);
                if (height < 0) {
                    height = 96; // bad hack
                }
                final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
                bi.createGraphics().drawImage(i, 0, 0, width, height, null);
                result = RasterPlotter.exportImage(bi, targetExt);
            }

            updateRespHeadersForImages(target, response);
            final String mimeType = Classification.ext2mime(targetExt, MimeTypes.Type.TEXT_HTML.asString());
            response.setContentType(mimeType);
            response.setContentLength(result.length());
            response.setStatus(HttpServletResponse.SC_OK);

            result.writeTo(response.getOutputStream());
            result.close();
            return;
        }

        if (tmp instanceof InputStream) {
            /* Images and favicons can also be written directly from an inputStream */
            updateRespHeadersForImages(target, response);

            writeInputStream(response, targetExt, (InputStream) tmp);
            return;
        }

        servletProperties templatePatterns;
        if (tmp == null) {
            // if no args given, then tp will be an empty Hashtable object (not null)
            templatePatterns = new servletProperties();
        } else if (tmp instanceof servletProperties) {
            templatePatterns = (servletProperties) tmp;

            if (templatePatterns.getOutgoingHeader() != null) {
                // handle responseHeader entries set by servlet
                ResponseHeader tmpouthdr = templatePatterns.getOutgoingHeader();
                for (String hdrkey : tmpouthdr.keySet()) {
                    if (!HeaderFramework.STATUS_CODE.equals(hdrkey)) { // skip default init response status value (not std. )
                        String val = tmpouthdr.get(hdrkey);
                        if (!response.containsHeader(hdrkey) && val != null) { // to be on the safe side, add only new hdr (mainly used for CORS_ALLOW_ORIGIN)
                            response.setHeader(hdrkey, tmpouthdr.get(hdrkey));
                        }
                    }
                }
                // handle login cookie
                if (tmpouthdr.getCookiesEntries() != null) {
                    for (Cookie c : tmpouthdr.getCookiesEntries()) {
                        response.addCookie(c);
                    }
                }
            }
        } else {
            templatePatterns = new servletProperties((serverObjects) tmp);
        }

        // handle YaCy http commands
        // handle action auth: check if the servlets requests authentication
        if (templatePatterns.containsKey(serverObjects.ACTION_AUTHENTICATE)) {
            if (!request.authenticate(response)) {
                return;
            }
            //handle action forward
        } else if (templatePatterns.containsKey(serverObjects.ACTION_LOCATION)) {
            String location = templatePatterns.get(serverObjects.ACTION_LOCATION, "");

            if (location.isEmpty()) {
                location = request.getPathInfo();
            }
            //TODO: handle equivalent of this from httpdfilehandler
            // final ResponseHeader headers = getDefaultHeaders(request.getPathInfo());
            // headers.setAdditionalHeaderProperties(templatePatterns.getOutgoingHeader().getAdditionalHeaderProperties()); //put the cookies into the new header TODO: can we put all headerlines, without trouble?

            response.setHeader(HeaderFramework.LOCATION, location);
            response.setStatus(HttpServletResponse.SC_FOUND);
            return;
        }

        if (targetFile.exists() && targetFile.isFile() && targetFile.canRead()) {

            sb.setConfig("server.servlets.called",
                    appendPath(sb.getConfig("server.servlets.called", ""), target));
            if (args != null && !args.isEmpty()) {
                sb.setConfig("server.servlets.submitted",
                        appendPath(sb.getConfig("server.servlets.submitted", ""), target));
            }

            // add the application version, the uptime and the client name to every rewrite table
            templatePatterns.put(servletProperties.PEER_STAT_VERSION, yacyBuildProperties.getVersion());
            templatePatterns.put(servletProperties.PEER_STAT_UPTIME,
                    ((System.currentTimeMillis() - sb.startupTime) / 1000) / 60); // uptime in minutes
            templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTNAME, sb.peers.mySeed().getName());
            templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTID, sb.peers.myID());
            templatePatterns.put(servletProperties.PEER_STAT_MYTIME,
                    GenericFormatter.SHORT_SECOND_FORMATTER.format());
            templatePatterns.put(servletProperties.RELATIVE_BASE, YaCyDefaultServlet.getRelativeBase(target));
            Seed myPeer = sb.peers.mySeed();
            templatePatterns.put("newpeer", myPeer.getAge() >= 1 ? 0 : 1);
            templatePatterns.putHTML("newpeer_peerhash", myPeer.hash);
            boolean authorized = sb.adminAuthenticated(legacyRequestHeader) >= 2;
            templatePatterns.put("authorized", authorized ? 1 : 0); // used in templates and other html (e.g. to display lock/unlock symbol)

            templatePatterns.put("simpleheadernavbar",
                    sb.getConfig("decoration.simpleheadernavbar", "navbar-default"));

            // add navigation keys to enable or disable menu items
            templatePatterns.put("navigation-p2p",
                    sb.getConfigBool(SwitchboardConstants.DHT_ENABLED, true) || !sb.isRobinsonMode() ? 1 : 0);
            templatePatterns.put("navigation-p2p_authorized", authorized ? 1 : 0);
            String submitted = sb.getConfig("server.servlets.submitted", "");
            boolean crawler_enabled = true; /*
                                            submitted.contains("Crawler_p") ||
                                            submitted.contains("ConfigBasic") ||
                                            submitted.contains("Load_RSS_p");*/
            boolean advanced_enabled = crawler_enabled || submitted.contains("IndexImportMediawiki_p")
                    || submitted.contains("CrawlStart");
            templatePatterns.put("navigation-crawlmonitor", crawler_enabled);
            templatePatterns.put("navigation-crawlmonitor_authorized", authorized ? 1 : 0);
            templatePatterns.put("navigation-advanced", advanced_enabled);
            templatePatterns.put("navigation-advanced_authorized", authorized ? 1 : 0);
            templatePatterns.put(SwitchboardConstants.GREETING_HOMEPAGE,
                    sb.getConfig(SwitchboardConstants.GREETING_HOMEPAGE, ""));
            templatePatterns.put(SwitchboardConstants.GREETING_SMALL_IMAGE,
                    sb.getConfig(SwitchboardConstants.GREETING_SMALL_IMAGE, ""));
            templatePatterns.put(SwitchboardConstants.GREETING_IMAGE_ALT,
                    sb.getConfig(SwitchboardConstants.GREETING_IMAGE_ALT, ""));
            templatePatterns.put("clientlanguage", localeSelection);

            String mimeType = Classification.ext2mime(targetExt, MimeTypes.Type.TEXT_HTML.asString());

            InputStream fis;
            long fileSize = targetFile.length();

            if (fileSize <= Math.min(4 * 1024 * 1204, MemoryControl.available() / 100)) {
                // read file completely into ram, avoid that too many files are open at the same time
                fis = new ByteArrayInputStream(FileUtils.read(targetFile));
            } else {
                fis = new BufferedInputStream(new FileInputStream(targetFile));
            }

            // set response header
            response.setContentType(mimeType);
            response.setStatus(HttpServletResponse.SC_OK);
            ByteArrayOutputStream bas = new ByteArrayOutputStream(4096);
            try {
                // apply templates
                TemplateEngine.writeTemplate(targetFile.getName(), fis, bas, templatePatterns);

                // handle SSI
                parseSSI(bas.toByteArray(), request, response);
            } finally {
                try {
                    fis.close();
                } catch (IOException ignored) {
                    ConcurrentLog.warn("FILEHANDLER",
                            "YaCyDefaultServlet: could not close target file " + targetFile.getName());
                }

                try {
                    bas.close();
                } catch (IOException ignored) {
                    /* Should never happen with a ByteArrayOutputStream */
                }
            }
        }
    }
}

From source file:com.glaf.core.util.HttpQueryUtils.java

public static BaseQuery prepareQuery(HttpServletRequest request, HttpServletResponse response,
        String serviceKey, Map<String, Object> paramMap) {
    BaseQuery query = new BaseQuery();
    Map<String, Object> params = new java.util.HashMap<String, Object>();
    List<QueryCondition> conditions = new java.util.ArrayList<QueryCondition>();
    JSONObject rootJson = new JSONObject();
    JSONObject paramJson = new JSONObject();
    JSONObject queryJson = new JSONObject();

    String qt = getStringValue(request, "qt");
    String qid = getStringValue(request, "qid");
    String field = getStringValue(request, "field");
    boolean removeLast = getBooleanValue(request, "removeLast");

    queryJson.put("removeLast", removeLast);

    if (serviceKey != null) {
        queryJson.put("serviceKey", serviceKey);
    }//from   w w  w . j av a  2  s . com
    if (qt != null) {
        queryJson.put("qt", qt);
    }
    if (qid != null) {
        queryJson.put("qid", qid);
    }
    if (field != null) {
        queryJson.put("field", field);
    }

    /**
     * IP?Cookie
     */
    String ip = RequestUtils.getIPAddress(request);
    String cookieKey = ip + "_mx_query_" + serviceKey;
    cookieKey = Hex.bytesToHex(cookieKey.getBytes());

    String content = null;

    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (Cookie cookie : cookies) {
            /**
             * Cookie???
             */
            if (StringUtils.equals(cookie.getName(), cookieKey)) {
                content = cookie.getValue();
            }
        }
    }

    JSONObject oldJson = null;

    if (StringUtils.isNotEmpty(content)) {
        String str = new String(Hex.hexToBytes(content));
        if (str != null) {
            oldJson = JSON.parseObject(str);
        }
    }

    Object value = null;
    String fieldValue = null;
    QueryCondition currentCondition = null;

    if (oldJson != null) {
        logger.debug("@@previous query json:\n" + oldJson.toJSONString());
        JSONObject paramJx = oldJson.getJSONObject("params");
        if (paramJx != null && !paramJx.isEmpty()) {
            Set<String> keySet = paramJx.keySet();
            Iterator<String> iterator = keySet.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                if (paramJx.getString(key) != null) {
                    params.put(key, paramJx.getString(key));
                    paramJson.put(key, paramJx.getString(key));
                }
            }
        }

        JSONObject conjx = oldJson.getJSONObject("currentCondition");
        if (conjx != null && conjx.get("value") != null) {
            currentCondition = new QueryCondition();
            currentCondition.setAlias(conjx.getString("alias"));
            currentCondition.setName(conjx.getString("name"));
            currentCondition.setColumn(conjx.getString("column"));
            currentCondition.setType(conjx.getString("type"));
            currentCondition.setFilter(conjx.getString("filter"));
            currentCondition.setStringValue(conjx.getString("stringValue"));
            currentCondition.setValue(conjx.get("value"));
        }
    }

    Enumeration<?> enumeration = request.getParameterNames();
    while (enumeration.hasMoreElements()) {
        String paramName = (String) enumeration.nextElement();
        String paramValue = getStringValue(request, paramName);
        if (paramName != null) {
            if (StringUtils.isNotEmpty(paramValue)) {
                params.put(paramName, paramValue);
                paramJson.put(paramName, paramValue);
            }
        }
    }

    if (paramMap != null && !paramMap.isEmpty()) {
        if (paramMap != null && paramMap.size() > 0) {
            Set<Entry<String, Object>> entrySet = paramMap.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                String name = entry.getKey();
                Object v = entry.getValue();
                if (name != null && v != null) {
                    params.put(name, v);
                    paramJson.put(name, v);
                }
            }
        }
    }

    if (qt == null) {
        qt = (String) params.get("qt");
    }
    if (qid == null) {
        qid = (String) params.get("qid");
    }
    if (field == null) {
        field = (String) params.get("field");
    }

    /**
     * ??
     */
    if (StringUtils.isNotEmpty(qid)) {
        EntityService entityService = ContextFactory.getBean("entityService");
        /**
         * ?????
         */
        List<Object> rows = entityService.getList(qid, params);
        if (rows != null && rows.size() > 0) {
            for (Object object : rows) {
                if (object instanceof ColumnDefinition) {
                    ColumnDefinition column = (ColumnDefinition) object;
                    query.addColumn(column.getName(), column.getColumnName());
                    if (StringUtils.isNotEmpty(field) && StringUtils.equals(field, column.getName())) {
                        fieldValue = request.getParameter(field);
                        if (StringUtils.isNotEmpty(fieldValue)) {
                            String alias = getStringValue(request, "alias");
                            String filter = getStringValue(request, "filter");
                            if (StringUtils.isEmpty(alias)) {
                                alias = getStringValue(request, field + "_alias");
                            }
                            if (StringUtils.isEmpty(filter)) {
                                filter = getStringValue(request, field + "_filter");
                            }
                            String type = column.getJavaType();
                            if (StringUtils.equalsIgnoreCase(type, "datetime")
                                    || StringUtils.equalsIgnoreCase(type, "Date")) {
                                type = "Date";
                                value = fieldValue;
                                if (StringUtils.isEmpty(filter)) {
                                    filter = SearchFilter.GREATER_THAN_OR_EQUAL;
                                }
                            } else if (StringUtils.equalsIgnoreCase(type, "i4")
                                    || StringUtils.equalsIgnoreCase(type, "Integer")) {
                                type = "Integer";
                                value = Integer.parseInt(fieldValue);
                                if (StringUtils.isEmpty(filter)) {
                                    filter = SearchFilter.GREATER_THAN_OR_EQUAL;
                                }
                            } else if (StringUtils.equalsIgnoreCase(type, "i8")
                                    || StringUtils.equalsIgnoreCase(type, "Long")) {
                                type = "Long";
                                value = Long.parseLong(fieldValue);
                                if (StringUtils.isEmpty(filter)) {
                                    filter = SearchFilter.GREATER_THAN_OR_EQUAL;
                                }
                            } else if (StringUtils.equalsIgnoreCase(type, "r8")
                                    || StringUtils.equalsIgnoreCase(type, "Double")) {
                                type = "Double";
                                value = Double.parseDouble(fieldValue);
                                if (StringUtils.isEmpty(filter)) {
                                    filter = SearchFilter.GREATER_THAN_OR_EQUAL;
                                }
                            } else if (StringUtils.equalsIgnoreCase(type, "String")) {
                                type = "String";
                                value = fieldValue;
                                if (StringUtils.isEmpty(filter)) {
                                    filter = SearchFilter.LIKE;
                                }
                                if (StringUtils.equals(filter, SearchFilter.LIKE)) {
                                    value = "%" + fieldValue + "%";
                                }
                            }
                            if (value != null && filter != null) {
                                currentCondition = new QueryCondition();
                                currentCondition.setType(type);
                                currentCondition.setAlias(alias);
                                currentCondition.setName(field);
                                currentCondition.setColumn(column.getColumnName());
                                currentCondition.setFilter(filter);
                                currentCondition.setStringValue(fieldValue);
                                currentCondition.setValue(value);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * CookieSession??Ta???
     */
    if (oldJson != null) {
        JSONArray array = oldJson.getJSONArray("conditions");
        if (array != null) {
            // logger.debug("previous conditions:" + array.toJSONString());
            int size = array.size();
            for (int i = 0; i < size; i++) {
                JSONObject json = array.getJSONObject(i);
                QueryCondition c = new QueryCondition();
                c.setAlias(json.getString("alias"));
                c.setName(json.getString("name"));
                c.setColumn(json.getString("column"));
                c.setType(json.getString("type"));
                c.setFilter(json.getString("filter"));
                String val = json.getString("stringValue");

                if (StringUtils.equals(c.getType(), "Date")) {
                    c.setValue(DateUtils.toDate(val));
                    c.setStringValue(val);
                } else if (StringUtils.equals(c.getType(), "Integer")) {
                    c.setValue(Integer.parseInt(val));
                    c.setStringValue(val);
                } else if (StringUtils.equals(c.getType(), "Long")) {
                    c.setValue(Long.parseLong(val));
                    c.setStringValue(val);
                } else if (StringUtils.equals(c.getType(), "Double")) {
                    c.setValue(Double.parseDouble(val));
                    c.setStringValue(val);
                } else if (StringUtils.equals(c.getType(), "Boolean")) {
                    c.setValue(Boolean.valueOf(val));
                    c.setStringValue(val);
                } else {
                    c.setValue(json.get("value"));
                    c.setStringValue(val);
                }

                if (!conditions.contains(c)) {
                    conditions.add(c);
                }
            }
        }
        /**
         * ?
         */
        if (removeLast && conditions.size() > 0) {
            conditions.remove(conditions.size() - 1);
        }
    }

    /**
     * ????
     */
    if (StringUtils.equals("R", qt)) {
        logger.debug("#### clear conditions");
        conditions.clear();
    }

    if (currentCondition != null && currentCondition.getValue() != null) {
        query.setCurrentQueryCondition(currentCondition);
        if (!conditions.contains(currentCondition)) {
            conditions.add(currentCondition);
        }
        JSONObject json = new JSONObject();
        if (currentCondition.getAlias() != null) {
            json.put("alias", currentCondition.getAlias());
        }
        json.put("name", currentCondition.getName());
        json.put("column", currentCondition.getColumn());
        json.put("type", currentCondition.getType());
        json.put("filter", currentCondition.getFilter());
        json.put("value", currentCondition.getValue());
        json.put("stringValue", currentCondition.getStringValue());
        json.put("index", 0);
        rootJson.put("currentCondition", json);
    }

    if (conditions.size() > 0) {
        JSONArray jsonArray = new JSONArray();
        int index = 0;
        for (QueryCondition c : conditions) {
            if (c.getValue() != null) {
                JSONObject json = new JSONObject();
                if (c.getAlias() != null) {
                    json.put("alias", c.getAlias());
                }
                json.put("name", c.getName());
                json.put("column", c.getColumn());
                json.put("type", c.getType());
                json.put("filter", c.getFilter());
                json.put("value", c.getValue());
                json.put("stringValue", c.getStringValue());
                json.put("index", index++);
                jsonArray.add(json);
            }
        }
        rootJson.put("conditions", jsonArray);
    }

    rootJson.put("query", queryJson);
    rootJson.put("params", paramJson);

    String jsonText = rootJson.toJSONString();
    logger.debug("prepare query json:\n" + jsonText);

    jsonText = Hex.bytesToHex(jsonText.getBytes());

    if (response != null) {
        Cookie cookie = new Cookie(cookieKey, jsonText);
        response.addCookie(cookie);
    }

    query.setParameter(params);
    query.getParameters().putAll(params);

    logger.debug("#conditions:" + conditions);

    for (QueryCondition condition : conditions) {
        query.addCondition(condition);
    }

    return query;
}

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

/**
 * Servlet's doPost: processes a POST request. Controls the overall 
 * kerberos silent authentication process. It supports both the Security 
 * Framework's SAML and Forms Based interface.
 * <p>//from w  ww.  jav a  2s.c  om
 * You can find more information on the Security Framework's Kerberos guide 
 * about the scenarios implemented here
 * 
 * @param request HTTP request
 * @param response HTTP response
 * 
 * @throws ServletException
 * @throws IOException
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.debug("Kerberos servlet");

    if (gsaValveConfigPath == null) {
        if (request.getAttribute("gsaValveConfigPath") == null) {
            //Read parameter from config file: SAML
            gsaValveConfigPath = readValveConfigPath();
        } else {
            gsaValveConfigPath = request.getAttribute("gsaValveConfigPath").toString();
        }
    }

    logger.debug("Valve Config Path is: " + gsaValveConfigPath);

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    //Authentication Processes 
    AuthenticationProcessImpl authenticationProcessCls = null;
    KerberosAuthenticationProcess krbAuthN = new KerberosAuthenticationProcess();

    //Initialize cookies vars
    Cookie gsaRefererCookie = null;
    Cookie gsaAuthCookie = null;

    //Session Cookie arrays
    Vector<Cookie> krbCookies = new Vector<Cookie>();
    Vector<Cookie> nonKrbCookies = new Vector<Cookie>();

    //user agent
    String userAgent = null;

    //user credentials
    Credentials creds = null;

    //User Session and Session ID vars definition
    UserSession userSession = null;
    String sessionID = null;
    String encodedSessionID = null;

    //Create the credentials store
    try {
        this.valveConf = ValveConfigurationInstance.getValveConfig(gsaValveConfigPath);
    } catch (ValveConfigurationException e) {
        logger.error("Valve Config instantiation error: " + e);
    }

    logger.debug("Creating the credentials store");
    creds = new Credentials();
    String username = null;

    //Setting Valve parameters
    logger.debug("Setting Valve params");
    setValveParams(request);

    //Protection
    if ((!isKerberos) || (!isNegotiate)) {
        logger.error(
                "Configuration error: if you want to use Kerberos silent AuthN, isKerberos and isNegotiate config vars have to be set to true");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Configuration error - Kerberos is not set properly");
        return;
    }

    Cookie cookies[] = null;

    // Retrieve cookies
    cookies = request.getCookies();

    // Protection: look for auth and referer cookies
    if (cookies != null) {

        // Look for the referer cookie
        for (int i = 0; i < cookies.length; i++) {

            // Look for the referer cookie
            if ((cookies[i].getName()).equals(refererCookieName)) {

                // Cache cookie
                gsaRefererCookie = cookies[i];

                logger.debug("Referer cookie already exists: " + gsaRefererCookie.getValue());

            } else {
                // Look for the auth cookie
                if ((cookies[i].getName()).equals(authCookieName)) {

                    // Cache cookie
                    gsaAuthCookie = cookies[i];

                    logger.debug("Auth cookie already exists: " + gsaAuthCookie.getValue());

                }
            }

            if ((gsaRefererCookie != null) && (gsaAuthCookie != null)) {
                // Exit
                break;
            }

        }

    }

    // Protection
    if (!isSAML) {
        if (gsaRefererCookie == null) {

            // Raise error
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "The GSA authentication servlet couldn't read the referer cookie");

            // Log error
            logger.error(
                    "The GSA authentication servlet couldn't read the referer cookie, pls. check the cookie domain value");

            // Return
            return;

        }
    } else {
        //SAML

        //Get SAML Params
        relayState = request.getParameter("RelayState");
        samlRequest = request.getParameter("SAMLRequest");
        //String relayStateCookie = valveConf.getSAMLConfig().getRelayStateCookie();
        boolean noParams = false;
        boolean cookieExist = true;

        //Protection
        if ((relayState == null) || (relayState.equals(""))) {
            noParams = true;
        } else {
            if ((samlRequest == null) || (samlRequest.equals(""))) {
                noParams = true;
            }
        }

        createRefererCookie(gsaRefererCookie);

        //if ((noParams)&&(!cookieExist)) {
        if (noParams) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request");
            return;
        }
    }

    logger.debug("Let's validate if gsaAuthCookie is present");

    if (gsaAuthCookie != null) {

        if (!isSAML) {
            //redirect
            String redirect = gsaRefererCookie.getValue();

            logger.debug("redirect is " + redirect);
            //redirect only if the URL is different than the login one                    
            if (!redirect.equals(loginUrl)) {

                //user properly authenticated
                logger.debug("The user was properly authenticated. Lets redirect to..." + redirect);

                // Redirect
                response.sendRedirect(redirect);

            } else {
                logger.debug("It's the login URL. No redirect");
            }
        } else {
            logger.debug("As this is SAML. Let's obviate the previous authentication cookie");
            gsaAuthCookie = null;
        }
    }

    userSession = new UserSession();

    Sessions sessions = Sessions.getInstance();
    sessions.setMaxSessionAgeMinutes(maxSessionAge);
    sessions.setSessionTimeoutMinutes(sessionTimeout);

    if (gsaAuthCookie == null) {

        logger.debug("gsaAuthCookie does not exist");

        isNegotiate = true;

        // Read User-Agent header
        userAgent = request.getHeader("User-Agent");

        logger.debug("userAgent is... " + userAgent);

        //check if user is gsa-crawler
        if (userAgent.startsWith(GSA_CRAWLER_USER)) {

            logger.debug("User is " + GSA_CRAWLER_USER);

            //check if user is gsa-crawler and have to authenticate it thru a form                                  
            if (KrbUsrPwdCrawler) {

                logger.debug("gsa-crawler has to access thru username and password");

                //check if crawler already provided credentials

                if (request.getParameter("UserIDKrb") == null) {

                    //the login page have to be filled in by the admin user before reaching here. Return error
                    logger.error("The login page [" + KrbUsrPwdCrawlerUrl
                            + "] has to be invoked and its credentials fields filled in before reaching here");
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "It means the GSA Valve Kerberos configuration is not done properly or you just forgot to fill in the Kerberos credentials in the login page");
                    return;

                } else {

                    //user already submits credentials
                    logger.debug("Crawler has already sent credentials");
                    //set isNegotiate equal false (it authenticates the user thru username and pwd credentials)                                                                                    
                    isNegotiate = false;

                    //set Crawler credentials
                    setCrawlerCredentials(request, creds, KrbAdditionalAuthN);

                    //authenticate user
                    statusCode = krbAuthentication(request, response, krbAuthN, krbCookies,
                            gsaRefererCookie.getValue(), creds, isNegotiate);

                    // Protection: check status code
                    if (statusCode != HttpServletResponse.SC_OK) {

                        // Raise error
                        response.sendError(statusCode, "Authentication process failed!");

                        // Debug
                        if (logger.isDebugEnabled())
                            logger.debug("Krb Authentication process failed with code: " + statusCode);

                        if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
                            logger.debug(
                                    "Note: this 401 could not be an error as sending 401 could be part of the Negotiation process");
                        }

                        // Return
                        return;

                    }

                    //check if the additional authN method is available. If so, start authN with these creds as well
                    //N: modification for always lanching the root authN process. Comment out the following line
                    //if (KrbAdditionalAuthN) {

                    statusCode = nonKrbAuthentication(request, response, authenticationProcessCls,
                            nonKrbCookies, gsaRefererCookie.getValue(), creds);

                    //check if the status code is indeterminate
                    if (statusCode == -1) {
                        //the process could not determinate the authorization
                        //as there is no pattern that matches with any repository
                        statusCode = HttpServletResponse.SC_UNAUTHORIZED;
                    }

                    // Protection: check status code
                    if (statusCode != HttpServletResponse.SC_OK) {

                        // Raise error
                        response.sendError(statusCode, "Authentication process failed!");

                        // Debug
                        if (logger.isDebugEnabled())
                            logger.debug("Non Krb Authentication process failed with code: " + statusCode);

                        // Return
                        return;

                    }

                    //}

                }
            } else { // end KrbUsrPwdCrawler is set. 
                //If KrbUsrPwdCrawler is not set to true, then do nothing (assume content is feeded)
                //just send back the error as a configuration one (we shouldn't configure Froms-based crawling)
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Configuration error. Review your configuration as you can not define this rule if it's not set properly (see doc on how to set it up using Kerberos config attributes)");
                return;
            }

        } else { //User is not Crawler

            logger.debug("User is NOT crawler");

            //check if we have double AuthN or not
            if (!KrbAdditionalAuthN) {

                logger.debug("Krb silent authN only");

                //set isNegotiate equal true (it authenticates the user thru kerberos ticket)                                                                                    
                isNegotiate = true;

                String refererCookieValue = null;
                if (gsaRefererCookie != null) {
                    refererCookieValue = new String(gsaRefererCookie.getValue());
                }

                //authenticate user
                statusCode = krbAuthentication(request, response, krbAuthN, krbCookies, refererCookieValue,
                        creds, isNegotiate);

                // Protection: check status code
                if (statusCode != HttpServletResponse.SC_OK) {

                    // Raise error
                    response.sendError(statusCode, "Authentication process failed!");

                    // Debug
                    if (logger.isDebugEnabled())
                        logger.debug("Krb Authentication process failed with code: " + statusCode);

                    if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
                        logger.debug(
                                "Note: this 401 could not be an error as sending 401 could be part of the Negotiation process");
                    }

                    // Return
                    return;

                } else {

                    boolean doesKrbSubjectExist = lookForKrbCreds(creds);

                    if (!doesKrbSubjectExist) {
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Credentials not valid. Try to close your browser and try it again");

                        // Log error
                        logger.error("Kerberos Subject is not present when authenticating");

                        // Return
                        return;
                    }

                    //N: call rootAuthN once we have the Kerberos creds
                    //N: Begin update
                    if (!KrbAdditionalAuthN) {
                        statusCode = nonKrbAuthentication(request, response, authenticationProcessCls,
                                nonKrbCookies, refererCookieValue, creds);

                        //check if the status code is indeterminate
                        if (statusCode == -1) {
                            //the process could not determinate the authorization
                            //as there is no pattern that matches with any repository
                            statusCode = HttpServletResponse.SC_UNAUTHORIZED;
                        }

                        // Protection: check status code
                        if (statusCode != HttpServletResponse.SC_OK) {

                            // Raise error
                            response.sendError(statusCode, "Authentication process failed!");

                            // Debug
                            if (logger.isDebugEnabled())
                                logger.debug("Non Krb Authentication process failed with code: " + statusCode);

                            // Return
                            return;
                        }

                    }
                    //N:End update

                }

            } else { //Double AuthN required. So that apart from the Krb silent authN, we authN the user as well thru username and pwd

                logger.debug("Krb and Forms based AuthN mechanisms");

                //check if Krb credentials are already set
                Cookie gsaKrbCookie = getCookie(request, KRB_COOKIE_NAME);

                //if (gsaKrbCookie != null) { //Kerberos cookie set
                if (!isKrbProcess(gsaKrbCookie)) { //Kerberos cookie set    

                    logger.debug("Krb cookie is set. Krb AuthN already in place");

                    Subject krbSubj = getKrbSubject(gsaKrbCookie.getValue());

                    //Protection
                    if (krbSubj == null) { // couldn't localize the subject. 

                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Credentials not valid. Try to close your browser and try it again");

                        // Log error
                        logger.error("Kerberos Subject is not present when authenticating");

                        // Return
                        return;
                    } else {

                        logger.debug("The Krb subject exists. This is the Forms based AuthN part");

                        //check if parameters are present
                        if (request.getParameter("UserIDKrb") == null) {

                            logger.debug("Login page has not been already invoked");

                            String redirectUrl = contructKrbLoginURL();

                            logger.debug("Redirecting to...." + redirectUrl);

                            //redirect to the login page
                            response.sendRedirect(response.encodeRedirectURL(redirectUrl));

                            // Return
                            return;

                        } else {

                            //user already submits credentials
                            logger.debug("User has already sent credentials");

                            createCredsDoubleAuthN(request, creds, krbSubj);

                            logger.debug("User Credentials created. Let's authenticate the user without Krb");

                            statusCode = nonKrbAuthentication(request, response, authenticationProcessCls,
                                    nonKrbCookies, gsaRefererCookie.getValue(), creds);

                            //check if the status code is indeterminate
                            if (statusCode == -1) {
                                //the process could not determinate the authorization
                                //as there is no pattern that matches with any repository
                                statusCode = HttpServletResponse.SC_UNAUTHORIZED;
                            }

                            // Protection: check status code
                            if (statusCode != HttpServletResponse.SC_OK) {

                                // Raise error
                                response.sendError(statusCode, "Authentication process failed!");

                                // Debug
                                if (logger.isDebugEnabled())
                                    logger.debug(
                                            "Non Krb Authentication process failed with code: " + statusCode);

                                // Return
                                return;

                            }
                            boolean resultDelete = deleteKrbSubject(gsaKrbCookie.getValue());
                            if (!resultDelete) {
                                logger.error("Not KrbSubj found when deleting it");
                            }

                        }
                    }

                } else { //Krb cookie does not exist
                    logger.debug(
                            "Krb cookie does not exist. Let's silently authenticate the user thru Krb firstly");
                    logger.debug("Krb silent authN only");

                    //set isNegotiate equal true (it authenticates the user thru kerberos ticket)                                                                                    
                    isNegotiate = true;

                    //authenticate user
                    statusCode = krbAuthentication(request, response, krbAuthN, krbCookies,
                            gsaRefererCookie.getValue(), creds, isNegotiate);

                    // Protection: check status code
                    if (statusCode != HttpServletResponse.SC_OK) {

                        // Raise error
                        response.sendError(statusCode, "Authentication process failed!");

                        // Debug
                        if (logger.isDebugEnabled())
                            logger.debug("Krb Authentication process failed with code: " + statusCode);

                        if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
                            logger.debug(
                                    "Note: this 401 could not be an error as sending 401 could be part of the Negotiation process");
                        }

                        // Return
                        return;

                    } else {
                        Cookie krbCookie = krbCookies.elementAt(0);
                        String krbAuthCookieValue = krbCookie.getValue();

                        logger.debug("Krb cookie value: " + krbAuthCookieValue);
                        if (krbAuthCookieValue == null) {
                            logger.error("Krb cookie not present");
                            // Raise error
                            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Kerberos cookie not present");
                            // Return
                            return;
                        } else {
                            addKrbCookie(response, krbCookie);
                            addKrbSubject(krbAuthCookieValue, krbAuthN.getUserSubject());
                            logger.debug(
                                    "The User Krb identity is already present. Let's authenticate the user thru username/password");
                            //redirect to Login page
                            String redirectUrl = contructKrbLoginURL();
                            response.sendRedirect(response.encodeRedirectURL(redirectUrl));
                            logger.debug("Redirect to.... " + redirectUrl);
                            return;
                        }

                    }

                }

            }
        }

        logger.debug("Krb and/or Forms based AuthN OK. Let's create the session");

        //set username and cookies
        username = creds.getCredential(KRB5_ID).getUsername();

        //creation time var
        long creationTime = System.currentTimeMillis();

        //Setting session values
        sessionID = UserIDEncoder.getID(username, creationTime);
        encodedSessionID = URLEncoder.encode(sessionID, encoder);

        logger.debug("Krb Username is... " + username);

        // setSession                                               
        boolean sessionOk = settingSession(userSession, gsaAuthCookie, creds, username, krbAuthN, creationTime,
                encodedSessionID, krbCookies, nonKrbCookies);

        logger.debug("Session is .... " + sessionOk);

        if (!sessionOk) {
            //SAML
            statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
            response.setStatus(statusCode);

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

            // Return
            return;
        } else {
            //Store Session in the Session Map
            sessions.addSession(sessionID, userSession);

            sessions.setMaxSessionAgeMinutes(maxSessionAge);

            if (isSessionEnabled) {
                sessions.setSessionTimeoutMinutes(sessionTimeout);
            } else {
                sessions.setSessionTimeoutMinutes(-1);
            }

            logger.debug("User Session created");

            // Add internal authentication cookie
            response.addCookie(gsaAuthCookie);

            logger.debug("Auth cookie added");

            // Debug
            if (logger.isDebugEnabled())
                logger.debug("Authentication process successful");

            if (!isSAML) {
                // Debug
                if (logger.isDebugEnabled())
                    logger.debug("Redirecting user to: " + gsaRefererCookie.getValue());

                // Redirect
                response.sendRedirect(gsaRefererCookie.getValue());
            } else {
                try {
                    redirectingSAML(response, cookies, sessionID);
                } catch (ValveConfigurationException e) {
                    logger.error("Configuration error: " + e.getMessage(), e);
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }
            }

        }

    } //end of AuthN cases

}

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  . ja  v  a2 s .  c om
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);
    }
}