Example usage for javax.servlet.http Cookie setPath

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

Introduction

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

Prototype

public void setPath(String uri) 

Source Link

Document

Specifies a path for the cookie to which the client should return the cookie.

Usage

From source file:com.ssbusy.controller.catalog.CategoryController.java

@Override
@SuppressWarnings("unchecked")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    ModelAndView model = new ModelAndView();
    MyCustomer customer = (MyCustomer) CustomerState.getCustomer();

    HttpSession session = request.getSession();
    MyOfferCode myOfferCode = (MyOfferCode) session.getAttribute("bonusOfferCode");
    Boolean w_flag = Boolean.FALSE;
    // cookies//from   www  .j  a  v a  2s .  co  m
    String dateTime = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
    int count = 0;// ??
    Cookie cookies[] = request.getCookies();
    Boolean uiv2 = null;
    if (cookies != null) {
        for (Cookie c : cookies) {
            if (dateTime.equals(c.getName())) {
                count = Integer.valueOf(c.getValue());
                break;
                // } else if ("uiv2".equals(c.getName())) {
                // uiv2 = Boolean.valueOf(c.getValue()); // 2 cookie
            }
        }
    }
    if (cookies != null) {
        for (Cookie c : cookies) {
            if ("SPRING_SECURITY_REMEMBER_ME_COOKIE".equals(c.getName())) {
                model.addObject("rember", c.getValue());
                break;
            }
        }
    }
    // String uiParam = request.getParameter("uiv2");
    // if (StringUtils.isNotEmpty(uiParam)) { // 1 param
    // uiv2 = Boolean.valueOf(uiParam);
    // Cookie c = new Cookie("uiv2", uiv2.toString());
    // c.setPath("/");
    // c.setMaxAge(60 * 60 * 24 * 360);
    // response.addCookie(c);
    // } else if (uiv2 == null) {
    uiv2 = Boolean.TRUE; // 3 default. 
    // }
    session.setAttribute("uiv2", uiv2);
    // LOG.warn("uiv2=" + uiv2);

    if (myOfferCode != null) {
        if (customer.isRegistered())
            giftService.updateOwnerCustomer(customer, myOfferCode);
        else
            myOfferCode = null;
    } else if (count < maxoffercodeCount) {
        myOfferCode = giftService.getgift(customer);
        if (myOfferCode != null) {
            if (customer.isAnonymous()) {
                session.setAttribute("bonusOfferCode", myOfferCode);
                model.addObject("bonusOfferCode", myOfferCode);
                myOfferCode = null;
            }
        }
    }
    if (myOfferCode != null) {
        session.removeAttribute("bonusOfferCode");
        model.addObject("bonusOfferCode", myOfferCode);
        Cookie c = new Cookie(dateTime, String.valueOf(count + 1));
        c.setPath("/");
        c.setMaxAge(60 * 60 * 24);
        response.addCookie(c);
        LOG.info("offerCode sent, id=" + myOfferCode.getId() + ", ip=" + request.getRemoteAddr());
    }

    if (request.getParameterMap().containsKey("facetField")) {
        // If we receive a facetField parameter, we need to convert the
        // field to the
        // product search criteria expected format. This is used in
        // multi-facet selection. We
        // will send a redirect to the appropriate URL to maintain canonical
        // URLs

        String fieldName = request.getParameter("facetField");
        List<String> activeFieldFilters = new ArrayList<String>();
        Map<String, String[]> parameters = new HashMap<String, String[]>(request.getParameterMap());
        for (Iterator<Entry<String, String[]>> iter = parameters.entrySet().iterator(); iter.hasNext();) {
            Map.Entry<String, String[]> entry = iter.next();
            String key = entry.getKey();
            if (key.startsWith(fieldName + "-")) {
                activeFieldFilters.add(key.substring(key.indexOf('-') + 1));
                iter.remove();
            }
        }

        parameters.remove(ProductSearchCriteria.PAGE_NUMBER);
        parameters.put(fieldName, activeFieldFilters.toArray(new String[activeFieldFilters.size()]));
        parameters.remove("facetField");

        String newUrl = ProcessorUtils.getUrl(request.getRequestURL().toString(), parameters);
        model.setViewName("redirect:" + newUrl);
    } else {
        // Else, if we received a GET to the category URL (either the user
        // clicked this link or we redirected
        // from the POST method, we can actually process the results

        Category category = (Category) request
                .getAttribute(CategoryHandlerMapping.CURRENT_CATEGORY_ATTRIBUTE_NAME);
        assert (category != null);

        List<SearchFacetDTO> availableFacets = searchService.getCategoryFacets(category);
        ProductSearchCriteria searchCriteria = facetService.buildSearchCriteria(request, availableFacets);

        String searchTerm = request.getParameter(ProductSearchCriteria.QUERY_STRING);
        ProductSearchResult result;

        List<FulfillmentLocation> locations = null;
        try {
            // 
            if (customer != null && customer.getRegion() != null) {
                InventorySolrSearchServiceExtensionHandler.customerLocation
                        .set(locations = customer.getRegion().getFulfillmentLocations());
            }
            if (StringUtils.isNotBlank(searchTerm)) {
                result = searchService.findProductsByCategoryAndQuery(category, searchTerm, searchCriteria);
            } else {
                result = searchService.findProductsByCategory(category, searchCriteria);
            }
        } finally {
            InventorySolrSearchServiceExtensionHandler.customerLocation.remove();
        }

        facetService.setActiveFacetResults(result.getFacets(), request);
        List<Product> products = result.getProducts();

        if (products != null && products.size() > 0) {
            List<String> prodIds = new ArrayList<String>(products.size());
            for (Product product : products) {
                prodIds.add(String.valueOf(product.getId()));
            }
            model.addObject("ratingSums", ratingService.readRatingSummaries(prodIds, RatingType.PRODUCT));

            // ?productinventories
            if (locations != null) {
                Map<Product, List<Inventory>> invs = inventoryService.listAllInventories(products, locations);
                model.addObject("inventories", invs);
            }
        }

        model.addObject(PRODUCTS_ATTRIBUTE_NAME, products);
        model.addObject(CATEGORY_ATTRIBUTE_NAME, category);
        // facets
        List<SearchFacetDTO> facets = result.getFacets();
        if (facets != null) {
            _nextFact: for (Iterator<SearchFacetDTO> itr = facets.iterator(); itr.hasNext();) {
                SearchFacetDTO dto = itr.next();
                if (dto != null && dto.getFacetValues() != null) {
                    for (SearchFacetResultDTO searchFacetDTO : dto.getFacetValues()) {
                        if (searchFacetDTO != null)
                            if (searchFacetDTO.getQuantity() != null && searchFacetDTO.getQuantity() > 0)
                                continue _nextFact;
                    }
                }
                itr.remove();
            }
            model.addObject(FACETS_ATTRIBUTE_NAME, result.getFacets());
        }
        model.addObject(PRODUCT_SEARCH_RESULT_ATTRIBUTE_NAME, result);

        // TODO temp
        String view = category.getDisplayTemplate();
        if (StringUtils.isEmpty(view))
            view = getDefaultCategoryView();
        if (request.getRequestURI().startsWith("/weixin/")) {
            view = "weixin/catalog/w_category_item";
            w_flag = Boolean.TRUE;
        }
        if (uiv2) {
            if ("layout/home".equals(view))
                view = "v2/home";
            else {
                if (!view.startsWith("activity") && !view.startsWith("weixin/")) {
                    view = "v2/" + view;
                }

            }
        }
        session.setAttribute("w_flag", w_flag);
        model.setViewName(view);
    }
    // if (isAjaxRequest(request)) {
    // model.setViewName(RETURN_PRODUCT_WATERFALL_ITEM);
    // model.addObject("ajax", Boolean.TRUE);
    // }
    return model;
}

