Example usage for javax.servlet.http Cookie getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the cookie.

Usage

From source file:de.tu_dortmund.ub.api.paaa.PaaaEndpoint.java

protected void doDelete(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    ObjectMapper mapper = new ObjectMapper();

    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "PathInfo = "
            + httpServletRequest.getPathInfo());
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "QueryString = "
            + httpServletRequest.getQueryString());

    String patronid = "";
    String service = "";
    String accept = "";
    String authorization = "";

    String format = "json";

    String path = httpServletRequest.getPathInfo();
    String[] params = path.substring(1, path.length()).split("/");

    if (params.length == 1) {
        patronid = params[0];/* www .j  a  v  a 2 s .  co  m*/
        service = "deletepatron";
    } else if (params.length == 2) {
        patronid = params[0];
        service = params[1];
    }

    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Patron: " + patronid);
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Service: " + service);

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

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

        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerNameKey = headerNames.nextElement();

            if (headerNameKey.equals("Accept")) {

                this.logger.debug("headerNameKey = " + httpServletRequest.getHeader(headerNameKey));

                if (httpServletRequest.getHeader(headerNameKey).contains("text/html")) {
                    format = "html";
                } else if (httpServletRequest.getHeader(headerNameKey).contains("application/xml")) {
                    format = "xml";
                } else if (httpServletRequest.getHeader(headerNameKey).contains("application/json")) {
                    format = "json";
                }
            }
        }
    }

    this.logger.info("format = " + format);

    if (!format.equals("json") && !format.equals("xml")) {

        this.logger.error("[" + this.config.getProperty("service.name") + "] "
                + HttpServletResponse.SC_BAD_REQUEST + ": " + format + " not implemented!");

        // 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);
    } else {
        // PAAA - function
        if (service.equals("deletepatron")) {

            // get 'Accept' and 'Authorization' from Header;
            Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
            while (headerNames.hasMoreElements()) {

                String headerNameKey = (String) headerNames.nextElement();
                this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "headerNameKey = "
                        + headerNameKey + " / headerNameValue = "
                        + httpServletRequest.getHeader(headerNameKey));

                if (headerNameKey.equals("Accept")) {
                    accept = httpServletRequest.getHeader(headerNameKey);
                }
                if (headerNameKey.equals("Authorization")) {
                    authorization = httpServletRequest.getHeader(headerNameKey);
                }
            }

            this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Accept: " + accept);
            this.logger.debug(
                    "[" + this.config.getProperty("service.name") + "] " + "Authorization: " + authorization);

            // if not exists token: read request parameter
            if (authorization.equals("") && httpServletRequest.getParameter("access_token") != null
                    && !httpServletRequest.getParameter("access_token").equals("")) {
                authorization = httpServletRequest.getParameter("access_token");
            }

            // if not exists token
            if (authorization.equals("")) {

                // if exists PaiaService-Cookie: read content
                Cookie[] cookies = httpServletRequest.getCookies();

                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals("PaaaService")) {

                            String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                            this.logger.info(value);
                            LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class);

                            // A C H T U N G: ggf. andere patronID im Cookie als in Request (UniAccount vs. BibAccount)
                            if (loginResponse.getPatron().equals(patronid)) {
                                authorization = loginResponse.getAccess_token();
                            }

                            break;
                        }
                    }
                }
            }

            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

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

            if (!authorization.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,
                                patronid, authorization);
                    } catch (AuthorizationException e) {

                        // TODO correct error handling
                        this.logger.error("[" + config.getProperty("service.name") + "] "
                                + HttpServletResponse.SC_UNAUTHORIZED + "!");
                    }
                } else {

                    // TODO correct error handling
                    this.logger.error("[" + this.config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": "
                            + "Authorization Interface not implemented!");
                }
            }

            this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: "
                    + authorization + " - " + isAuthorized);

            // ... - if not is authorized - against DFN-AAI service
            if (!isAuthorized) {

                // TODO if exists OpenAM-Session-Cookie: read content
                this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: "
                        + authorization + " - " + isAuthorized);
            }

            if (isAuthorized) {

                // execute query
                this.provideService(httpServletRequest, httpServletResponse, format, patronid, authorization,
                        service);
            } else {

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

            this.logger.error("[" + this.config.getProperty("service.name") + "] "
                    + HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + "DELETE for '" + service
                    + "' not allowed!");

            httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
            httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
            httpServletResponse.setContentType("application/json");
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

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

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

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

            // send response
            httpServletResponse.getWriter().println(json);
        }
    }
}

From source file:de.tu_dortmund.ub.api.paaa.PaaaEndpoint.java

