Example usage for javax.servlet.http HttpServletRequest getCookies

List of usage examples for javax.servlet.http HttpServletRequest getCookies

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getCookies.

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

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];//from  w w w. jav  a2s . c om
        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: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 av a 2 s. com*/
    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;
}

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

/**
 * @param httpServletRequest//from www .j  a  v a 2s.c  o m
 * @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:de.tu_dortmund.ub.api.paia.core.PaiaCoreEndpoint.java

/**
 *
 * @param httpServletRequest/* ww  w.java  2 s .co m*/
 * @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:de.innovationgate.wgpublisher.WGPDispatcher.java

public void doGet(javax.servlet.http.HttpServletRequest request,
        javax.servlet.http.HttpServletResponse response)
        throws javax.servlet.ServletException, java.io.IOException {

    if (!isServePages()) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "Website is currently updating configuration. Please try again later.");
        return;//from w  w w .  j  av a  2 s  .  c  o  m
    }

    Date startDate = new Date();

    if (this._contextPath == null) {
        this._contextPath = request.getContextPath();
        this._listenPort = request.getServerPort();
    }

    WGARequestInformation reqInfo = (WGARequestInformation) request
            .getAttribute(WGARequestInformation.REQUEST_ATTRIBUTENAME);

    try {

        // Parse request
        WGPRequestPath path = WGPRequestPath.parseRequest(this, request, response);
        request.setAttribute(WGACore.ATTRIB_REQUESTPATH, path);

        // If database login failed or access was denied exit immediately
        if (!path.isProceedRequest()) {
            return;
        }

        // Set access logging for this request
        if (path.getDatabase() != null) {
            String accessLoggingEnabled = (String) path.getDatabase()
                    .getAttribute(WGACore.DBATTRIB_ENABLE_ACCESSLOGGING);
            if (accessLoggingEnabled != null) {
                if (reqInfo != null) {
                    reqInfo.setLoggingEnabled(Boolean.parseBoolean(accessLoggingEnabled));
                }
            }
        }

        int iPathType = path.getPathType();

        // Treatment of special URL types
        String dbKey = path.getDatabaseKey();
        if (iPathType == WGPRequestPath.TYPE_INVALID) {
            throw new HttpErrorException(404, "Invalid path: " + path.getBasePath(), dbKey);
        }
        if (iPathType == WGPRequestPath.TYPE_INVALID_DB) {
            throw new HttpErrorException(404, "Specified application '" + dbKey + "' is unknown", null);
        }

        if (iPathType == WGPRequestPath.TYPE_UNKNOWN_CONTENT) {
            sendNoContentNotification(path, request, response, path.getDatabase());
            return;
        }

        if (iPathType == WGPRequestPath.TYPE_GOTO_HOMEPAGE) {
            iPathType = determineHomepage(request, path, iPathType);
        }

        if (iPathType == WGPRequestPath.TYPE_UNAVAILABLE_DB) {
            throw new HttpErrorException(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    "The website is currently unavailable", path.getDatabaseKey());
        }

        if (iPathType == WGPRequestPath.TYPE_UNDEFINED_HOMEPAGE) {
            throw new HttpErrorException(
                    HttpServletResponse.SC_NOT_FOUND, "No home page was defined for app '"
                            + path.getDatabaseKey() + "'. Please specify an explicit content path.",
                    path.getDatabaseKey());
        }

        if (iPathType == WGPRequestPath.TYPE_TMLDEBUG) {
            _tmlDebugger.performDebugMode(request, response, request.getSession());
            return;
        }

        if (iPathType == WGPRequestPath.TYPE_JOBLOG) {
            sendJobLog(request, response, request.getSession());
            return;
        }

        if (iPathType == WGPRequestPath.TYPE_LOGOUT) {
            WGDatabase db = (WGDatabase) _core.getContentdbs().get(dbKey);
            String domain = (String) db.getAttribute(WGACore.DBATTRIB_DOMAIN);
            _core.logout(domain, request.getSession(), request, response, true);
            removeSessionCookie(response, request.getSession(), db);

            iPathType = WGPRequestPath.TYPE_REDIRECT;
        }

        if (iPathType == WGPRequestPath.TYPE_FAVICON) {
            String faviconPath = determineFavicon(request);
            if (faviconPath != null) {
                iPathType = WGPRequestPath.TYPE_REDIRECT;
                path.setResourcePath(faviconPath);
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Favicon not defined");
                return;
            }
        }

        if (iPathType == WGPRequestPath.TYPE_TMLFORM) {
            dispatchTmlFormRequest(path, request, response);
            return;
        }

        // Treatment of base URL Types
        if (iPathType == WGPRequestPath.TYPE_REDIRECT) {
            String url = path.getResourcePath();
            if (path.appendQueryString() == true && request.getQueryString() != null
                    && !request.getQueryString().equals("")) {
                if (url.indexOf("?") != -1) {
                    url += "&" + request.getQueryString();
                } else {
                    url += "?" + request.getQueryString();
                }
            }

            if (path.isPermanentRedirect()) {
                sendPermanentRedirect(response, url);
            } else {
                sendRedirect(request, response, url);
            }
        } else if (iPathType != WGPRequestPath.TYPE_RESOURCE && iPathType != WGPRequestPath.TYPE_STATICTML
                && !_core.getContentdbs().containsKey(path.getDatabaseKey())) {
            throw new HttpErrorException(404, "Database '" + dbKey + "' is unknown", null);
        } else {

            String requestMethod = request.getMethod().toLowerCase();
            switch (iPathType) {
            case (WGPRequestPath.TYPE_TML):
            case (WGPRequestPath.TYPE_TITLE_PATH):

                // Fetch the redirect cookie
                Cookie lastRedirectCookie = null;
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals(COOKIE_LASTREDIRECT)) {
                            lastRedirectCookie = cookie;
                            break;
                        }
                    }
                }

                // If path is not complete redirect it to the complete path, if possible. Set redirect cookie to prevent endless redirections
                if (!path.isCompletePath()) {
                    String redirectPath = path.expandToCompletePath(request);
                    if (isRedirectable(request, redirectPath, lastRedirectCookie)) {
                        lastRedirectCookie = new WGCookie(COOKIE_LASTREDIRECT,
                                Hex.encodeHexString(redirectPath.getBytes("UTF-8")));
                        lastRedirectCookie.setMaxAge(-1);
                        lastRedirectCookie.setPath("/");
                        ((WGCookie) lastRedirectCookie).addCookieHeader(response);
                        sendRedirect(request, response, redirectPath);
                        break;
                    }
                }

                // Delete redirect cookie when exists on normal dispatching
                if (lastRedirectCookie != null) {
                    lastRedirectCookie = new WGCookie(COOKIE_LASTREDIRECT, "");
                    lastRedirectCookie.setMaxAge(0);
                    lastRedirectCookie.setPath("/");
                    ((WGCookie) lastRedirectCookie).addCookieHeader(response);
                }

                // Dispatch
                dispatchTmlRequest(path, request, response, startDate);
                break;

            case (WGPRequestPath.TYPE_FILE):
                dispatchFileRequest(path, request, response);
                break;

            case (WGPRequestPath.TYPE_CSS):
            case (WGPRequestPath.TYPE_JS):
                dispatchCssjsRequest(path, request, response);
                break;

            case (WGPRequestPath.TYPE_RESOURCE):
                dispatchResourceRequest(path, request, response);
                break;

            case (WGPRequestPath.TYPE_STATICTML):
                dispatchStaticTmlRequest(path, request, response);
                break;

            default:
                throw new HttpErrorException(500, "Invalid url format", dbKey);
            }
        }

        // moved from finally block to ensure errorpage can be displayed
        commitResponse(response);
    } catch (ClientAccessException exc) {
        response.sendError(403, exc.getMessage());
    } catch (AjaxFailureException exc) {
        handleAjaxFailure(exc, request, response);
    } catch (HttpErrorException exc) {
        request.setAttribute(WGACore.ATTRIB_EXCEPTION, exc);
        ProblemOccasion occ = new PathDispatchingOccasion(request, exc.getDbHint());
        _core.getProblemRegistry().addProblem(
                Problem.create(occ, "dispatching.http404#" + request.getRequestURL(), ProblemSeverity.LOW));
        if (!response.isCommitted()) {
            // throw exception to display errorpage - with senderror() the
            // applicationserver use the buildin errorpage
            if (exc.getCode() == HttpServletResponse.SC_NOT_FOUND
                    || exc.getCode() == HttpServletResponse.SC_FORBIDDEN
                    || exc.getCode() == HttpServletResponse.SC_PRECONDITION_FAILED) {
                response.sendError(exc.getCode(), exc.getMessage());
            } else {
                _log.error("Exception in processing request from " + request.getRemoteAddr() + " to URL "
                        + String.valueOf(request.getRequestURL()));
                throw new ServletException(exc);
            }
        }
    } catch (SocketException exc) {
        _log.warn("Socket Exception: " + exc.getMessage());
    } catch (Exception exc) {
        _log.error("Exception in processing of request URL " + String.valueOf(request.getRequestURL()), exc);
        request.setAttribute(WGACore.ATTRIB_EXCEPTION, exc);
        throw new ServletException(exc);
    } catch (Error err) {
        _log.error("Error in processing of request URL " + String.valueOf(request.getRequestURL()), err);
        request.setAttribute(WGACore.ATTRIB_EXCEPTION, err);
        throw new ServletException(err);
    } finally {
        if (reqInfo != null) {
            reqInfo.setCommited(true);
        }
    }
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.Dump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("Dump", this);
    request.setCharacterEncoding("ISO_8859_1");
    getServletContext().setAttribute("Dump", this);

    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {/*w  w  w .ja v a 2 s  . c  om*/
            throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance());
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }

    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(redirect);
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String error = request.getParameter("error");
    if (error != null && error.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }

    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));

    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");

    if (info != null && info.indexOf("Locale/") >= 0) {
        try {
            String locale_name = info.substring(info.indexOf("Locale/") + 7);
            Field f = java.util.Locale.class.getField(locale_name);
            response.setLocale((Locale) f.get(null));
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            response.setLocale(Locale.getDefault());
        }
    }

    String cn = request.getParameter("cookie");
    String cv = request.getParameter("value");
    String v = request.getParameter("version");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        cookie.setComment("Cookie from dump servlet");
        if (v != null) {
            cookie.setMaxAge(300);
            cookie.setPath("/");
            cookie.setVersion(Integer.parseInt(v));
        }
        response.addCookie(cookie);
    }

    String pi = request.getPathInfo();
    if (pi != null && pi.startsWith("/ex")) {
        OutputStream out = response.getOutputStream();
        out.write("</H1>This text should be reset</H1>".getBytes());
        if ("/ex0".equals(pi))
            throw new ServletException("test ex0", new Throwable());
        if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        if ("/ex3".equals(pi))
            throw new HttpException(501);
    }

    PrintWriter pout = response.getWriter();
    Page page = null;

    try {
        page = new Page();
        page.title("Dump Servlet");

        page.add(new Heading(1, "Dump Servlet"));
        Table table = new Table(0).cellPadding(0).cellSpacing(0);
        page.add(table);
        table.newRow();
        table.addHeading("getMethod:&nbsp;").cell().right();
        table.addCell("" + request.getMethod());
        table.newRow();
        table.addHeading("getContentLength:&nbsp;").cell().right();
        table.addCell(Integer.toString(request.getContentLength()));
        table.newRow();
        table.addHeading("getContentType:&nbsp;").cell().right();
        table.addCell("" + request.getContentType());
        table.newRow();
        table.addHeading("getCharacterEncoding:&nbsp;").cell().right();
        table.addCell("" + request.getCharacterEncoding());
        table.newRow();
        table.addHeading("getRequestURI:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURI());
        table.newRow();
        table.addHeading("getRequestURL:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURL());
        table.newRow();
        table.addHeading("getContextPath:&nbsp;").cell().right();
        table.addCell("" + request.getContextPath());
        table.newRow();
        table.addHeading("getServletPath:&nbsp;").cell().right();
        table.addCell("" + request.getServletPath());
        table.newRow();
        table.addHeading("getPathInfo:&nbsp;").cell().right();
        table.addCell("" + request.getPathInfo());
        table.newRow();
        table.addHeading("getPathTranslated:&nbsp;").cell().right();
        table.addCell("" + request.getPathTranslated());
        table.newRow();
        table.addHeading("getQueryString:&nbsp;").cell().right();
        table.addCell("" + request.getQueryString());

        table.newRow();
        table.addHeading("getProtocol:&nbsp;").cell().right();
        table.addCell("" + request.getProtocol());
        table.newRow();
        table.addHeading("getScheme:&nbsp;").cell().right();
        table.addCell("" + request.getScheme());
        table.newRow();
        table.addHeading("getServerName:&nbsp;").cell().right();
        table.addCell("" + request.getServerName());
        table.newRow();
        table.addHeading("getServerPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getServerPort()));
        table.newRow();
        table.addHeading("getLocalName:&nbsp;").cell().right();
        table.addCell("" + request.getLocalName());
        table.newRow();
        table.addHeading("getLocalAddr:&nbsp;").cell().right();
        table.addCell("" + request.getLocalAddr());
        table.newRow();
        table.addHeading("getLocalPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getLocalPort()));
        table.newRow();
        table.addHeading("getRemoteUser:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteUser());
        table.newRow();
        table.addHeading("getRemoteAddr:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteAddr());
        table.newRow();
        table.addHeading("getRemoteHost:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteHost());
        table.newRow();
        table.addHeading("getRemotePort:&nbsp;").cell().right();
        table.addCell("" + request.getRemotePort());
        table.newRow();
        table.addHeading("getRequestedSessionId:&nbsp;").cell().right();
        table.addCell("" + request.getRequestedSessionId());
        table.newRow();
        table.addHeading("isSecure():&nbsp;").cell().right();
        table.addCell("" + request.isSecure());

        table.newRow();
        table.addHeading("isUserInRole(admin):&nbsp;").cell().right();
        table.addCell("" + request.isUserInRole("admin"));

        table.newRow();
        table.addHeading("getLocale:&nbsp;").cell().right();
        table.addCell("" + request.getLocale());

        Enumeration locales = request.getLocales();
        while (locales.hasMoreElements()) {
            table.newRow();
            table.addHeading("getLocales:&nbsp;").cell().right();
            table.addCell(locales.nextElement());
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers")
                .attribute("COLSPAN", "2").left();
        Enumeration h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();

            Enumeration h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().right();
                table.addCell(hv);
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters")
                .attribute("COLSPAN", "2").left();
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().right();
            table.addCell(request.getParameter(name));
            String[] values = request.getParameterValues(name);
            if (values == null) {
                table.newRow();
                table.addHeading(name + " Values:&nbsp;").cell().right();
                table.addCell("NULL!!!!!!!!!");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    table.newRow();
                    table.addHeading(name + "[" + i + "]:&nbsp;").cell().right();
                    table.addCell(values[i]);
                }
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left();
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            table.newRow();
            table.addHeading(cookie.getName() + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell(cookie.getValue());
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes")
                .attribute("COLSPAN", "2").left();
        Enumeration a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>");
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>");
        }

        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")
                && request.getContentLength() < 1000000) {
            MultiPartRequest multi = new MultiPartRequest(request);
            String[] parts = multi.getPartNames();

            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content")
                    .attribute("COLSPAN", "2").left();
            for (int p = 0; p < parts.length; p++) {
                name = parts[p];
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
                table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>");
            }
        }

        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res)
                    .attribute("COLSPAN", "2").left();

            table.newRow();
            table.addHeading("this.getClass():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getResource(res));

            table.newRow();
            table.addHeading("this.getClass().getClassLoader():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getClassLoader().getResource(res));

            table.newRow();
            table.addHeading("Thread.currentThread().getContextClassLoader():&nbsp;").cell().right();
            table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res));

            table.newRow();
            table.addHeading("getServletContext():&nbsp;").cell().right();
            try {
                table.addCell("" + getServletContext().getResource(res));
            } catch (Exception e) {
                table.addCell("" + e);
            }
        }

        /* ------------------------------------------------------------ */
        page.add(Break.para);
        page.add(new Heading(1, "Request Wrappers"));
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            page.add((w++) + ": " + rw.getClass().getName() + "<br/>");
            if (rw instanceof HttpServletRequestWrapper)
                rw = ((HttpServletRequestWrapper) rw).getRequest();
            else if (rw instanceof ServletRequestWrapper)
                rw = ((ServletRequestWrapper) rw).getRequest();
            else
                rw = null;
        }

        page.add(Break.para);
        page.add(new Heading(1, "International Characters"));
        page.add("Directly encoced:  Drst<br/>");
        page.add("HTML reference: D&uuml;rst<br/>");
        page.add("Decimal (252) 8859-1: D&#252;rst<br/>");
        page.add("Hex (xFC) 8859-1: D&#xFC;rst<br/>");
        page.add(
                "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>");
        page.add(Break.para);
        page.add(new Heading(1, "Form to generate GET content"));
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("GET");
        tf.addTextField("TextField", "TextField", 20, "value");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(Break.para);
        page.add(new Heading(1, "Form to generate POST content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("TextField", "TextField", 20, "value");
        Select select = tf.addSelect("Select", "Select", true, 3);
        select.add("ValueA");
        select.add("ValueB1,ValueB2");
        select.add("ValueC");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(new Heading(1, "Form to upload content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.attribute("enctype", "multipart/form-data");
        tf.addFileField("file", "file");
        tf.addButton("Upload", "Upload");
        page.add(tf);

        page.add(new Heading(1, "Form to get Resource"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("resource", "resource", 20, "");
        tf.addButton("Action", "getResource");
        page.add(tf);

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

    page.write(pout);

    String data = request.getParameter("data");
    if (data != null && data.length() > 0) {
        int d = Integer.parseInt(data);
        while (d > 0) {
            pout.println("1234567890123456789012345678901234567890123456789\n");
            d = d - 50;

        }
    }

    pout.close();

    if (pi != null) {
        if ("/ex4".equals(pi))
            throw new ServletException("test ex4", new Throwable());
        if ("/ex5".equals(pi))
            throw new IOException("test ex5");
        if ("/ex6".equals(pi))
            throw new UnavailableException("test ex6");
        if ("/ex7".equals(pi))
            throw new HttpException(501);
    }

    request.getInputStream().close();

}

From source file:de.innovationgate.wgpublisher.WGACore.java

public WGDatabase openContentDB(WGDatabase db, HttpServletRequest request, HttpSession session,
        boolean useMaster, WGDatabase hintDB) throws WGException {

    // If already open, and useMaster==isMaster, just return
    if (db.isSessionOpen()) {
        if (db.getSessionContext().isMasterSession() == useMaster) {
            return db;
        }//from   ww w .  j  av  a 2  s  .c o m
    }

    // If db is not ready throw an exception
    if (!db.isReady()) {
        throw new WGUnavailableException(db);
    }

    // Force master login
    if (useMaster) {
        db.openSession();
        return prepareDB(db, request);
    }

    // check client access to this db
    if (request != null && !this.isClientPermitted(db, request)) {
        throw new ClientAccessException("Client '" + request.getRemoteAddr()
                + "' is not permitted to access app '" + db.getDbReference() + "'.");
    }

    // Load config and login info from domain
    WGADomain domainConfig = getDomainForDatabase(db);
    DBLoginInfo sessionLoginInfo = null;
    String accessFilter = null;
    if (session != null) {
        sessionLoginInfo = WGACore.getSessionLogins(session).get(domainConfig.getName());
        if (sessionLoginInfo != null) {
            if (sessionLoginInfo.getDbAccessFilters().containsKey(db.getDbReference())) {
                accessFilter = sessionLoginInfo.getDbAccessFilters().get(db.getDbReference());
            } else {
                accessFilter = sessionLoginInfo.getAccessFilter();
            }
        }
    }

    // Check if regular or request based login is forced by some filter
    Boolean forceRegular = (request != null ? (Boolean) request.getAttribute(ATTRIB_FORCEREGULARLOGIN) : null);
    if (forceRegular == null) {
        forceRegular = Boolean.FALSE;
    }
    Boolean forceRequestBased = (request != null ? (Boolean) request.getAttribute(ATTRIB_FORCEREQUESTBASELOGIN)
            : null);
    if (forceRequestBased == null) {
        forceRequestBased = Boolean.FALSE;
    }

    // Load HTTP basic auth information
    DBLoginInfo httpLoginInfo = (request != null
            ? (DBLoginInfo) request.getAttribute(WGPRequestPath.REQATTRIB_HTTPLOGIN)
            : null);

    // Certificate based login
    if (request != null && !forceRegular.booleanValue() && db.certAuthEnabled()) {
        return openContentDBCertAuth(db, request, accessFilter);
    }

    // Requestinfo based login
    else if (request != null && (!forceRegular || forceRequestBased) && db.getAuthenticationModule() != null
            && db.getAuthenticationModule() instanceof RequestBasedAuthenticationModule) {
        return openContentDBRequestBased(db, request, accessFilter);
    }

    // HTTP basic authentication login
    else if (httpLoginInfo != null) {
        getBruteForceLoginBlocker().login(db, httpLoginInfo.getUserName(), httpLoginInfo.getCredentials(),
                accessFilter);
        if (db.isSessionOpen() && session != null) {
            updateLoginInfo(db, request, DBLoginInfo.AuthType.PASSWORD);
        }
        return prepareDB(db, request);
    }

    // do standard login process
    else {

        // Try to login via session token
        if (request != null && db.hasFeature(WGDatabase.FEATURE_SESSIONTOKEN)) {
            String cookieName = (String) db.getAttribute(WGACore.DBATTRIB_SESSIONCOOKIE);
            if (cookieName != null) {
                Cookie[] cookies = request.getCookies();
                if (cookies != null) { // Can actually happen, especially
                                       // with
                                       // non-browser http clients
                    Cookie tokenCookie = null;
                    for (int idx = 0; idx < cookies.length; idx++) {
                        if (cookies[idx].getName().equals(cookieName)) {
                            tokenCookie = cookies[idx];
                            break;
                        }
                    }
                    if (tokenCookie != null) {
                        db.openSession(WGDatabase.SESSIONTOKEN_USER, tokenCookie.getValue(), accessFilter,
                                request);
                        if (db.isSessionOpen()) {
                            // CONSIDERED HARMFUL: Session tokens may
                            // expire. Safer to always retrieve "fresh" from
                            // cookie
                            // loginInfo = new
                            // DBLoginInfo(WGDatabase.SESSIONTOKEN_USER,
                            // tokenCookie.getValue());
                            // this.getSessionLogins(session).put(domainConfig.getName(),
                            // loginInfo);
                            return prepareDB(db, request);
                        }
                    }
                }
            }
        }

        // If no session available, log in by hint or anonymous
        if (session == null) {

            if (hintDB != null && hintDB.isSessionOpen()) {
                if (hintDB.getSessionContext().isMasterSession()) {
                    db.openSession();
                } else {
                    db.openSession(hintDB.getSessionContext().getUser(),
                            hintDB.getSessionContext().getPassword(), accessFilter, request);
                }
                if (db.isSessionOpen()) {
                    return prepareDB(db, request);
                }

            }

            db.openSession(WGDatabase.ANONYMOUS_USER, null, null, request);
            return prepareDB(db, request);
        }

        // Try to login by previously stored domain-specific login
        if (sessionLoginInfo != null && !WGDatabase.ANONYMOUS_USER.equals(sessionLoginInfo.getUserName())) {
            int accessLevel = db.openSession(sessionLoginInfo.getUserName(), sessionLoginInfo.getCredentials(),
                    accessFilter, request);
            if (accessLevel > WGDatabase.ACCESSLEVEL_NOTLOGGEDIN) {
                return prepareDB(db, request);
            } else {
                if (domainConfig.getAuthModule() != null) {
                    getLog().warn("User '" + sessionLoginInfo.getUserName() + "' could not login to database '"
                            + db.getAttribute(DBATTRIB_DBKEY)
                            + "' although she/he could login to the domain authentication. Is the domain '"
                            + db.getAttribute(DBATTRIB_DOMAIN) + "' misconfigured?");
                } else {
                    getLog().warn("User '" + sessionLoginInfo.getUserName() + "' could not login to database '"
                            + db.getAttribute(DBATTRIB_DBKEY)
                            + "' although another db in the same domain permitted it. Is the domain '"
                            + db.getAttribute(DBATTRIB_DOMAIN) + "' misconfigured?");
                }
                // Misconfigured domains will no longer result in dropped
                // logins
                // this.getSessionLogins(session).remove(domain);
            }
        }

        // Anonymous login, if nothing else applies. CANNOT BE STORED, bc.
        // Sessionlogins may suddenly be available without notice
        db.openSession(WGDatabase.ANONYMOUS_USER, null, accessFilter, request);
        return prepareDB(db, request);
    }
}

From source file:edu.harvard.iq.dvn.core.web.subsetting.AnalysisPage.java

public String dwnldAction() {
    dbgLog.fine("***** within dwnldAction() *****");

    resetMsgDwnldButton();/* ww  w .  j av  a2 s  .  c  o  m*/

    if (checkDwnldParameters()) {

        FacesContext cntxt = FacesContext.getCurrentInstance();

        HttpServletResponse res = (HttpServletResponse) cntxt.getExternalContext().getResponse();

        HttpServletRequest req = (HttpServletRequest) cntxt.getExternalContext().getRequest();

        StudyFile sf = dataTable.getStudyFile();

        Long noRecords = dataTable.getRecordsPerCase();

        String dsbUrl = getDsbUrl();
        dbgLog.fine("dsbUrl=" + dsbUrl);

        String serverPrefix = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath();

        dbgLog.fine("serverPrefix" + serverPrefix);

        Map<String, List<String>> mpl = new HashMap<String, List<String>>();

        // File inFile = new File(sf.getFileSystemLocation());
        // File origFile = new File(inFile.getParent(), "_" + sf.getFileSystemName());

        String formatType = (String) dwnldFileTypeSet.getValue();
        dbgLog.fine("file type from the binding=" + formatType);
        if (formatType == null) {
            formatType = dwnldFileTypeSelected;
            dbgLog.fine("file type from the value=" + dwnldFileTypeSelected);
        }
        mpl.put("dtdwnld", Arrays.asList(formatType));

        dbgLog.fine("citation info to be sent:\n" + getCitation());

        mpl.put("studytitle", Arrays.asList(getStudyTitle()));
        dbgLog.fine("studyId=" + getStudyId().toString());
        mpl.put("studyno", Arrays.asList(getStudyId().toString()));
        mpl.put("studyURL", Arrays.asList(studyURL));

        mpl.put("", Arrays.asList(""));
        mpl.put("browserType", Arrays.asList(browserType));

        mpl.put("recodedVarIdSet", getRecodedVarIdSet());
        mpl.put("recodedVarNameSet", getRecodedVarNameSet());
        mpl.put("recodedVarLabelSet", getRecodedVarLabelSet());
        mpl.put("recodedVarTypeSet", getRecodedVariableType());
        mpl.put("recodedVarBaseTypeSet", getBaseVariableTypeForRecodedVariable());

        mpl.put("baseVarIdSet", getBaseVarIdSetFromRecodedVarIdSet());
        mpl.put("baseVarNameSet", getBaseVarNameSetFromRecodedVarIdSet());

        mpl.put("requestType", Arrays.asList("Download"));

        // Added by Matt Owen to find a way to sneak in Metadata that is lost between Rdata -> Tab 
        mpl.put("originalFile", Arrays.asList(getOriginalFileSystemLocation().getAbsolutePath()));

        // -----------------------------------------------------
        // Processing route, step by step:
        // 
        // Step 0. Locate the data file and its attributes

        String fileId = sf.getId().toString();

        String fileloc = sf.getFileSystemLocation();
        String tabflnm = sf.getFileName();
        boolean sbstOK = sf.isSubsettable();
        String flct = sf.getFileType();

        // Output debug statements
        dbgLog.info("location=" + fileloc);
        dbgLog.info("filename=" + tabflnm);
        dbgLog.info("subsettable=" + sbstOK);
        dbgLog.info("filetype=" + flct);
        dbgLog.info("studyUrl = " + studyURL);
        dbgLog.info("original file asbolute path = " + getOriginalFileSystemLocation().getAbsolutePath());

        // D
        DvnRJobRequest sro = null;

        List<File> zipFileList = new ArrayList();

        File tmpsbfl = null;

        if (sbstOK) {

            try {

                // this temp file will store the requested column(s):
                tmpsbfl = File.createTempFile("tempsubsetfile.", ".tab");
                deleteTempFileList.add(tmpsbfl);

                // to produce this file, we'll either open the stream
                // and run our local subsetting code on it, or request
                // the subsetting to be performed natively by the access
                // driver, if it supports the functionality:

                // check whether a source file is tab-delimited or not

                boolean fieldcut = true;
                if ((noRecords != null) && (noRecords >= 1)) {
                    fieldcut = false;
                }

                DataAccessRequest daReq = new DataAccessRequest();
                daReq.setParameter("noVarHeader", "1");

                DataAccessObject accessObject = DataAccess.createDataAccessObject(sf, daReq);

                if (accessObject.isSubsetSupported()) {
                    dbgLog.fine("Using NATIVE subset functionality of the repository.");
                    daReq.setParameter("vars", getVariableNamesForSubset());

                    accessObject.open();

                    InputStream inSubset = accessObject.getInputStream();
                    OutputStream outSubset = new BufferedOutputStream(
                            new FileOutputStream(tmpsbfl.getAbsolutePath()));

                    int bufsize = 8192;
                    byte[] subsetDataBuffer = new byte[bufsize];
                    while ((bufsize = inSubset.read(subsetDataBuffer)) != -1) {
                        outSubset.write(subsetDataBuffer, 0, bufsize);
                    }

                    inSubset.close();
                    outSubset.close();

                    // TODO: catch exceptions; reset the state of the page
                    // if anything went wrong. See the fixed-field section
                    // below for an example.

                } else {
                    accessObject.open();

                    if (fieldcut) {
                        // Cutting requested fields of data from a TAB-delimited stream:

                        Set<Integer> fields = getFieldNumbersForSubsetting();
                        dbgLog.fine("subsetting fields=" + fields);

                        // Create an instance of DvnJavaFieldCutter
                        FieldCutter fc = new DvnJavaFieldCutter();

                        // Executes the subsetting request
                        fc.subsetFile(accessObject.getInputStream(), tmpsbfl.getAbsolutePath(), fields,
                                dataTable.getCaseQuantity(), "\t");

                        // TODO: catch exceptions; reset the state of the page
                        // if anything went wrong. See the fixed-field section
                        // below for an example.

                    } else {
                        // Cutting requested columns of data from a fixed-field stream:

                        Map<Long, List<List<Integer>>> varMetaSet = getSubsettingMetaData(noRecords);
                        DvnNewJavaFieldCutter fc = new DvnNewJavaFieldCutter(varMetaSet);

                        try {
                            //fc.cutColumns(new File(cutOp1), noRecords.intValue(), 0, "\t", tmpsbfl.getAbsolutePath());
                            fc.cutColumns(accessObject.getInputStream(), noRecords.intValue(), 0, "\t",
                                    tmpsbfl.getAbsolutePath());
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();

                            msgDwnldButton.setValue("* could not generate subset due to an IO problem");
                            msgDwnldButton.setVisible(true);
                            dbgLog.warning("exiting dwnldAction() due to an IO problem ");
                            getVDCRequestBean().setSelectedTab("tabDwnld");
                            dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                            return "";

                        } catch (RuntimeException re) {
                            re.printStackTrace();

                            msgDwnldButton.setValue("* could not generate subset due to an runtime error");
                            msgDwnldButton.setVisible(true);
                            dbgLog.warning("exiting dwnldAction() due to an runtime error");
                            getVDCRequestBean().setSelectedTab("tabDwnld");
                            dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                            return "";

                        }

                    }
                }

                // Checks the resulting subset file:

                if (tmpsbfl.exists()) {
                    Long subsetFileSize = tmpsbfl.length();
                    dbgLog.fine("subset file:Length=" + subsetFileSize);
                    dbgLog.fine("subset file:name=" + tmpsbfl.getAbsolutePath());

                    if (subsetFileSize > 0) {
                        mpl.put("subsetFileName", Arrays.asList(tmpsbfl.getAbsolutePath()));
                        mpl.put("subsetDataFileName", Arrays.asList(tmpsbfl.getName()));
                    } else {
                        // subset file exists but it is empty

                        msgDwnldButton.setValue("* an subset file is empty");
                        msgDwnldButton.setVisible(true);
                        dbgLog.warning(
                                "exiting dwnldAction() due to a subsetting error:" + "a subset file is empty");
                        getVDCRequestBean().setSelectedTab("tabDwnld");
                        dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                        return "";

                    }
                } else {
                    // subset file was not created
                    msgDwnldButton.setValue("* a subset file was not created");
                    msgDwnldButton.setVisible(true);
                    dbgLog.warning("exiting dwnldAction() due to a subsetting error:"
                            + "a subset file was not created");
                    getVDCRequestBean().setSelectedTab("tabDwnld");
                    dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                    return "";

                }

                // If we've made it this far, we can increment the number of
                // downloads for the study file:

                VDC vdc = vdcService.getVDCFromRequest(req);
                GuestBookResponse guestbookResponse = (GuestBookResponse) getVDCSessionBean()
                        .getGuestbookResponseMap().get("guestBookResponse_" + sf.getStudy().getId());

                if (guestbookResponse == null) {
                    //need to set up dummy network response
                    guestbookResponse = guestBookResponseServiceBean.initNetworkGuestBookResponse(sf.getStudy(),
                            sf, getVDCSessionBean().getLoginBean());
                }
                guestbookResponse.setStudyVersion(sf.getStudy().getStudyVersionByNumber(versionNumber));
                String jsessionId = null;
                Cookie cookies[] = req.getCookies();

                for (int i = 0; i < cookies.length; i++) {
                    if ("JSESSIONID".equals(cookies[i].getName())) {
                        jsessionId = cookies[i].getValue();
                    }
                }

                if (jsessionId == null || "".equals(jsessionId)) {
                    String[] stringArray = getVDCSessionBean().toString().split("@");
                    jsessionId = stringArray[1];
                }

                guestbookResponse.setSessionId(jsessionId);

                String friendlyFormatName = "";
                String formatRequestedMimeType = "";

                if (formatType != null && !"".equals(formatType)) {
                    if (formatType.equals("D00")) {
                        formatRequestedMimeType = "text/tab-separated-values"; // tabular
                    } else if (formatType.equals("D01")) {
                        formatRequestedMimeType = "text/tab-separated-values"; // fixed-field
                    } else {
                        for (DataFileFormatType type : studyService.getDataFileFormatTypes()) {
                            if (formatType.equals(type.getValue())) {
                                formatRequestedMimeType = type.getMimeType();
                            }
                        }
                    }
                }

                if (formatRequestedMimeType == null || "".equals(formatRequestedMimeType)) {
                    formatRequestedMimeType = "application/x-unknown";
                }

                friendlyFormatName = FileUtil.getUserFriendlyTypeForMime(formatRequestedMimeType);
                guestbookResponse.setDownloadtype("Subsetting - " + friendlyFormatName);

                if (vdc != null) {
                    studyService.incrementNumberOfDownloads(sf.getId(), vdc.getId(),
                            (GuestBookResponse) guestbookResponse);
                } else {
                    studyService.incrementNumberOfDownloads(sf.getId(), (Long) null,
                            (GuestBookResponse) guestbookResponse);
                }

                // Step 3. Organizes parameters/metadata to be sent to the implemented
                // data-analysis-service class

                // skip the Rserve call completely (for plain tab file format, with no recoding)! -- L.A.
                if (!formatType.equals("D01") || (recodeSchema.size() > 0)) {

                    Map<String, Map<String, String>> vls = getValueTablesForAllRequestedVariables();

                    // New (as of 3.6): support for ordered categorical variables 
                    // (ingested from R ordered factors). 
                    // Note that this is only being added here, i.e., to the 
                    // download-and-save part; if/when we make the analysis 
                    // and statistics utilize/handle these ordered categories 
                    // in some special way, we'll need to add the actual 
                    // ordered values to the SRO objects there as well. -- L.A. 

                    Map<String, List<String>> categoryOrders = getCategoryValueOrdersForAllRequestedVariables();

                    if (categoryOrders != null) {
                        sro = new DvnRJobRequest(getDataVariableForRequest(), mpl, vls, recodeSchema,
                                categoryOrders, null);
                    } else {
                        sro = new DvnRJobRequest(getDataVariableForRequest(), mpl, vls, recodeSchema);
                    }

                    /*
                     * Add the recoded -> base variable name map; (new as of v3.6;)
                     * TODO: (?) do the same for the other action requests. 
                     *          -- L.A.
                     */
                    sro.setRecodedToBaseVar(getRecodedVarToBaseVarName());

                    // dbgLog.fine("sro dump:\n"+ToStringBuilder.reflectionToString(sro, ToStringStyle.MULTI_LINE_STYLE));

                    // Step 4. Creates an instance of the the implemented
                    // data-analysis-service class

                    DvnRDataAnalysisServiceImpl das = new DvnRDataAnalysisServiceImpl();

                    // Executes a download or data analysis request and
                    // stores the results in a Map <String, String>

                    resultInfo = das.execute(sro);

                    // Step 5. Check the exit status of the R process:

                    if (resultInfo.get("RexecError").equals("true")) {

                        msgDwnldButton.setValue("* The Request failed due to an R-runtime error");
                        msgDwnldButton.setVisible(true);
                        dbgLog.fine("exiting dwnldAction() due to an R-runtime error");
                        getVDCRequestBean().setSelectedTab("tabDwnld");
                        dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                        return "";
                    }
                }

                if (recodeSchema.size() > 0) {
                    resultInfo.put("subsettingCriteria", sro.getSubsetConditionsForCitation());
                } else {
                    resultInfo.put("subsettingCriteria", "variables: " + getVariableNamesForSubset());
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();

                msgDwnldButton.setValue("* file URL is malformed");
                msgDwnldButton.setVisible(true);
                dbgLog.warning("exiting dwnldAction() due to a URL problem ");
                getVDCRequestBean().setSelectedTab("tabDwnld");

                return "";

            } catch (IOException e) {
                // this may occur if the dataverse is not released,
                // or if the file exists, but it is not accessible, etc.
                e.printStackTrace();

                msgDwnldButton.setValue("* an IO problem occurred");
                msgDwnldButton.setVisible(true);
                dbgLog.warning("exiting dwnldAction() due to an IO problem ");
                getVDCRequestBean().setSelectedTab("tabDwnld");

                return "";
            }

            // end of subset-OK case
        } else {
            // not subsettable data file
            msgDwnldButton.setValue("* this data file is not subsettable file");
            msgDwnldButton.setVisible(true);
            dbgLog.warning("exiting dwnldAction(): the data file is not subsettable ");
            getVDCRequestBean().setSelectedTab("tabDwnld");
            dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
            return "";

        } // end:subsetNotOKcase

        // final processing steps for all successful cases
        // add study-metadata to the resultInfo map

        if (formatType.equals("D01") && !(recodeSchema.size() > 0)) {
            resultInfo.put("wbDataFileName", tmpsbfl.getAbsolutePath());
            // Fields that would normally be populated by R:

            resultInfo.put("PID", "N/A");
            resultInfo.put("R_min_verion_no", "N/A");
            resultInfo.put("dsbHost", "N/A");
            Date now = new Date();
            resultInfo.put("RexecDate", now.toString());
        } else {
            resultInfo.put("R_min_verion_no", resultInfo.get("Rversion").substring(2));
        }

        resultInfo.put("offlineCitation", getCitation());
        resultInfo.put("studyTitle", getStudyTitle());
        resultInfo.put("studyNo", getStudyId().toString());
        resultInfo.put("dtId", dtId.toString());
        if (versionNumber != null) {
            resultInfo.put("versionNumber", versionNumber.toString());
        }
        resultInfo.put("studyURL", studyURL);
        resultInfo.put("dataverse_version_no", dvnVersionNumber);

        resultInfo.put("option", "subset");
        resultInfo.put("variableList", getVariableNamesForSubset());

        // calculate UNF (locally, on the application side):

        List<DataVariable> subsetVariableList = getDataVariableForRequest();

        String subsetUNFvalue = "[NOT CALCULATED]";

        String[] unfValues = new String[subsetVariableList.size()];

        for (int i = 0; i < subsetVariableList.size(); i++) {
            unfValues[i] = subsetVariableList.get(i).getUnf();
        }

        dbgLog.fine("unf set:\n" + Arrays.deepToString(unfValues));

        try {
            subsetUNFvalue = UNF5Util.calculateUNF(unfValues);

        } catch (NumberFormatException ex) {
            // if anything went wrong during the UNF calculation, it's not
            // a fatal condition; we'll just be displaying "not calculated"
            // instead of the UNF in the final README file.

            dbgLog.fine("error while trying to calculate subset UNF: Number Format Exception.");
            ex.printStackTrace();
        } catch (IOException ex) {
            dbgLog.fine("error while trying to calculate subset UNF: IO Exception.");
            ex.printStackTrace();
        }

        resultInfo.put("fileUNF", subsetUNFvalue);

        // writing necessary files:

        try {

            if (formatType.equals("D01") && !(recodeSchema.size() > 0)) {
                // (2) tab-delimited-format-only step:
                //
                // In the final zip file we package the subset file
                // and a replication README file (also contains citation). 
                // We also *used to* include the SAS, SPSS and R control
                // files created by R. We are not doing this anymore, but 
                // I left the code commented-out below. 
                //                  -- L.A. Jan. 2012
                //
                // We are also adding the variable header to the file here.

                /* SKIP CODE FILES -- L.A.
                String codeFileSas = "codeFile_sas_" + resultInfo.get("PID") + ".sas";
                File tmpCCsasfl = new File(TEMP_DIR, codeFileSas);
                        
                deleteTempFileList.add(tmpCCsasfl);
                zipFileList.add(tmpCCsasfl);
                        
                String codeFileSpss = "codeFile_spss_" + resultInfo.get("PID") + ".sps";
                File tmpCCspsfl = new File(TEMP_DIR, codeFileSpss);
                        
                deleteTempFileList.add(tmpCCspsfl);
                zipFileList.add(tmpCCspsfl);
                        
                String codeFileStata = "codeFile_stata_" + resultInfo.get("PID") + ".do";
                File tmpCCdofl  = new File(TEMP_DIR, codeFileStata);
                        
                deleteTempFileList.add(tmpCCdofl);
                zipFileList.add(tmpCCdofl);
                        
                StatisticalCodeFileWriter scfw = new StatisticalCodeFileWriter(sro);
                scfw.write(tmpCCsasfl, tmpCCspsfl, tmpCCdofl);
                 */

                // add the subset file:

                File tmpsbflnew = File.createTempFile("tempsubsetfile_new.", ".tab");
                deleteTempFileList.add(tmpsbflnew);

                InputStream inb = new BufferedInputStream(new FileInputStream(tmpsbfl));
                OutputStream outb = new BufferedOutputStream(new FileOutputStream(tmpsbflnew));

                String varHeaderLine = getVariableHeaderForSubset();
                // Add the variable header to the subset file:
                byte[] varHeaderBuffer = null;
                varHeaderBuffer = varHeaderLine.getBytes();
                outb.write(varHeaderBuffer);
                outb.flush();

                int bufsize;
                byte[] bffr = new byte[8192];
                while ((bufsize = inb.read(bffr)) != -1) {
                    outb.write(bffr, 0, bufsize);
                }
                inb.close();
                outb.close();

                dbgLog.fine("adding tab file: " + tmpsbflnew.getName());
                zipFileList.add(tmpsbflnew);

            } else {

                // (2)The format-converted subset data file
                String wbDataFileName = resultInfo.get("wbDataFileName");
                dbgLog.fine("wbDataFileName=" + wbDataFileName);

                File wbSubsetDataFile = new File(wbDataFileName);
                if (wbSubsetDataFile.exists()) {
                    dbgLog.fine("wbSubsetDataFile:length=" + wbSubsetDataFile.length());
                    deleteTempFileList.add(wbSubsetDataFile);
                    zipFileList.add(wbSubsetDataFile);
                } else {
                    // the data file was not created
                    dbgLog.fine("wbSubsetDataFile does not exist");

                    msgDwnldButton.setValue("* The requested data file is not available");
                    msgDwnldButton.setVisible(true);
                    dbgLog.warning("exiting dwnldAction(): data file was not transferred");
                    getVDCRequestBean().setSelectedTab("tabDwnld");
                    dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                    return "";
                }
            }

            // Create README file:

            String readMeFileName = null;

            if (resultInfo.get("PID") != null && !resultInfo.get("PID").equals("N/A")) {
                readMeFileName = REP_README_FILE_PREFIX + resultInfo.get("PID") + ".txt";
            } else {
                readMeFileName = REP_README_FILE_PREFIX + fileId + ".txt";
            }

            File readMeFile = new File(TEMP_DIR, readMeFileName);

            DvnReplicationREADMEFileWriter rw = new DvnReplicationREADMEFileWriter(resultInfo);
            rw.writeREADMEfile(readMeFile, true);

            zipFileList.add(readMeFile);
            deleteTempFileList.add(readMeFile);

            for (File f : zipFileList) {
                dbgLog.fine("file to zip: path=" + f.getAbsolutePath() + "\tname=" + f.getName());
            }

            // We can now zip all the required files"
            try {
                String zipFilePrefix = null;

                if (resultInfo.get("PID") != null && !resultInfo.get("PID").equals("N/A")) {
                    zipFilePrefix = "zipFile_" + resultInfo.get("PID") + ".zip";
                } else {
                    zipFilePrefix = "zipFile_" + fileId + ".zip";

                }
                File zipFile = new File(TEMP_DIR, zipFilePrefix);

                //deleteTempFileList.add(zipFile);
                String zfname = zipFile.getName();
                zipFileName = zfname;
                zipFiles(new FileOutputStream(zipFile), zipFileList);

                /*
                try {
                Thread.sleep(1000);
                } catch (Exception e) {
                        
                }
                 */

                zipResourceDynFileName = new ByteArrayResource(
                        toByteArray(new FileInputStream(zipFile.getAbsolutePath())));
                dbgLog.info("Subsetting: zipFileName=" + zipFileName);
                dbgLog.info("Subsetting: zipFile, absolute path: " + zipFile.getAbsolutePath());
                dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);

                // Hide 'Create' button, show 'Download' button:
                dwnldButton.setRendered(false);
                dwnloadSubsetButton.setRendered(true);
                dbgLog.info("***** within dwnldAction(): ends here *****");

                /*
                 * Navigation: 
                 *  - is it necessary to use "faces-redirect" navigation here? 
                 *    Or should we simply return "" as long as we want to stay 
                 *    on the subsetting page?
                if (versionNumber != null) {
                    return "/study/SubsettingPage?faces-redirect=true&dtId=" + dtId + "&versionNumber=" + versionNumber;
                }
                return "/study/SubsettingPage?faces-redirect=true&dtId=" + dtId;
                 */
                return "";

            } catch (IOException e) {
                // file-access problem, etc.
                e.printStackTrace();
                dbgLog.fine("download zipping IO exception");
                msgDwnldButton.setValue("* an IO problem occurred");
                msgDwnldButton.setVisible(true);
                dbgLog.warning("exiting dwnldAction() due to an IO problem ");
                getVDCRequestBean().setSelectedTab("tabDwnld");
                dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                return "";
            }
            // end of zipping step

        } catch (IOException e) {
            e.printStackTrace();

            msgDwnldButton.setValue("* an IO problem occurred");
            msgDwnldButton.setVisible(true);
            dbgLog.warning("exiting dwnldAction() due to an IO problem ");
            getVDCRequestBean().setSelectedTab("tabDwnld");
            dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
            return "";
        }

        // end: params are OK-case
    } else {
        // the selection is incomplete
        // show error message;
        pgDwnldErrMsg.setRendered(true);
        msgDwnldButton.setValue("* Error: Select a file format");
        msgDwnldButton.setVisible(true);
        dbgLog.warning("exiting dwnldAction() due to incomplete data ");
        getVDCRequestBean().setSelectedTab("tabDwnld");

        return "";
    } // end: checking params

}