From source file:org.jahia.params.valves.CookieAuthValveImpl.java

public void invoke(Object context, ValveContext valveContext) throws PipelineException {
    if (!isEnabled()) {
        valveContext.invokeNext(context);
        return;//from   w w  w  . j a  v a2s .c o  m
    }

    AuthValveContext authContext = (AuthValveContext) context;
    JCRUserNode jahiaUser = null;
    // now lets look for a cookie in case we are using cookie-based
    // authentication.
    Cookie[] cookies = cookieAuthConfig.isActivated() ? authContext.getRequest().getCookies() : null;
    if (cookies == null) {
        // no cookies at all sent by the client, let's go to the next
        // valve.
        valveContext.invokeNext(context);
        return;
    }
    // we first need to find the authentication cookie in the list.
    Cookie authCookie = null;
    for (Cookie curCookie : cookies) {
        if (cookieAuthConfig.getCookieName().equals(curCookie.getName())) {
            // found it.
            authCookie = curCookie;
            break;
        }
    }
    if (authCookie != null) {
        // now we need to look in the database to see if we have a
        // user that has the corresponding key.
        Properties searchCriterias = new Properties();
        String userPropertyName = cookieAuthConfig.getUserPropertyName();
        String value = authCookie.getValue();
        String realm = null;
        if (value.contains(":")) {
            realm = StringUtils.substringAfter(value, ":");
            value = StringUtils.substringBefore(value, ":");
        }
        if (value.equals("deleted")) {
            valveContext.invokeNext(context);
            return;
        }
        searchCriterias.setProperty(userPropertyName, value);
        Set<JCRUserNode> foundUsers = null;
        try {
            foundUsers = ServicesRegistry.getInstance().getJahiaUserManagerService().searchUsers(
                    searchCriterias, realm, null,
                    JCRSessionFactory.getInstance().getCurrentSystemSession("live", null, null));
            if (foundUsers.size() == 1) {
                jahiaUser = foundUsers.iterator().next();
                if (jahiaUser.isAccountLocked()) {
                    jahiaUser = null;
                } else {
                    HttpSession session = authContext.getRequest().getSession(false);
                    if (session != null) {
                        session.setAttribute(Constants.SESSION_USER, jahiaUser.getJahiaUser());
                    }

                    if (cookieAuthConfig.isRenewalActivated()) {
                        createAndSendCookie(authContext, jahiaUser, cookieAuthConfig);
                    }
                }
            } else {
                authCookie = new Cookie(cookieAuthConfig.getCookieName(), "deleted");
                authCookie.setPath(StringUtils.isNotEmpty(authContext.getRequest().getContextPath())
                        ? authContext.getRequest().getContextPath()
                        : "/");
                authCookie.setMaxAge(0);
                authCookie.setHttpOnly(cookieAuthConfig.isHttpOnly());
                authCookie.setSecure(cookieAuthConfig.isSecure());
                authContext.getResponse().addCookie(authCookie);
            }
        } catch (RepositoryException e) {
            logger.error("Error while searching for users", e);
        }
    }
    if (jahiaUser == null) {
        valveContext.invokeNext(context);
    } else {
        if (authContext.getRequest().getSession(false) != null) {
            authContext.getRequest().getSession().invalidate();
        }
        authContext.getSessionFactory().setCurrentUser(jahiaUser.getJahiaUser());

        try {
            jahiaUser.setProperty(Constants.JCR_LASTLOGINDATE, String.valueOf(System.currentTimeMillis()));
            jahiaUser.save();
        } catch (RepositoryException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

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

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

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

    ObjectMapper mapper = new ObjectMapper();

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

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

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

        try {

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

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

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

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

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

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

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

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

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

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

        httpServletResponse.sendRedirect(login_url);
    }
}

From source file:org.apache.coyote.tomcat5.CoyoteRequest.java

/**
 * Configures the given JSESSIONID cookie.
 *
 * @param cookie The JSESSIONID cookie to be configured
 *///from w ww  .j a  va  2s.  co m
protected void configureSessionCookie(Cookie cookie) {
    cookie.setMaxAge(-1);
    String contextPath = null;
    if (getContext() != null) {
        contextPath = getContext().getPath();
    }
    if ((contextPath != null) && (contextPath.length() > 0)) {
        cookie.setPath(contextPath);
    } else {
        cookie.setPath("/");
    }
    if (isSecure()) {
        cookie.setSecure(true);
    }
}

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

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

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

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

        int i = 0;

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

            cookie.setComment(c.getComment());

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

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

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

From source file:org.b3log.symphony.service.UserMgmtService.java

/**
 * Tries to login with cookie./*from ww  w .ja v a  2 s  .co m*/
 *
 * @param request the specified request
 * @param response the specified response
 * @return returns {@code true} if logged in, returns {@code false} otherwise
 */
public boolean tryLogInWithCookie(final HttpServletRequest request, final HttpServletResponse response) {
    final Cookie[] cookies = request.getCookies();
    if (null == cookies || 0 == cookies.length) {
        return false;
    }

    try {
        for (final Cookie cookie : cookies) {
            if (!"b3log-latke".equals(cookie.getName())) {
                continue;
            }

            final JSONObject cookieJSONObject = new JSONObject(cookie.getValue());

            final String userId = cookieJSONObject.optString(Keys.OBJECT_ID);
            if (Strings.isEmptyOrNull(userId)) {
                break;
            }

            final JSONObject user = userRepository.get(userId);
            if (null == user) {
                break;
            }

            final String ip = Requests.getRemoteAddr(request);

            if (UserExt.USER_STATUS_C_INVALID == user.optInt(UserExt.USER_STATUS)
                    || UserExt.USER_STATUS_C_INVALID_LOGIN == user.optInt(UserExt.USER_STATUS)) {
                Sessions.logout(request, response);

                updateOnlineStatus(userId, ip, false);

                return false;
            }

            final String userPassword = user.optString(User.USER_PASSWORD);
            final String password = cookieJSONObject.optString(Common.TOKEN);
            if (userPassword.equals(password)) {
                Sessions.login(request, response, user);

                updateOnlineStatus(userId, ip, true);

                LOGGER.log(Level.DEBUG, "Logged in with cookie[email={0}]", userId);

                return true;
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.WARN, "Parses cookie failed, clears the cookie[name=b3log-latke]", e);

        final Cookie cookie = new Cookie("b3log-latke", null);
        cookie.setMaxAge(0);
        cookie.setPath("/");

        response.addCookie(cookie);
    }

    return false;
}

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

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

    ObjectMapper mapper = new ObjectMapper();

    switch (service) {

    case "login": {

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

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

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

                // AuthorizationInterface.revokeToken()
                try {

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

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

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

                // cleanup variable
                access_token = "";
            }

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

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

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

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

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

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

                    if (params.length > 1) {

                        loginRequest = new LoginRequest();

                        for (String param : params) {

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

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

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

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

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

                    scope = loginRequest.getScope();
                }

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

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

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

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

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

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

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

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

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

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

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

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

                        try {

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

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

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

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

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

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

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

                        httpServletResponse.sendRedirect(redirect_url);
                    }
                } else {

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

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

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

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

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

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

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

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

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

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

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

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

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

                    try {

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

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

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

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

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

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

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

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

        break;
    }
    case "logout": {

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

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

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

                // AuthorizationInterface.revokeToken()
                try {

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

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

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

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

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

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

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

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

                httpServletResponse.sendRedirect(redirect_url);
            }

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

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

        } else {

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

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

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

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

        break;
    }
    case "change": {

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

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

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

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

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

                try {

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

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

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

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

        if (!isAuthorized) {

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

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

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

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

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

                    boolean isChanged = libraryManagementSystem.changePassword(changeRequest);

                    if (isChanged) {

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

                        try {

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

                        } catch (MessagingException e1) {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        break;
    }
    case "renew": {

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

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

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

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

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

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

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

                    if (isRenewed) {

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

                        try {

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

                        } catch (MessagingException e1) {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                e.printStackTrace();

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

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

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

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

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

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

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

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

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

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

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

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

        break;
    }
    default: {

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

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

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

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

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

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

From source file:net.lightbody.bmp.proxy.jetty.http.HttpRequest.java

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

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

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

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

        int version = 0;
        Cookie cookie = null;

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

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

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

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

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

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

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

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

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

    return _cookies;
}