/**
 * @param httpServletRequest//from ww  w  .  j  ava2s.  com
 * @param httpServletResponse
 * @throws ServletException
 * @throws java.io.IOException
 */
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    ObjectMapper mapper = new ObjectMapper();

    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "PathInfo = "
            + httpServletRequest.getPathInfo());
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "QueryString = "
            + httpServletRequest.getQueryString());

    String patronid = "";
    String service = "";
    String accept = "";
    String authorization = "";

    String format = "json";

    String path = httpServletRequest.getPathInfo();
    String[] params = path.substring(1, path.length()).split("/");

    if (params.length == 1) {
        patronid = params[0];
        service = "patron";
    } else if (params.length == 2) {
        patronid = params[0];
        service = params[1];
    }

    if (patronid.equals("patronid")) {
        patronid = "";
    }

    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Patron: " + patronid);
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Service: " + service);

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

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

        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerNameKey = headerNames.nextElement();

            if (headerNameKey.equals("Accept")) {

                this.logger.debug("headerNameKey = " + httpServletRequest.getHeader(headerNameKey));

                if (httpServletRequest.getHeader(headerNameKey).contains("text/html")) {
                    format = "html";
                } else if (httpServletRequest.getHeader(headerNameKey).contains("application/xml")) {
                    format = "xml";
                } else if (httpServletRequest.getHeader(headerNameKey).contains("application/json")) {
                    format = "json";
                }
            }
        }
    }

    this.logger.info("format = " + format);

    if (!format.equals("json") && !format.equals("xml")) {

        this.logger.error("[" + this.config.getProperty("service.name") + "] "
                + HttpServletResponse.SC_BAD_REQUEST + ": " + format + " not implemented!");

        // 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);
    } else {
        // PAAA - function
        if (service.equals("signup") || service.equals("newpatron") || service.equals("updatepatron")
                || service.equals("blockpatron") || service.equals("unblockpatron")
                || service.equals("newfee")) {

            // get 'Accept' and 'Authorization' from Header;
            Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
            while (headerNames.hasMoreElements()) {

                String headerNameKey = (String) headerNames.nextElement();
                this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "headerNameKey = "
                        + headerNameKey + " / headerNameValue = "
                        + httpServletRequest.getHeader(headerNameKey));

                if (headerNameKey.equals("Accept")) {
                    accept = httpServletRequest.getHeader(headerNameKey);
                }
                if (headerNameKey.equals("Authorization")) {
                    authorization = httpServletRequest.getHeader(headerNameKey);
                }
            }

            this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Accept: " + accept);
            this.logger.debug(
                    "[" + this.config.getProperty("service.name") + "] " + "Authorization: " + authorization);

            // if not exists token: read request parameter
            if (authorization.equals("") && httpServletRequest.getParameter("access_token") != null
                    && !httpServletRequest.getParameter("access_token").equals("")) {
                authorization = httpServletRequest.getParameter("access_token");
            }

            // if not exists token
            if (authorization.equals("")) {

                // if exists PaiaService-Cookie: read content
                Cookie[] cookies = httpServletRequest.getCookies();

                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals("PaaaService")) {

                            String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                            this.logger.info(value);
                            LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class);

                            // A C H T U N G: ggf. andere patronID im Cookie als in Request (UniAccount vs. BibAccount)
                            if (loginResponse.getPatron().equals(patronid)) {
                                authorization = loginResponse.getAccess_token();
                            }

                            break;
                        }
                    }
                }
            }

            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

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

            if (!authorization.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,
                                patronid, authorization);
                    } catch (AuthorizationException e) {

                        // TODO correct error handling
                        this.logger.error("[" + config.getProperty("service.name") + "] "
                                + HttpServletResponse.SC_UNAUTHORIZED + "!");
                    }
                } else {

                    // TODO correct error handling
                    this.logger.error("[" + this.config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": "
                            + "Authorization Interface not implemented!");
                }
            }

            this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: "
                    + authorization + " - " + isAuthorized);

            // ... - if not is authorized - against DFN-AAI service
            if (!isAuthorized) {

                // TODO if exists OpenAM-Session-Cookie: read content
                this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: "
                        + authorization + " - " + isAuthorized);
            }

            if (isAuthorized) {

                // execute query
                this.provideService(httpServletRequest, httpServletResponse, format, patronid, authorization,
                        service);
            } else {

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

            this.logger.error("[" + this.config.getProperty("service.name") + "] "
                    + HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + "POST for '" + service
                    + "' not allowed!");

            httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
            httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
            httpServletResponse.setContentType("application/json");

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

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

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

            // send response
            httpServletResponse.getWriter().println(json);
        }
    }
}

From source file:com.google.gsa.valve.modules.httpbasic.HTTPBasicAuthenticationProcess.java

/**
 * This is the main method that does the authentication and should be 
 * invoked by the classes that would like to open a new authentication 
 * process against an HTTP Basic protected source.
 * <p>/* w  w  w  . j a v  a  2  s. c  o m*/
 * The username and password for the source are assumed to be the ones 
 * captured during the authentication. These are stored in creds and in 
 * this case the root parameters. creds is an array of credentials for 
 * all external sources. The first element is 'root' which contains the 
 * credentials captured from the login page. This method reviews if there 
 * is a credential id identical to the name associated to this module 
 * in the config file. If so, these credentials are used to authenticate 
 * against this HTTP Basic source, and if not 'root' one will be used 
 * instead.
 * <p>
 * If the HTTP Basic authentication result is OK, it creates an 
 * authentication cookie containing the HTTP Basic credentials 
 * to be reused during authorization. The content returned back from the 
 * remote secure backend system is sent as well. Anyway, the HTTP 
 * response code is returned in this method to inform the caller on the 
 * status.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    Cookie[] cookies = null;

    //Credentials                     
    UsernamePasswordCredentials credentials = null;

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

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

    // Debug
    logger.debug("HTTP Basic authentication start");

    //First read the u/p the credentails store, in this case using the same as the root login
    logger.debug("HttpBasic: trying to get creds from repository ID: " + id);
    Credential httpBasicCred = null;
    try {
        httpBasicCred = creds.getCredential(id);
    } catch (NullPointerException npe) {
        logger.error("NPE while reading credentials of ID: " + id);
    }
    if (httpBasicCred != null) {
        credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(), httpBasicCred.getPassword());
    } else {
        logger.debug("HttpBasic: trying to get creds from repository \"root\"");
        httpBasicCred = creds.getCredential("root");
        if (httpBasicCred != null) {
            logger.info("Trying with root credentails");
            credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(),
                    httpBasicCred.getPassword());
        }
    }

    logger.debug("Authenticating");
    Header[] headers = null;
    HttpMethodBase method = null;

    //Get Max connections
    int maxConnectionsPerHost = 30;
    int maxTotalConnections = 100;

    //Cookie Max Age
    int authMaxAge = -1;

    try {
        maxConnectionsPerHost = new Integer(valveConf.getMaxConnectionsPerHost()).intValue();
        maxTotalConnections = (new Integer(valveConf.getMaxTotalConnections())).intValue();
        authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
    } catch (NumberFormatException nfe) {
        logger.error(
                "Configuration error: chack the configuration file as the numbers set for any of the following parameters are not OK:");
        logger.error("  * maxConnectionsPerHost    * maxTotalConnections    * authMaxAge");
    }

    // Protection
    if (webProcessor == null) {
        // Instantiate Web processor
        if ((maxConnectionsPerHost != -1) && (maxTotalConnections != -1)) {
            webProcessor = new WebProcessor(maxConnectionsPerHost, maxTotalConnections);
        } else {
            webProcessor = new WebProcessor();
        }
    }

    //
    // Launch the authentication process
    //

    // A fixed URL in the repository that all users have access to which can be used to authN a user
    // and capture the HTTP Authorization Header
    String authURL = valveConf.getRepository(id).getParameterValue("HTTPAuthPage");

    try {

        // Set HTTP headers
        headers = new Header[1];

        // Set User-Agent
        headers[0] = new Header("User-Agent",
                "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5");

        // Request page, testing if credentials are valid
        if (credentials != null) {
            logger.debug("Username: " + credentials.getUserName());
            logger.debug("URL: " + authURL);
        }

        //HTTP request
        method = webProcessor.sendRequest(credentials, RequestType.GET_REQUEST, headers, null, authURL);

        //Read the auth header and store in the cookie, the authZ class will use this later
        headers = method.getRequestHeaders();

        Header authHeader = null;
        authHeader = method.getRequestHeader("Authorization");

        // Cache status code
        if (method != null)
            statusCode = method.getStatusCode();

        if (statusCode == HttpServletResponse.SC_OK) {
            //Authentication worked, so create the auth cookie to indicate it has worked
            Cookie extAuthCookie = null;
            extAuthCookie = new Cookie(BASIC_COOKIE, "");

            if (authHeader != null) {

                String basicCookie = null;

                try {
                    basicCookie = URLEncoder.encode(getBasicAuthNChain(authHeader.getValue()), encoder);
                    if (basicCookie == null) {
                        basicCookie = "";
                    }
                } catch (Exception ex) {
                    logger.error("Error when setting Basic cookie value: " + ex.getMessage(), ex);
                    basicCookie = "";
                }

                extAuthCookie.setValue(basicCookie);

            }
            String authCookieDomain = null;
            String authCookiePath = null;

            // Cache cookie properties
            authCookieDomain = valveConf.getAuthCookieDomain();
            authCookiePath = valveConf.getAuthCookiePath();

            // Set extra cookie parameters
            extAuthCookie.setDomain(authCookieDomain);
            extAuthCookie.setPath(authCookiePath);
            extAuthCookie.setMaxAge(authMaxAge);

            // Log info
            if (logger.isDebugEnabled())
                logger.debug("Adding " + BASIC_COOKIE + " cookie: " + extAuthCookie.getName() + ":"
                        + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":"
                        + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

            //sendCookies support                        
            boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled())
                    .booleanValue();
            boolean sendCookies = false;
            if (isSessionEnabled) {
                sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue();
            }
            if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) {
                logger.debug("Adding cookie to response");
                response.addCookie(extAuthCookie);
            }

            //Add cookies to the Cookie array to support sessions
            authCookies.add(extAuthCookie);
            logger.debug("Cookie added to the array");

        }

        // Clear webProcessor cookies
        webProcessor.clearCookies();

    } catch (Exception e) {

        // Log error
        logger.error("HTTP Basic authentication failure: " + e.getMessage(), e);

        // Garbagge collect
        method = null;

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    // End of the authentication process
    logger.debug("HTTP Basic Authentication completed (" + statusCode + ")");

    // Return status code
    return statusCode;

}

From source file:com.ylife.shoppingcart.service.impl.ShoppingCartServiceImpl.java

/**
 * //w w w. j a v  a  2s  . c  o m
 *
 * @param shoppingCartId
 *            id
 * @param marketingId
 *            ??id
 * @param marketingActivityId
 *            id
 * @return int
 */
@Override
public int changeShoppingCartMarket(Long shoppingCartId, Long marketingId, Long marketingActivityId,
        HttpServletRequest request, HttpServletResponse response) {
    Long marketingIdNew = marketingId;
    Long marketingActivityIdNew = marketingActivityId;
    Long customerId = (Long) request.getSession().getAttribute(CUSTOMERID);

    // ?
    if (customerId != null) {
        ShoppingCart sc = new ShoppingCart();

        sc.setShoppingCartId(shoppingCartId);
        // ??id0???
        if (marketingIdNew != null && marketingIdNew == 0) {
            marketingIdNew = null;
        }
        sc.setMarketingId(marketingIdNew);
        // id0?
        if (marketingActivityIdNew != null && marketingActivityIdNew == 0) {
            marketingActivityIdNew = null;
        }
        sc.setMarketingActivityId(marketingActivityIdNew);
        return shoppingCartMapper.changeShoppingCartMarket(sc);
    } else {
        Cookie[] cookies = request.getCookies();

        StringBuilder newMid = new StringBuilder();

        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (cookie != null && NPSTORE_MID.equals(cookie.getName()) && cookie.getValue() != null
                        && !"".equals(cookie.getValue())) {
                    String[] mIds = cookie.getValue().split("-");
                    // ?cookie
                    for (int j = 0; j < mIds.length; j++) {
                        String[] mid = mIds[j].split("e");
                        // ??
                        if (mid[0] != null) {
                            if (mid[0].equals(shoppingCartId.toString())) {
                                newMid.append(shoppingCartId);
                                newMid.append("e");
                                newMid.append(marketingIdNew);
                                newMid.append("e");
                                newMid.append(marketingActivityIdNew);
                                newMid.append("e");
                                newMid.append("1");
                                newMid.append("-");
                            } else {
                                newMid.append(mIds[j]);
                                newMid.append("-");
                            }
                        }
                    }
                }
            }
            Cookie cookie = new Cookie(NPSTORE_MID, newMid.toString());
            cookie.setMaxAge(15 * 24 * 3600);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return 0;
    }

}

From source file:com.ylife.shoppingcart.service.impl.ShoppingCartServiceImpl.java

/**
 * cookie?//from  w  ww. j  a  v a2 s  .  co m
 *
 * @param request
 *            
 * @param response
 *            
 * @return ?
 * @throws UnsupportedEncodingException
 */
public int delCookShopCar(Long productId, HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    Integer count = 0;
    Cookie[] cookies = request.getCookies();
    String oldCar = "";
    String[] cars = null;
    String[] car = null;
    Cookie cook;
    String newMid = "";
    StringBuilder bufOldCar = new StringBuilder();
    StringBuilder bufNewMid = new StringBuilder();

    try {
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (null != cookie && NPSTORE_SHOPCAR.equals(cookie.getName())) {
                    oldCar = URLDecoder.decode(cookie.getValue(), "utf-8");
                    if (oldCar.indexOf("," + productId + "-") != -1) {
                        oldCar = oldCar.substring(1, oldCar.length());
                        oldCar = oldCar.substring(0, oldCar.length() - 1);
                        cars = oldCar.split("e,");
                        oldCar = "";
                        for (int j = 0; j < cars.length; j++) {
                            car = cars[j].split("-");
                            if (!car[0].equals(productId.toString())) {
                                bufOldCar.append(oldCar);
                                bufOldCar.append(",");
                                bufOldCar.append(car[0]);
                                bufOldCar.append("-");
                                bufOldCar.append(car[1]);
                                bufOldCar.append("e");
                                oldCar += bufOldCar.toString();
                            }
                        }
                    }
                }
                if (cookie != null && NPSTORE_MID.equals(cookie.getName()) && cookie.getValue() != null
                        && !"".equals(cookie.getValue())) {
                    String[] mIds = cookie.getValue().split("-");
                    // ?cookie
                    for (int j = 0; j < mIds.length; j++) {
                        String[] mid = mIds[j].split("e");
                        // ??
                        if (mid[0] != null && !mid[0].equals(productId.toString())) {
                            bufNewMid.append(mIds[j]);
                            bufNewMid.append("-");
                            newMid += bufNewMid.toString();
                        }
                    }
                }

            }
        }
        cook = new Cookie(NPSTORE_SHOPCAR, URLEncoder.encode(oldCar, "utf-8"));
        cook.setMaxAge(15 * 24 * 3600);
        cook.setPath("/");
        response.addCookie(cook);
        Cookie cookie = new Cookie(NPSTORE_MID, URLEncoder.encode(newMid, "utf-8"));
        cookie.setMaxAge(15 * 24 * 3600);
        cookie.setPath("/");
        response.addCookie(cookie);
        return count;
    } finally {
        cook = null;
        cars = null;
        car = null;
        cookies = null;
        oldCar = null;
    }
}

From source file:com.ylife.shoppingcart.service.impl.ShoppingCartServiceImpl.java

/**
 * cookie?/* ww w  .  j  a va 2 s.  c  o m*/
 *
 * @return 
 * @throws UnsupportedEncodingException
 */
public List<ShopCarUtil> loadCookShopCar(HttpServletRequest request) throws UnsupportedEncodingException {
    List<ShopCarUtil> list = new ArrayList<ShopCarUtil>();
    Cookie[] cookies = request.getCookies();
    String oldCar = "";
    String[] cars = null;
    String[] car = null;
    String[] car2 = null;
    ShopCarUtil carUtil = null;
    boolean checkExists = false;
    try {
        if (null != cookies) {
            for (Cookie cookie : cookies) {

                if (null != cookie && NPSTORE_SHOPCAR.equals(cookie.getName()) && cookie.getValue() != null
                        && !"".equals(cookie.getValue())) {
                    oldCar = URLDecoder.decode(cookie.getValue(), "utf-8");
                    oldCar = oldCar.substring(1, oldCar.length());
                    oldCar = oldCar.substring(0, oldCar.length() - 1);
                    cars = oldCar.split("e,");
                    if (null != cars && cars.length > 0) {
                        for (int i = 0; i < cars.length; i++) {
                            car = cars[i].split("-");
                            carUtil = new ShopCarUtil();

                            /* ?,,?? */
                            if (car[0].length() > 6 && CODE001.equals(car[0].substring(0, 6))) {
                                carUtil.setFitId(Long.parseLong(car[0].substring(6, car[0].length())));
                                carUtil.setProductId(Long.parseLong(car[0]));
                            } else {
                                carUtil.setProductId(Long.parseLong(car[0]));
                                for (Cookie cook : cookies) {
                                    // 
                                    if (cook != null && NPSTORE_MID.equals(cook.getName())
                                            && cook.getValue() != null && !"".equals(cook.getValue())) {
                                        String[] mIds = cook.getValue().split("-");
                                        // ?cookie
                                        for (int j = 0; j < mIds.length; j++) {
                                            String[] mid = mIds[j].split("e");
                                            // ??
                                            if (mid[0] != null && car[0].equals(mid[0])) {
                                                if (mid[1] != null && !"null".equals(mid[1])) {
                                                    carUtil.setMarketId(Long.parseLong(mid[1]));
                                                }

                                                carUtil.setMarketActiveId(Long.parseLong(mid[2]));
                                                carUtil.setStatus(Long.parseLong(mid[3]));
                                            }
                                        }
                                    }
                                }
                                car2 = car[1].split("&");
                                carUtil.setGoodsNum(Integer.parseInt(car2[0]));
                                carUtil.setDistinctId(Long.parseLong(car2[1]));
                                for (int j = 0; j < list.size(); j++) {
                                    if (list.get(j).getProductId().equals(carUtil.getProductId())) {
                                        checkExists = true;
                                    }
                                }
                                if (!checkExists) {
                                    list.add(carUtil);
                                    checkExists = false;
                                }
                            }
                        }
                    }

                }

            }
        }
        return list;
    } finally {
        list = null;
        cookies = null;
        oldCar = null;
        cars = null;
        car = null;
    }
}

From source file:com.ylife.shoppingcart.service.impl.ShoppingCartServiceImpl.java

/**
 * /*  w w  w .j  av  a  2 s .c o m*/
 *
 * @param shoppingCart
 * @return int
 * @throws UnsupportedEncodingException
 */
@Override
@Transactional
public int addShoppingCart(ShoppingCart shoppingCart, HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    Long custId = (Long) request.getSession().getAttribute(CUSTOMERID);
    if (null != custId) {
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", custId);
        int sum = shoppingCartMapper.selectSumByCustomerId(map);
        if (sum >= 20) {
            return -1;
        }
        shoppingCart.setCustomerId(custId);
        shoppingCart.setDelFlag("0");
        shoppingCart.setShoppingCartTime(new Date());
        int count = shoppingCartMapper.selectCountByReady(shoppingCart);

        if (count == 0) {
            return shoppingCartMapper.addShoppingCart(shoppingCart);
        } else {
            ShoppingCart sc = shoppingCartMapper.selectShopingByParam(shoppingCart);
            // ?
            if (sc.getGoodsNum() == 99) {
                return 0;
            }
            return shoppingCartMapper.updateShoppingCart(shoppingCart);
        }
    } else {
        num = "";
        Cookie[] cookies = request.getCookies();
        String oldCar = "";
        String mId = "";
        Cookie cook;
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (null != cookie && NPSTORE_SHOPCAR.equals(cookie.getName())) {
                    oldCar = URLDecoder.decode(cookie.getValue(), "utf-8");
                    if (oldCar.indexOf("," + shoppingCart.getGoodsInfoId() + "-") != -1) {
                        num = oldCar.substring(oldCar.indexOf("," + shoppingCart.getGoodsInfoId() + "-"),
                                oldCar.indexOf("," + shoppingCart.getGoodsInfoId() + "-") + oldCar
                                        .substring(oldCar.indexOf("," + shoppingCart.getGoodsInfoId() + "-"),
                                                oldCar.length() - 1)
                                        .indexOf("&"));
                        num = num.substring(num.indexOf("-") + 1, num.length());
                        oldCar = oldCar.replace("," + shoppingCart.getGoodsInfoId() + "-" + num + "&"
                                + shoppingCart.getDistinctId() + "e", "");
                        if (oldCar.indexOf("," + shoppingCart.getGoodsInfoId() + "-" + num + "&"
                                + shoppingCart.getDistinctId()) != -1) {
                            oldCar = oldCar.replace("," + shoppingCart.getGoodsInfoId() + "-" + num + "&"
                                    + shoppingCart.getDistinctId(), "");

                        }
                    }
                }
                if (cookie != null && NPSTORE_MID.equals(cookie.getName()) && cookie.getValue() != null
                        && !"".equals(cookie.getValue())) {
                    String[] mIds = cookie.getValue().split("-");
                    // ?cookie
                    for (int j = 0; j < mIds.length; j++) {
                        String[] mid = mIds[j].split("e");
                        // ??
                        if (mid[0] != null && "".equals(mIds[0])
                                && !mid[0].equals(shoppingCart.getGoodsInfoId().toString())) {
                            mId = cookie.getValue();
                        }
                    }
                }

            }
        }
        if (!"".equals(num)) {
            num = String.valueOf(Long.parseLong(num) + shoppingCart.getGoodsNum());
        } else {
            num = String.valueOf(shoppingCart.getGoodsNum());
        }
        oldCar += "," + shoppingCart.getGoodsInfoId() + "-" + num + "&" + shoppingCart.getDistinctId() + "e";
        GoodsDetailBean goodsDetailBean = null;
        if (shoppingCart.getFitId() == null) {
            goodsDetailBean = goodsProductService.queryDetailBeanByProductId(shoppingCart.getGoodsInfoId(),
                    Long.parseLong("0"), null);

        }
        cook = new Cookie(NPSTORE_SHOPCAR, URLEncoder.encode(oldCar, "utf-8"));
        cook.setMaxAge(15 * 24 * 3600);
        cook.setPath("/");
        response.addCookie(cook);
        Cookie cookie = new Cookie(NPSTORE_MID, mId);
        cookie.setMaxAge(15 * 24 * 3600);
        cookie.setPath("/");
        response.addCookie(cookie);
        return 1;
    }
}

From source file:org.apache.click.util.ClickUtils.java

/**
 * Returns the specified Cookie object, or null if the cookie does not exist.
 * <p/>//www  .j av  a2  s  . c  o  m
 * This method was derived from Atlassian <tt>CookieUtils</tt> method of
 * the same name, release under the BSD License.
 *
 * @param request the servlet request
 * @param name the name of the cookie
 * @return the Cookie object if it exists, otherwise null
 */
public static Cookie getCookie(HttpServletRequest request, String name) {
    Cookie cookies[] = request.getCookies();

    if (cookies == null || name == null || name.length() == 0) {
        return null;
    }

    //Otherwise, we have to do a linear scan for the cookie.
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals(name)) {
            return cookie;
        }
    }

    return null;
}

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

/**
 *
 * @param httpServletRequest/*from   w  w  w.  ja  v  a2s. com*/
 * @param httpServletResponse
 * @throws ServletException
 * @throws IOException
 */
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    ObjectMapper mapper = new ObjectMapper();

    String format;
    String language;
    String redirect_url;

    this.logger.debug(
            "[" + config.getProperty("service.name") + "] " + "PathInfo = " + httpServletRequest.getPathInfo());
    this.logger.debug("[" + config.getProperty("service.name") + "] " + "QueryString = "
            + httpServletRequest.getQueryString());

    String patronid = "";
    String service = "";
    String accept = "";
    String authorization = "";

    String path = httpServletRequest.getPathInfo();
    if (path != null) {
        String[] params = path.substring(1, path.length()).split("/");

        if (params.length == 1) {
            patronid = params[0];
            service = "patron";
        } else if (params.length == 2) {
            patronid = params[0];
            service = params[1];
        } else if (params[1].equals("items") && params.length > 2) {
            patronid = params[0];
            for (int i = 1; i < params.length; i++) {

                service += params[i];
                if (i < params.length - 1) {
                    service += "/";
                }
            }
        }
    }

    if (patronid.equals("patronid")) {

        patronid = "";
    }

    this.logger.debug("[" + config.getProperty("service.name") + "] " + "Service: " + service);
    this.logger.debug("[" + config.getProperty("service.name") + "] " + "Patron: " + patronid);

    format = "html";

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

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

        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerNameKey = headerNames.nextElement();

            if (headerNameKey.equals("Accept")) {

                this.logger.debug("headerNameKey = " + httpServletRequest.getHeader(headerNameKey));

                if (httpServletRequest.getHeader(headerNameKey).contains("text/html")) {
                    format = "html";
                } else if (httpServletRequest.getHeader(headerNameKey).contains("application/xml")) {
                    format = "xml";
                } else if (httpServletRequest.getHeader(headerNameKey).contains("application/json")) {
                    format = "json";
                }
            }
        }
    }

    this.logger.info("format = " + format);

    if (format.equals("html") && Lookup.lookupAll(ObjectToHtmlTransformation.class).size() == 0) {

        this.logger.error("[" + this.config.getProperty("service.name") + "] "
                + HttpServletResponse.SC_BAD_REQUEST + ": " + "html not implemented!");

        // 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, "", "");
    } else {

        // read requestBody
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = httpServletRequest.getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        } catch (Exception e) {
            /*report an error*/ }

        String requestBody = jb.toString();

        // read document list
        DocumentList documentList = null;

        try {

            // read DocumentList
            documentList = mapper.readValue(requestBody, DocumentList.class);
        } catch (Exception e) {

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

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

                if (params.length > 1) {

                    documentList = new DocumentList();
                    documentList.setDoc(new ArrayList<Document>());

                    for (String param : params) {

                        if (param.startsWith("document_id")) {
                            Document document = new Document();
                            document.setEdition(param.split("=")[1]);
                            documentList.getDoc().add(document);
                        }
                    }
                }
            } else if (httpServletRequest.getParameter("document_id") != null
                    && !httpServletRequest.getParameter("document_id").equals("")) {

                Document document = new Document();
                document.setEdition(httpServletRequest.getParameter("document_id"));

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

                    document.setStorage_id(httpServletRequest.getParameter("storage_id"));
                }

                documentList = new DocumentList();
                documentList.setDoc(new ArrayList<Document>());
                documentList.getDoc().add(document);
            } else {

                // if exists cookie with name "PaiaServiceDocumentList": read it
                Cookie[] cookies = httpServletRequest.getCookies();

                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals("PaiaServiceDocumentList")) {

                            if (cookie.getValue() != null && !cookie.getValue().equals("")
                                    && !cookie.getValue().equals("null")) {

                                String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                                this.logger.info(value);
                                documentList = mapper.readValue(value, DocumentList.class);
                            }

                            break;
                        }
                    }
                }
            }
        }

        if (patronid.equals("")) {

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

            redirect_url = "";

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

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

            this.logger.info("redirect_url = " + redirect_url);

            language = "";

            // PAIA core - function
            if ((httpServletRequest.getMethod().equals("GET")
                    && (service.equals("patron") || service.equals("fullpatron") || service.equals("items")
                            || service.startsWith("items/ordered") || service.startsWith("items/reserved")
                            || service.startsWith("items/borrowed") || service.startsWith("items/borrowed/ill")
                            || service.startsWith("items/borrowed/renewed")
                            || service.startsWith("items/borrowed/recalled") || service.equals("fees")
                            || service.equals("request")))
                    || (httpServletRequest.getMethod().equals("POST") && (service.equals("request")
                            || service.equals("renew") || service.equals("cancel")))) {

                // get 'Accept' and 'Authorization' from Header
                Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
                while (headerNames.hasMoreElements()) {

                    String headerNameKey = (String) headerNames.nextElement();
                    this.logger.debug(
                            "[" + config.getProperty("service.name") + "] " + "headerNameKey = " + headerNameKey
                                    + " / headerNameValue = " + httpServletRequest.getHeader(headerNameKey));

                    if (headerNameKey.equals("Accept-Language")) {
                        language = httpServletRequest.getHeader(headerNameKey);
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "Accept-Language: "
                                + language);
                    }
                    if (headerNameKey.equals("Accept")) {
                        accept = httpServletRequest.getHeader(headerNameKey);
                        this.logger
                                .debug("[" + config.getProperty("service.name") + "] " + "Accept: " + accept);
                    }
                    if (headerNameKey.equals("Authorization")) {
                        authorization = httpServletRequest.getHeader(headerNameKey);
                    }
                }

                // language
                if (language.startsWith("de")) {
                    language = "de";
                } else if (language.startsWith("en")) {
                    language = "en";
                } else if (httpServletRequest.getParameter("l") != null) {
                    language = httpServletRequest.getParameter("l");
                } else {
                    language = "de";
                }

                // if not exists token: read request parameter
                if ((authorization == null || authorization.equals(""))
                        && httpServletRequest.getParameter("access_token") != null
                        && !httpServletRequest.getParameter("access_token").equals("")) {
                    authorization = httpServletRequest.getParameter("access_token");
                }

                // if not exists token
                if (authorization == null || authorization.equals("")) {

                    // if exists PaiaService-Cookie: read content
                    Cookie[] cookies = httpServletRequest.getCookies();

                    if (cookies != null) {
                        for (Cookie cookie : cookies) {
                            if (cookie.getName().equals("PaiaService")) {

                                String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                                this.logger.info(value);
                                LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class);

                                // A C H T U N G: ggf. andere patronID im Cookie als in Request (UniAccount vs. BibAccount)
                                if (loginResponse.getPatron().equals(patronid)) {
                                    authorization = loginResponse.getAccess_token();
                                }

                                break;
                            }
                        }

                        // if not exists token - search for Shibboleth-Token
                        if (authorization == null || authorization.equals("")) {

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

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

                                try {

                                    authorization = authorizationInterface.getAuthCookies(cookies);
                                } catch (AuthorizationException e) {

                                    // TODO correct error handling
                                    this.logger.error("[" + config.getProperty("service.name") + "] "
                                            + HttpServletResponse.SC_UNAUTHORIZED + "!");
                                }

                                this.logger.debug("[" + config.getProperty("service.name") + "] "
                                        + "Authorization: " + authorization);
                            }
                        }
                    }
                }

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

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

                if (authorization != null && !authorization.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,
                                    patronid, authorization);
                        } catch (AuthorizationException e) {

                            // TODO correct error handling
                            this.logger.error("[" + config.getProperty("service.name") + "] "
                                    + HttpServletResponse.SC_UNAUTHORIZED + "!");
                        }
                    } else {

                        // TODO correct error handling
                        this.logger.error("[" + this.config.getProperty("service.name") + "] "
                                + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": "
                                + "Authorization Interface not implemented!");
                    }
                }

                this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: "
                        + authorization + " - " + isAuthorized);

                if (isAuthorized) {

                    // execute query
                    this.provideService(httpServletRequest, httpServletResponse, patronid, service, format,
                            language, redirect_url, documentList);
                } else {

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

                this.logger.error("[" + config.getProperty("service.name") + "] "
                        + HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + httpServletRequest.getMethod()
                        + " for '" + service + "' not allowed!");

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

                RequestError requestError = new RequestError();
                requestError.setError(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED)));
                requestError.setCode(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                requestError.setDescription(this.config.getProperty("error."
                        + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".description"));
                requestError.setErrorUri(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".uri"));

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

From source file:com.iskyshop.manage.buyer.action.OrderBuyerAction.java

@SecurityMapping(title = "?", value = "/buyer/order.htm*", rtype = "buyer", rname = "", rcode = "user_center", rgroup = "")
@RequestMapping("/buyer/order.htm")
public ModelAndView order(HttpServletRequest request, HttpServletResponse response, String currentPage,
        String order_id, String beginTime, String endTime, String order_status) {
    ModelAndView mv = new JModelAndView("user/default/usercenter/buyer_order.html",
            configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response);
    OrderFormQueryObject ofqo = new OrderFormQueryObject(currentPage, mv, "addTime", "desc");
    User user = this.userService.getObjById(SecurityUserHolder.getCurrentUser().getId());
    ofqo.addQuery("obj.user_id", new SysMap("user_id", SecurityUserHolder.getCurrentUser().getId().toString()),
            "=");
    ofqo.addQuery("obj.order_main", new SysMap("order_main", 1), "=");// ??,????
    ofqo.addQuery("obj.order_cat", new SysMap("order_cat", 2), "!=");
    if (!CommUtil.null2String(order_id).equals("")) {
        ofqo.addQuery("obj.order_id", new SysMap("order_id", "%" + order_id + "%"), "like");
        mv.addObject("order_id", order_id);
    }//from   w  w w . j  a v  a 2 s. c o  m
    if (!CommUtil.null2String(beginTime).equals("")) {
        ofqo.addQuery("obj.addTime", new SysMap("beginTime", CommUtil.formatDate(beginTime)), ">=");
        mv.addObject("beginTime", beginTime);
    }
    if (!CommUtil.null2String(endTime).equals("")) {
        String ends = endTime + " 23:59:59";
        ofqo.addQuery("obj.addTime", new SysMap("endTime", CommUtil.formatDate(ends, "yyyy-MM-dd hh:mm:ss")),
                "<=");
        mv.addObject("endTime", endTime);
    }
    if (!CommUtil.null2String(order_status).equals("")) {
        if (order_status.equals("order_submit")) {// ???
            ofqo.addQuery("obj.order_status", new SysMap("order_status", 10), "=");
        }
        if (order_status.equals("order_pay")) {// ?
            ofqo.addQuery("obj.order_status", new SysMap("order_status", 20), "=");
        }
        if (order_status.equals("order_shipping")) {// ??
            ofqo.addQuery("obj.order_status", new SysMap("order_status", 30), "=");
        }
        if (order_status.equals("order_receive")) {// ?
            ofqo.addQuery("obj.order_status", new SysMap("order_status", 40), "=");
        }
        if (order_status.equals("order_finish")) {// ??
            ofqo.addQuery("obj.order_status", new SysMap("order_status", 50), "=");
        }
        if (order_status.equals("order_cancel")) {// ??
            ofqo.addQuery("obj.order_status", new SysMap("order_status", 0), "=");
        }
    }
    mv.addObject("orderFormTools", orderFormTools);
    mv.addObject("order_status", order_status);
    IPageList pList = this.orderFormService.list(ofqo);
    List<OrderForm> orderForms = pList.getResult();

    //???
    orderFormService.changPhotoByJson(orderForms);
    CommUtil.saveIPageList2ModelAndView("", "", "", pList, mv);

    List<Object> result = dataProcess(pList.getResult());
    mv.addObject("data", result);
    // ??
    int[] status = new int[] { 10, 30, 50 }; // ?? ? ?
    String[] string_status = new String[] { "order_submit", "order_shipping", "order_finish" };
    Map orders_status = new LinkedHashMap();
    BigDecimal totleAmount = new BigDecimal(0);
    for (int i = 0; i < status.length; i++) {
        int size = this.orderFormService
                .query("select obj.id,obj.totalPrice from OrderForm obj where obj.user_id="
                        + user.getId().toString() + " and obj.order_status =" + status[i] + "", null, -1, -1)
                .size();
        mv.addObject("order_size_" + status[i], size);
        orders_status.put(string_status[i], size);
    }
    //?
    List list = this.orderFormService.query("select sum(obj.totalPrice) from OrderForm obj where obj.user_id="
            + user.getId().toString() + " and obj.order_status >=40", null, -1, -1);
    BigDecimal amountTotle = BigDecimal.ZERO;
    if (list != null && list.size() > 0 && list.get(0) != null) {
        amountTotle = (BigDecimal) list.get(0);
    }
    mv.addObject("amountTotle", amountTotle);
    mv.addObject("orders_status", orders_status);
    mv.addObject("orderFormTools", this.orderFormTools);
    //  ?cookie? ? cookie?
    List<Goods> your_like_goods = new ArrayList<Goods>();
    Long your_like_GoodsClass = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("goodscookie")) {
                String[] like_gcid = cookie.getValue().split(",", 2);
                Goods goods = this.goodsService.getObjById(CommUtil.null2Long(like_gcid[0]));
                if (goods == null)
                    break;
                your_like_GoodsClass = goods.getGc().getId();
                your_like_goods = this.goodsService
                        .query("select obj from Goods obj where obj.goods_status=0 and obj.gc.id = "
                                + your_like_GoodsClass + " and obj.id is not " + goods.getId()
                                + " order by obj.goods_salenum desc", null, 0, 20);
                int gcs_size = your_like_goods.size();
                if (gcs_size < 20) {
                    List<Goods> like_goods = this.goodsService.query(
                            "select obj from Goods obj where obj.goods_status=0 and obj.id is not "
                                    + goods.getId() + " order by obj.goods_salenum desc",
                            null, 0, 20 - gcs_size);
                    for (int i = 0; i < like_goods.size(); i++) {
                        // ???
                        int k = 0;
                        for (int j = 0; j < your_like_goods.size(); j++) {
                            if (like_goods.get(i).getId().equals(your_like_goods.get(j).getId())) {
                                k++;
                            }
                        }
                        if (k == 0) {
                            your_like_goods.add(like_goods.get(i));
                        }
                    }
                }
                break;
            } else {
                your_like_goods = this.goodsService.query(
                        "select obj from Goods obj where obj.goods_status=0 order by obj.goods_salenum desc",
                        null, 0, 20);
            }
        }
    } else {
        your_like_goods = this.goodsService.query(
                "select obj from Goods obj where obj.goods_status=0 order by obj.goods_salenum desc", null, 0,
                20);
    }
    mv.addObject("your_like_goods", your_like_goods);
    return mv;
}