Example usage for javax.servlet.http HttpServletRequest getServerPort

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

Introduction

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

Prototype

public int getServerPort();

Source Link

Document

Returns the port number to which the request was sent.

Usage

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 {//from  w  w  w. jav  a  2s  . c o m
            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:io.github.microcks.web.RestController.java

@RequestMapping(value = "/{service}/{version}/**")
public ResponseEntity<?> execute(@PathVariable("service") String serviceName,
        @PathVariable("version") String version, @RequestParam(value = "delay", required = false) Long delay,
        @RequestBody(required = false) String body, HttpServletRequest request) {

    log.info("Servicing mock response for service [{}, {}] on uri {} with verb {}", serviceName, version,
            request.getRequestURI(), request.getMethod());
    log.debug("Request body: " + body);

    long startTime = System.currentTimeMillis();

    // Extract resourcePath for matching with correct operation.
    String requestURI = request.getRequestURI();
    String serviceAndVersion = null;
    String resourcePath = null;//from   ww  w  . j  ava 2  s  .c om

    try {
        // Build the encoded URI fragment to retrieve simple resourcePath.
        serviceAndVersion = "/" + UriUtils.encodeFragment(serviceName, "UTF-8") + "/" + version;
        resourcePath = requestURI.substring(requestURI.indexOf(serviceAndVersion) + serviceAndVersion.length());
    } catch (UnsupportedEncodingException e1) {
        return new ResponseEntity<Object>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    log.info("Found resourcePath: " + resourcePath);

    Service service = serviceRepository.findByNameAndVersion(serviceName, version);
    Operation rOperation = null;
    for (Operation operation : service.getOperations()) {
        // Select operation based onto Http verb (GET, POST, PUT, etc ...)
        if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
            // ... then check is we have a matching resource path.
            if (operation.getResourcePaths().contains(resourcePath)) {
                rOperation = operation;
                break;
            }
        }
    }

    if (rOperation != null) {
        log.debug("Found a valid operation {} with rules: {}", rOperation.getName(),
                rOperation.getDispatcherRules());

        Response response = null;
        String uriPattern = getURIPattern(rOperation.getName());
        String dispatchCriteria = null;

        // Depending on dispatcher, evaluate request with rules.
        if (DispatchStyles.SEQUENCE.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.SCRIPT.equals(rOperation.getDispatcher())) {
            ScriptEngineManager sem = new ScriptEngineManager();
            try {
                // Evaluating request with script coming from operation dispatcher rules.
                ScriptEngine se = sem.getEngineByExtension("groovy");
                SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body, request);
                dispatchCriteria = (String) se.eval(rOperation.getDispatcherRules());
            } catch (Exception e) {
                log.error("Error during Script evaluation", e);
            }
        }
        // New cases related to services/operations/messages coming from a postman collection file.
        else if (DispatchStyles.URI_PARAMS.equals(rOperation.getDispatcher())) {
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        } else if (DispatchStyles.URI_PARTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.URI_ELEMENTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria += DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        }

        log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
        List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(
                IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
        if (!responses.isEmpty()) {
            response = responses.get(0);
        }

        if (response != null) {
            // Setting delay to default one if not set.
            if (delay == null && rOperation.getDefaultDelay() != null) {
                delay = rOperation.getDefaultDelay();
            }

            if (delay != null && delay > -1) {
                log.debug("Mock delay is turned on, waiting if necessary...");
                long duration = System.currentTimeMillis() - startTime;
                if (duration < delay) {
                    Object semaphore = new Object();
                    synchronized (semaphore) {
                        try {
                            semaphore.wait(delay - duration);
                        } catch (Exception e) {
                            log.debug("Delay semaphore was interrupted");
                        }
                    }
                }
                log.debug("Delay now expired, releasing response !");
            }

            // Publish an invocation event before returning.
            MockInvocationEvent event = new MockInvocationEvent(this, service.getName(), version,
                    response.getName(), new Date(startTime), startTime - System.currentTimeMillis());
            applicationContext.publishEvent(event);
            log.debug("Mock invocation event has been published");

            HttpStatus status = (response.getStatus() != null
                    ? HttpStatus.valueOf(Integer.parseInt(response.getStatus()))
                    : HttpStatus.OK);

            // Deal with specific headers (content-type and redirect directive).
            HttpHeaders responseHeaders = new HttpHeaders();
            if (response.getMediaType() != null) {
                responseHeaders.setContentType(MediaType.valueOf(response.getMediaType() + ";charset=UTF-8"));
            }

            // Adding other generic headers (caching directives and so on...)
            if (response.getHeaders() != null) {
                for (Header header : response.getHeaders()) {
                    if ("Location".equals(header.getName())) {
                        // We should process location in order to make relative URI specified an absolute one from
                        // the client perspective.
                        String location = "http://" + request.getServerName() + ":" + request.getServerPort()
                                + request.getContextPath() + "/rest" + serviceAndVersion
                                + header.getValues().iterator().next();
                        responseHeaders.add(header.getName(), location);
                    } else {
                        if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) {
                            responseHeaders.put(header.getName(), new ArrayList<>(header.getValues()));
                        }
                    }
                }
            }
            return new ResponseEntity<Object>(response.getContent(), responseHeaders, status);
        }
        return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}

From source file:com.portfolio.rest.RestServicePortfolio.java

@Path("/portfolios/portfolio/{portfolio-id}")
@GET/*from  www  . j a  v a  2 s. c o m*/
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "application/zip",
        MediaType.APPLICATION_OCTET_STREAM })
public Object getPortfolio(@CookieParam("user") String user, @CookieParam("credential") String token,
        @QueryParam("group") int groupId, @PathParam("portfolio-id") String portfolioUuid,
        @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest,
        @HeaderParam("Accept") String accept, @QueryParam("user") Integer userId,
        @QueryParam("group") Integer group, @QueryParam("resources") String resource,
        @QueryParam("files") String files, @QueryParam("export") String export,
        @QueryParam("lang") String lang) {
    UserInfo ui = checkCredential(httpServletRequest, user, token, null);

    Response response = null;
    try {
        String portfolio = dataProvider.getPortfolio(new MimeType("text/xml"), portfolioUuid, ui.userId, 0,
                this.label, resource, "", ui.subId).toString();

        if ("faux".equals(portfolio)) {
            response = Response.status(403).build();
        }

        if (response == null) {
            Date time = new Date();
            Document doc = DomUtils.xmlString2Document(portfolio, new StringBuffer());
            NodeList codes = doc.getDocumentElement().getElementsByTagName("code");
            // Le premier c'est celui du root
            Node codenode = codes.item(0);
            String code = "";
            if (codenode != null)
                code = codenode.getTextContent();

            if (export != null) {
                response = Response.ok(portfolio).header("content-disposition",
                        "attachment; filename = \"" + code + "-" + time + ".xml\"").build();
            } else if (resource != null && files != null) {
                //// Cas du renvoi d'un ZIP

                /// Temp file in temp directory
                File tempDir = new File(System.getProperty("java.io.tmpdir", null));
                File tempZip = File.createTempFile(portfolioUuid, ".zip", tempDir);

                FileOutputStream fos = new FileOutputStream(tempZip);
                ZipOutputStream zos = new ZipOutputStream(fos);
                //               BufferedOutputStream bos = new BufferedOutputStream(zos);

                /// zos.setComment("Some comment");

                /// Write xml file to zip
                ZipEntry ze = new ZipEntry(portfolioUuid + ".xml");
                zos.putNextEntry(ze);

                byte[] bytes = portfolio.getBytes("UTF-8");
                zos.write(bytes);

                zos.closeEntry();

                /// Find all fileid/filename
                XPath xPath = XPathFactory.newInstance().newXPath();
                String filterRes = "//asmResource/fileid";
                NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

                /// Direct link to data
                // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";

                /*
                String langatt = "";
                if( lang != null )
                   langatt = "?lang="+lang;
                else
                   langatt = "?lang=fr";
                //*/

                /// Fetch all files
                for (int i = 0; i < nodelist.getLength(); ++i) {
                    Node res = nodelist.item(i);
                    Node p = res.getParentNode(); // resource -> container
                    Node gp = p.getParentNode(); // container -> context
                    Node uuidNode = gp.getAttributes().getNamedItem("id");
                    String uuid = uuidNode.getTextContent();

                    String filterName = "./filename[@lang and text()]";
                    NodeList textList = (NodeList) xPath.compile(filterName).evaluate(p,
                            XPathConstants.NODESET);
                    String filename = "";
                    if (textList.getLength() != 0) {
                        Element fileNode = (Element) textList.item(0);
                        filename = fileNode.getTextContent();
                        lang = fileNode.getAttribute("lang");
                        if ("".equals(lang))
                            lang = "fr";
                    }

                    String servlet = httpServletRequest.getRequestURI();
                    servlet = servlet.substring(0, servlet.indexOf("/", 7));
                    String server = httpServletRequest.getServerName();
                    int port = httpServletRequest.getServerPort();
                    //                  "http://"+ server + /resources/resource/file/ uuid ? lang= size=
                    // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";
                    String url = "http://" + server + ":" + port + servlet + "/resources/resource/file/" + uuid
                            + "?lang=" + lang;
                    HttpGet get = new HttpGet(url);

                    // Transfer sessionid so that local request still get security checked
                    HttpSession session = httpServletRequest.getSession(true);
                    get.addHeader("Cookie", "JSESSIONID=" + session.getId());

                    // Send request
                    CloseableHttpClient client = HttpClients.createDefault();
                    CloseableHttpResponse ret = client.execute(get);
                    HttpEntity entity = ret.getEntity();

                    // Put specific name for later recovery
                    if ("".equals(filename))
                        continue;
                    int lastDot = filename.lastIndexOf(".");
                    if (lastDot < 0)
                        lastDot = 0;
                    String filenameext = filename.substring(0); /// find extension
                    int extindex = filenameext.lastIndexOf(".");
                    filenameext = uuid + "_" + lang + filenameext.substring(extindex);

                    // Save it to zip file
                    //                  int length = (int) entity.getContentLength();
                    InputStream content = entity.getContent();

                    //                  BufferedInputStream bis = new BufferedInputStream(entity.getContent());

                    ze = new ZipEntry(filenameext);
                    try {
                        int totalread = 0;
                        zos.putNextEntry(ze);
                        int inByte;
                        byte[] buf = new byte[4096];
                        //                     zos.write(bytes,0,inByte);
                        while ((inByte = content.read(buf)) != -1) {
                            totalread += inByte;
                            zos.write(buf, 0, inByte);
                        }
                        System.out.println("FILE: " + filenameext + " -> " + totalread);
                        content.close();
                        //                     bis.close();
                        zos.closeEntry();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    EntityUtils.consume(entity);
                    ret.close();
                    client.close();
                }

                zos.close();
                fos.close();

                /// Return zip file
                RandomAccessFile f = new RandomAccessFile(tempZip.getAbsoluteFile(), "r");
                byte[] b = new byte[(int) f.length()];
                f.read(b);
                f.close();

                response = Response.ok(b, MediaType.APPLICATION_OCTET_STREAM)
                        .header("content-disposition", "attachment; filename = \"" + code + "-" + time + ".zip")
                        .build();

                // Temp file cleanup
                tempZip.delete();
            } else {
                //try { this.userId = userId; } catch(Exception ex) { this.userId = -1; };
                //              String returnValue = dataProvider.getPortfolio(new MimeType("text/xml"),portfolioUuid,this.userId, this.groupId, this.label, resource, files).toString();
                if (portfolio.equals("faux")) {

                    throw new RestWebApplicationException(Status.FORBIDDEN,
                            "Vous n'avez pas les droits necessaires");
                }

                if (accept.equals(MediaType.APPLICATION_JSON)) {
                    portfolio = XML.toJSONObject(portfolio).toString();
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_JSON).build();
                } else
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_XML).build();

                logRestRequest(httpServletRequest, null, portfolio, Status.OK.getStatusCode());
            }
        }
    } catch (RestWebApplicationException ex) {
        throw new RestWebApplicationException(Status.FORBIDDEN, ex.getResponse().getEntity().toString());
    } catch (SQLException ex) {
        logRestRequest(httpServletRequest, null, "Portfolio " + portfolioUuid + " not found",
                Status.NOT_FOUND.getStatusCode());

        throw new RestWebApplicationException(Status.NOT_FOUND, "Portfolio " + portfolioUuid + " not found");
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, null, ex.getMessage() + "\n\n" + ex.getStackTrace(),
                Status.INTERNAL_SERVER_ERROR.getStatusCode());

        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        if (dataProvider != null)
            dataProvider.disconnect();
    }

    return response;
}

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

public String edaAction() {

    //        dbgLog.fine("selected tab(eda)="+getTabSet1().getSelected());
    // clear the error message around the EDA button if they exisit
    resetMsgEdaButton();/*from   w w w . j a va2 s  . co  m*/

    if (checkEdaParameters()) {

        FacesContext cntxt = FacesContext.getCurrentInstance();

        HttpServletResponse res = (HttpServletResponse) cntxt.getExternalContext().getResponse();
        HttpServletRequest req = (HttpServletRequest) cntxt.getExternalContext().getRequest();

        dbgLog.info("***** within edaAction() *****");

        StudyFile sf = dataTable.getStudyFile();
        Long noRecords = dataTable.getRecordsPerCase();

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

        String serverPrefix = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath();
        /*
        String serverPrefix = "http://dvn-alpha.hmdc.harvard.edu"
            + req.getContextPath();
        */
        dbgLog.info("serverPrefix" + serverPrefix);

        /*
         * "optnlst_a" => "A01|A02|A03",
         * "analysis" => "A01 A02",
         * "varbl" => "v1.3 v1.10 v1.13 v1.22 v1.40", 
         * "charVarNoSet" =>
         * "v1.10|v1.719",
         */

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

        Object[] vs = edaOptionSet.getSelectedValues();
        // analysis=[A01, A02]
        List<String> alst = new ArrayList<String>();

        for (int i = 0; i < vs.length; i++) {
            dbgLog.info("eda option[" + i + "]=" + vs[i]);
            alst.add((String) vs[i]);
        }

        mpl.put("analysis", alst);

        mpl.put("optnlst_a", Arrays.asList("A01|A02|A03"));

        // if there is a user-defined (recoded) variables
        /*
        if (recodedVarSet.size() > 0) {
            mpl.putAll(getRecodedVarParameters());
        }
        */
        //                dbgLog.fine("citation info to be sent:\n" + citation);
        //                mpl.put("OfflineCitation", Arrays.asList(citation));
        //                mpl.put("appSERVER", Arrays.asList(req.getServerName() + ":"
        //                    + req.getServerPort() + req.getContextPath()));

        mpl.put("studytitle", Arrays.asList(getStudyTitle()));
        dbgLog.info("studyId from get method=" + getStudyId().toString());
        mpl.put("studyno", Arrays.asList(getStudyId().toString()));
        mpl.put("studyURL", Arrays.asList(studyURL));
        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("EDA"));

        // -----------------------------------------------------
        // New processing route
        // 
        // Step 0. Locate the data file and its attributes

        String fileId = sf.getId().toString();
        //VDC vdc = vdcService.getVDCFromRequest(req);

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

        dbgLog.info("location=" + fileloc);
        dbgLog.info("filename=" + tabflnm);
        dbgLog.info("subsettable=" + sbstOK);
        dbgLog.info("filetype=" + flct);

        DvnRJobRequest sro = null;

        List<File> zipFileList = new ArrayList();

        // the data file for downloading/statistical analyses must be subset-ready
        // local (relative to the application) file case 
        // note: a typical remote case is: US Census Bureau
        File tmpsbfl = null;
        if (sbstOK) {

            try {
                // this temp file will store the requested columns:
                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.info("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.info("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.info("subsettFile:Length=" + subsetFileSize);
                    dbgLog.info("tmpsb 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

                        msgEdaButton.setValue("* an subset file is empty");
                        msgEdaButton.setVisible(true);
                        dbgLog.warning(
                                "exiting edaAction() due to a subsetting error:" + "a subset file is empty");
                        getVDCRequestBean().setSelectedTab("tabEda");

                        return "";

                    }
                } else {
                    // subset file was not created
                    msgEdaButton.setValue("* a subset file was not created");
                    msgEdaButton.setVisible(true);
                    dbgLog.warning(
                            "exiting edaAction() due to a subsetting error:" + "a subset file was not created");
                    getVDCRequestBean().setSelectedTab("tabEda");

                    return "";

                }

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

                //Map<String, Map<String, String>> vls = getValueTableForRequestedVariables(getDataVariableForRequest());
                Map<String, Map<String, String>> vls = getValueTablesForAllRequestedVariables();

                sro = new DvnRJobRequest(getDataVariableForRequest(), mpl, vls, recodeSchema);

                //                    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 request of downloading or data analysis and 
                // capture result info as a Map <String, String>

                resultInfo = das.execute(sro);

                // Step 5. Checks the DSB-exit-status code
                if (resultInfo.get("RexecError").equals("true")) {
                    msgEdaButton.setValue("* The Request failed due to an R-runtime error");
                    msgEdaButton.setVisible(true);
                    dbgLog.info("exiting edaAction() due to an R-runtime error");
                    getVDCRequestBean().setSelectedTab("tabEda");

                    return "";
                } else {
                    if (recodeSchema.size() > 0) {
                        resultInfo.put("subsettingCriteria", sro.getSubsetConditionsForCitation());
                    } else {
                        resultInfo.put("subsettingCriteria", "");
                    }
                }

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

                msgEdaButton.setValue("* file URL is malformed");
                msgEdaButton.setVisible(true);
                dbgLog.warning("exiting edaAction() due to a URL problem ");
                getVDCRequestBean().setSelectedTab("tabEda");

                return "";

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

                msgEdaButton.setValue("* an IO problem occurred");
                msgEdaButton.setVisible(true);
                dbgLog.warning("exiting edaAction() due to an IO problem ");
                getVDCRequestBean().setSelectedTab("tabEda");

                return "";
            }

            // end of the subset-OK case
        } else {
            // not subsettable data file
            msgEdaButton.setValue("* this data file is not subsettable file");
            msgEdaButton.setVisible(true);
            dbgLog.warning("exiting edaAction(): the data file is not subsettable ");
            getVDCRequestBean().setSelectedTab("tabEda");

            return "";

        } // end:subsetNotOKcaseF

        // final processing steps for all successful cases

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

        dbgLog.info("RwrkspFileName=" + resultInfo.get("wrkspFileName"));

        // writing necessary files
        try {

            // rename the subsetting file
            File tmpsbflnew = File.createTempFile(SUBSET_FILENAME_PREFIX + resultInfo.get("PID") + ".", ".tab");
            deleteTempFileList.add(tmpsbflnew);
            InputStream inb = new BufferedInputStream(new FileInputStream(tmpsbfl));
            OutputStream outb = new BufferedOutputStream(new FileOutputStream(tmpsbflnew));

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

            String rhistNew = StringUtils.replace(resultInfo.get("RCommandHistory"), tmpsbfl.getName(),
                    tmpsbflnew.getName());

            //zipFileList.add(tmpsbflnew);

            // (1) write a citation file 
            //                String citationFilePrefix = "citationFile_"+ resultInfo.get("PID") + "_";
            //                File tmpcfl = File.createTempFile(citationFilePrefix, ".txt");
            //
            //                zipFileList.add(tmpcfl);
            //                deleteTempFileList.add(tmpcfl);
            //
            //                DvnCitationFileWriter dcfw = new DvnCitationFileWriter(resultInfo);
            //
            //                String fmpcflFullname = tmpcfl.getAbsolutePath();
            //                String fmpcflname = tmpcfl.getName();
            //                dcfw.write(tmpcfl);

            // (2) R command file
            String rhistoryFilePrefix = R_COMMAND_FILE_PREFIX + resultInfo.get("PID") + ".R";
            File tmpRhfl = new File(TEMP_DIR, rhistoryFilePrefix);

            zipFileList.add(tmpRhfl);
            deleteTempFileList.add(tmpRhfl);
            resultInfo.put("dvn_R_helper_file", "dvn_helper.R");
            DvnReplicationCodeFileWriter rcfw = new DvnReplicationCodeFileWriter(resultInfo);
            rcfw.writeEdaCode(tmpRhfl);

            // (3)RData Replication file
            String wrkspFileName = resultInfo.get("wrkspFileName");
            dbgLog.info("wrkspFileName=" + wrkspFileName);

            File RwrkspFileName = new File(wrkspFileName);
            if (RwrkspFileName.exists()) {
                dbgLog.info("RwrkspFileName:length=" + RwrkspFileName.length());

                zipFileList.add(RwrkspFileName);

            } else {
                dbgLog.info("RwrkspFileName does not exist");
                //msgEdaButton.setValue("* The workspace file is not available");
                //msgEdaButton.setVisible(true);
                dbgLog.warning("edaAction(): R workspace file was not transferred");
                //getVDCRequestBean().setSelectedTab("tabEda");

                //return "failure";
            }
            deleteTempFileList.add(RwrkspFileName);

            //                // vdc_startup.R file
            //                String vdc_startupFileName = resultInfo.get("vdc_startupFileName");
            //                dbgLog.fine("vdc_startupFileName="+vdc_startupFileName);
            //                File vdcstrtFileName = new File(vdc_startupFileName);
            //                if (vdcstrtFileName.exists()){
            //                    dbgLog.fine("vdcstrtFileName:length="+vdcstrtFileName.length());
            //                    zipFileList.add(vdcstrtFileName);
            //                } else {
            //                    dbgLog.fine("vdcstrtFileName does not exist");
            //                    //msgEdaButton.setValue("* vdc_startup.R is not available");
            //                    //msgEdaButton.setVisible(true);
            //                    dbgLog.warning("edaAction(): vdc_startup.R was not transferred");
            //                    //getVDCRequestBean().setSelectedTab("tabEda");
            //
            //                    //return "failure";
            //                }
            //                deleteTempFileList.add(vdcstrtFileName);
            // add replication readme file
            // (4) readme file
            // zipFileList.add(REP_README_FILE);
            String readMeFileName = REP_README_FILE_PREFIX + resultInfo.get("PID") + ".txt";
            File readMeFile = new File(TEMP_DIR, readMeFileName);

            DvnReplicationREADMEFileWriter rw = new DvnReplicationREADMEFileWriter(resultInfo);
            rw.writeREADMEfile(readMeFile);
            //zipFileList.add(REP_README_FILE);
            zipFileList.add(readMeFile);
            deleteTempFileList.add(readMeFile);

            // (5) css file
            zipFileList.add(DVN_R2HTML_CSS_FILE);
            // (6) dvn_R_helper
            zipFileList.add(DVN_R_HELPER_FILE);
            // zip the following files as a replication-pack
            //
            // local     local        local      remote
            // citation, tab-file,   R history,  wrksp

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

            // zipping all required files
            try {
                String zipFilePrefix = "zipFile_" + resultInfo.get("PID") + ".zip";
                File zipFile = new File(TEMP_DIR, zipFilePrefix);

                //res.setContentType("application/zip");
                String zfname = zipFile.getAbsolutePath();
                //res.setHeader("content-disposition", "attachment; filename=" + zfname);

                OutputStream zfout = new FileOutputStream(zipFile);
                //zipFiles(res.getOutputStream(), zipFileList);
                zipFiles(zfout, zipFileList);
                deleteTempFileList.add(zipFile);
                if (zipFile.exists()) {
                    Long zipFileSize = zipFile.length();
                    dbgLog.info("zip file:length=" + zipFileSize);
                    dbgLog.info("zip file:name=" + zipFile.getAbsolutePath());
                    if (zipFileSize > 0) {
                        resultInfo.put("replicationZipFile", zfname);
                        resultInfo.put("replicationZipFileName", zipFile.getName());
                    } else {
                        dbgLog.info("zip file is empty");
                    }
                } else {
                    dbgLog.info("zip file was not saved");
                }

                resultInfo.remove("RCommandHistory");

                // put resultInfo into the session object

                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("resultInfo",
                        resultInfo);

                dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);

                dbgLog.info("***** within edaAction(): succcessfully ends here *****");

                return "/subsetting/AnalysisResultsPage?faces-redirect=true" + getContextSuffix();
                //return "success";

            } catch (IOException e) {
                // file-access problem, etc.
                e.printStackTrace();
                dbgLog.info("zipping IO exception");
                msgEdaButton.setValue("* an IO problem occurred during zipping replication files");
                msgEdaButton.setVisible(true);
                dbgLog.warning("exiting edaAction() due to an zipping IO problem ");
                //getVDCRequestBean().setSelectedTab("tabEda");
                dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                return "/subsetting/AnalysisResultsPage?faces-redirect=true" + getContextSuffix();
                //return "success";
            }
            // end of zipping step

        } catch (IOException e) {
            // io errors caught during writing files
            e.printStackTrace();

            msgEdaButton.setValue("* an IO problem occurred");
            msgEdaButton.setVisible(true);
            dbgLog.warning("exiting edaAction() due to an IO problem ");
            getVDCRequestBean().setSelectedTab("tabEda");

            return "";
        }

        // end of CheckParameters: OK case
    } else {
        // parameters are not complete: show error message;
        msgEdaButton.setValue("* Select at least one option");
        msgEdaButton.setVisible(true);
        dbgLog.warning("exiting edaAction(): selection is incomplete");
        getVDCRequestBean().setSelectedTab("tabEda");

        return "";
    }

}

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

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

    resetMsgDwnldButton();// w w w . j a  v a2s  .c om

    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

}

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

public String advStatAction() {
    //        dbgLog.fine("selected tab(advStat)="+getTabSet1().getSelected());
    // check the current model

    String mdlName = (String) dropDown1.getValue();
    dbgLog.fine("model name=" + mdlName);

    AdvancedStatGUIdata.Model modelSpec = getAnalysisApplicationBean().getSpecMap().get(mdlName);

    if (checkAdvStatParameters(mdlName)) {

        FacesContext cntxt = FacesContext.getCurrentInstance();

        HttpServletResponse res = (HttpServletResponse) cntxt.getExternalContext().getResponse();
        HttpServletRequest req = (HttpServletRequest) cntxt.getExternalContext().getRequest();

        dbgLog.fine("***** within advStatAction() *****");
        // common parts
        // data file
        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();/*from   w w w .  j  av  a  2s.  c  om*/

        dbgLog.fine("serverPrefix=" + serverPrefix);
        //                /
        //                  "optnlst_a" => "A01|A02|A03", "analysis" => "A01 A02",
        //                  "varbl" => "v1.3 v1.10 v1.13 v1.22 v1.40", "charVarNoSet" =>
        //                  "v1.10|v1.719",
        //                 /

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

        List<String> alst = new ArrayList<String>();
        List<String> aoplst = new ArrayList<String>();

        aoplst.add("A01|A02|A03");
        mpl.put("optnlst_a", aoplst);

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

        // xtbro: modelName
        xtbro.put("modelName", Arrays.asList(mdlName));

        // outoput options

        List<String> outOptionList = new ArrayList<String>();

        mpl.put("modelName", Arrays.asList(mdlName));
        if (mdlName.equals("xtb")) {
            mpl.put("requestType", Arrays.asList("Xtab"));
        } else {
            mpl.put("requestType", Arrays.asList("Zelig"));
        }

        if (mdlName.equals("xtb")) {
            alst.add("A03");

            // output options
            // Object[] outOptn = (Object[]) checkboxGroupXtbOptions.getSelectedValue();
            Object[] outOptn = chkbxAdvStatOutputXtbOpt.getSelectedValues();
            List<String> tv = new ArrayList<String>();
            //tv.add("T");

            for (int j = 0; j < outOptn.length; j++) {
                dbgLog.fine("output option[" + j + "]=" + outOptn[j]);
                mpl.put((String) outOptn[j], Arrays.asList("T"));
                tv.add((String) outOptn[j]);
            }
            mpl.put("xtb_outputOptions", tv);

            // variables: 1st RBox
            if (advStatVarRBox1.size() >= 1) {
                dbgLog.fine("RB1:" + getDataVariableForRBox1());
                mpl.put("xtb_nmBxR1", getDataVariableForRBox1());
            }

            // variables: 2nd RBox
            if (advStatVarRBox2.size() >= 1) {
                dbgLog.fine("RB2:" + getDataVariableForRBox2());
                mpl.put("xtb_nmBxR2", getDataVariableForRBox2());
            }

            mpl.put("analysis", alst);

        } else {
            // Zelig cases

            dbgLog.fine("***** zelig param block *****");
            // non-xtb, i.e., zelig cases
            // check zlg value

            dbgLog.fine("model spec dump=" + modelSpec);
            dbgLog.fine("model spec mdlId=" + modelSpec.getMdlId());

            String zligPrefix = modelSpec.getMdlId();
            dbgLog.fine("model no=" + zligPrefix);

            // get the varId-list of each box
            // 1-RBox case
            if (advStatVarRBox1.size() >= 1) {
                dbgLog.fine("RB1:" + getDataVariableForRBox1());
                //mpl.put(zligPrefix + "_nmBxR1", getDataVariableForRBox1());
                mpl.put("nmBxR1", getDataVariableForRBox1());
            }

            // 2-RBox case
            if (advStatVarRBox2.size() >= 1) {
                dbgLog.fine("RB2:" + getDataVariableForRBox2());
                //mpl.put(zligPrefix + "_nmBxR2", getDataVariableForRBox2());
                mpl.put("nmBxR2", getDataVariableForRBox2());
            }

            // 3-RBox case
            if (advStatVarRBox3.size() >= 1) {
                dbgLog.fine("RB3:" + getDataVariableForRBox3());
                //mpl.put(zligPrefix + "_nmBxR3", getDataVariableForRBox3());
                mpl.put("nmBxR3", getDataVariableForRBox3());
            }

            // model name
            //mpl.put("zlg", getZlg(zligPrefix, mdlName));

            // model type
            //String sfn = modelSpec.getSpecialFn();
            //mpl.put("mdlType_" + mdlName, getMdlType(mdlName, sfn));

            // model title
            //String ttl = modelSpec.getTitle();
            //dbgLog.fine("model title=" + ttl);
            //mpl.put("mdlTitle_" + mdlName, Arrays.asList(ttl));
            //mpl.put("mdlTitle", Arrays.asList(ttl));

            // nrBoxes
            int noRboxes = modelSpec.getNoRboxes();
            dbgLog.fine("noRboxes=" + noRboxes);

            //mpl.put("noBoxes_" + mdlName, Arrays.asList(Integer.toString(noRboxes)));
            mpl.put("noBoxes", Arrays.asList(Integer.toString(noRboxes)));

            // binary
            String mdlCategory = modelSpec.getCategory();
            String outcomeType = modelSpec.getVarBox().get(0).getVarType();

            dbgLog.fine("model category=" + mdlCategory);

            if (mdlCategory.equals("Models for Dichotomous Dependent Variables")) {
                mpl.put("mdlDepVarType", Arrays.asList("binary"));
            }
            if (outcomeType.equals("binary")) {
                mpl.put("isOutcomeBinary", Arrays.asList("T"));
            } else {
                mpl.put("isOutcomeBinary", Arrays.asList("F"));
            }
            // output options
            //                    //
            //                     // zlg_017_Summary zlg_017_Plots zlg_017_BinOutput
            //                     //
            //Object[] outOptn = (Object[]) checkboxGroup2DefaultOptions.getSelectedValue();
            Object[] outOptn = chkbxAdvStatOutputOpt.getSelectedValues();
            List<String> tv = new ArrayList<String>();

            for (int j = 0; j < outOptn.length; j++) {
                //String outputOptnkey = zligPrefix + "_"+ (String) outOptn[j];
                String outputOptnkey = (String) outOptn[j];
                dbgLog.fine("zelig: output option[" + j + "]=" + outputOptnkey);
                mpl.put(outputOptnkey, Arrays.asList("T"));
                tv.add((String) outOptn[j]);
            }
            mpl.put("zelig_outputOptions", tv);

            // analysis options
            //                    
            //                      zlg_017_Sim zlg_017_setx zlg_017_setx_var
            //                      zlg_017_setx_val_1 zlg_017_setx_val_2
            //                      
            //                      zlg_017_naMethod
            //                     
            //
            dbgLog.fine("simulationPanel is selected=" + simulationPanel.isSelected());
            if (simulationPanel.isSelected()) {
                dbgLog.fine("radioSimTypeChoiceSelected=" + radioSimTypeChoiceSelected);
                //mpl.put(zligPrefix + "_Sim", Arrays.asList("T"));
                mpl.put("Sim", Arrays.asList("T"));

                //Object simOptn = radioButtonGroup1DefaultOptions.getSelectedValue();
                dbgLog.fine("radioSimTypeChoice(value)=" + radioSimTypeChoice.getValue());
                dbgLog.fine("radioSimTypeChoiceSelected=" + radioSimTypeChoiceSelected);
                // simOptn = 0 or 1
                //mpl.put(zligPrefix + "_setx", Arrays.asList((String) simOptn));
                //                        mpl.put("setx", Arrays.asList((String) simOptn));
                //                        mpl.put("setxType", Arrays.asList((String) simOptn));
                mpl.put("setx", Arrays.asList(radioSimTypeChoiceSelected));
                mpl.put("setxType", Arrays.asList(radioSimTypeChoiceSelected));
                if (radioSimTypeChoiceSelected.equals("1")) {
                    Object v1 = dropDown2.getValue();
                    Object v2 = dropDown3.getValue();
                    Object vl1 = textField10.getValue();
                    Object vl2 = textField8.getValue();
                    dbgLog.fine("v1=" + v1);
                    dbgLog.fine("v2=" + v2);
                    dbgLog.fine("vl1=" + vl1);
                    dbgLog.fine("vl2=" + vl2);

                    List<String> setxVars = new ArrayList<String>();

                    if (v1 != null) {
                        setxVars.add((String) v1);

                    }
                    if (v2 != null) {
                        setxVars.add((String) v2);
                    }
                    //mpl.put(zligPrefix + "_setx_var", setxVars);
                    mpl.put("setx_var", setxVars);

                    if (vl1 != null) {
                        //mpl.put(zligPrefix + "_setx_val_1", Arrays.asList((String) vl1));
                        mpl.put("setx_val_1", Arrays.asList((String) vl1));
                    }
                    if (vl2 != null) {
                        //mpl.put(zligPrefix + "_setx_val_2", Arrays.asList((String) vl2));
                        mpl.put("setx_val_2", Arrays.asList((String) vl2));
                    }

                    List<String> setxVar1 = new ArrayList<String>();

                    if (v1 != null) {
                        setxVar1.add("v" + v1);
                        if (vl1 != null) {
                            setxVar1.add((String) vl1);
                        } else {
                            setxVar1.add("");
                        }
                        mpl.put("setx_var1", setxVar1);
                    }

                    if (v2 != null) {
                        List<String> setxVar2 = new ArrayList<String>();

                        setxVar2.add("v" + v2);
                        if (vl2 != null) {
                            setxVar2.add((String) vl2);
                        } else {
                            setxVar2.add("");
                        }
                        mpl.put("setx_var2", setxVar2);
                    }

                }
            } else {
                mpl.put("Sim", Arrays.asList("F"));
            }

        }

        dbgLog.fine("contents(mpl so far):" + mpl);

        // if there is a user-defined (recoded) variables
        /*
        if (recodedVarSet.size() > 0) {
            mpl.putAll(getRecodedVarParameters());
        }
        */
        //                dbgLog.fine("citation info to be sent:\n" + citation);
        //                mpl.put("OfflineCitation", Arrays.asList(citation));
        //                mpl.put("appSERVER", Arrays.asList(req.getServerName() +
        //                    ":"+ req.getServerPort() + req.getContextPath()));

        mpl.put("studytitle", Arrays.asList(getStudyTitle()));
        dbgLog.fine("alt studyId=" + getStudyId().toString());
        mpl.put("studyno", Arrays.asList(getStudyId().toString()));
        mpl.put("studyURL", Arrays.asList(studyURL));
        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());

        // -----------------------------------------------------
        // New processing route
        // 
        // Step 0. Locate the data file and its attributes

        String fileId = sf.getId().toString();
        //VDC vdc = vdcService.getVDCFromRequest(req);

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

        dbgLog.fine("location=" + fileloc);
        dbgLog.fine("filename=" + tabflnm);
        dbgLog.fine("subsettable=" + sbstOK);
        dbgLog.fine("filetype=" + flct);

        DvnRJobRequest sro = null;

        List<File> zipFileList = new ArrayList();

        // the data file for downloading/statistical analyses must be subset-ready
        // local (relative to the application) file case 
        // note: a typical remote case is: US Census Bureau
        File tmpsbfl = null;
        if (sbstOK) {

            try {
                // this temp file will store the requested columns:
                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 ""; //"failure";

                        }

                    }
                }

                // Checks the resulting subset file 
                if (tmpsbfl.exists()) {
                    Long subsetFileSize = tmpsbfl.length();
                    dbgLog.fine("subsettFile:Length=" + subsetFileSize);
                    dbgLog.fine("tmpsb 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

                        msgAdvStatButton.setValue("* an subset file is empty");
                        msgAdvStatButton.setVisible(true);
                        dbgLog.warning("exiting advStatAction() due to a subsetting error:"
                                + "a subset file is empty");
                        getVDCRequestBean().setSelectedTab("tabAdvStat");

                        return ""; //"failure";

                    }
                } else {
                    // subset file was not created
                    msgAdvStatButton.setValue("* a subset file was not created");
                    msgAdvStatButton.setVisible(true);
                    dbgLog.warning("exiting advStatAction() due to a subsetting error:"
                            + "a subset file was not created");
                    getVDCRequestBean().setSelectedTab("tabAdvStat");

                    return ""; //"failure";

                }

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

                //Map<String, Map<String, String>> vls = getValueTableForRequestedVariables(getDataVariableForRequest());
                Map<String, Map<String, String>> vls = getValueTablesForAllRequestedVariables();

                sro = new DvnRJobRequest(getDataVariableForRequest(), mpl, vls, recodeSchema, modelSpec);

                //dbgLog.fine("Prepared 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 request of downloading or data analysis and 
                // capture result info as a Map <String, String>

                resultInfo = das.execute(sro);

                // Step 5. Checks the DSB-exit-status code
                if (resultInfo.get("RexecError").equals("true")) {
                    //msgAdvStatButton.setValue("* The Request failed due to an R-runtime error");
                    msgAdvStatButton.setValue("* The Request failed due to an R-runtime error");
                    msgAdvStatButton.setVisible(true);
                    dbgLog.fine("exiting advStatAction() due to an R-runtime error");
                    getVDCRequestBean().setSelectedTab("tabAdvStat");

                    return ""; //"failure";
                } else {
                    if (recodeSchema.size() > 0) {
                        resultInfo.put("subsettingCriteria", sro.getSubsetConditionsForCitation());
                    } else {
                        resultInfo.put("subsettingCriteria", "");
                    }
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
                // pass the error message to the resultPage
                // resultInfo.put();
                msgAdvStatButton.setValue("* file URL is malformed");
                msgAdvStatButton.setVisible(true);
                dbgLog.warning("exiting advStatAction() due to a URL problem ");
                getVDCRequestBean().setSelectedTab("tabAdvStat");

                return ""; //"failure";

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

                msgAdvStatButton.setValue("* an IO problem occurred");
                msgAdvStatButton.setVisible(true);
                dbgLog.warning("exiting advStatAction() due to an IO problem ");
                getVDCRequestBean().setSelectedTab("tabAdvStat");

                return ""; //"failure";

            }
            // end of the subset-OK case
        } else {
            // not subsettable data file
            msgAdvStatButton.setValue("* this data file is not subsettable file");
            msgAdvStatButton.setVisible(true);
            dbgLog.warning("exiting advStatAction(): the data file is not subsettable ");
            getVDCRequestBean().setSelectedTab("tabAdvStat");

            return ""; //"failure";

        } // end:subsetNotOKcase

        // final processing steps for all successful cases

        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("R_min_verion_no", resultInfo.get("Rversion").substring(2));
        resultInfo.put("dataverse_version_no", dvnVersionNumber);

        dbgLog.fine("RwrkspFileName=" + resultInfo.get("wrkspFileName"));

        // writing necessary files
        try {

            // rename the subsetting file
            File tmpsbflnew = File.createTempFile(SUBSET_FILENAME_PREFIX + resultInfo.get("PID") + ".", ".tab");
            deleteTempFileList.add(tmpsbflnew);
            InputStream inb = new BufferedInputStream(new FileInputStream(tmpsbfl));
            OutputStream outb = new BufferedOutputStream(new FileOutputStream(tmpsbflnew));

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

            String rhistNew = StringUtils.replace(resultInfo.get("RCommandHistory"), tmpsbfl.getName(),
                    tmpsbflnew.getName());

            //zipFileList.add(tmpsbflnew);

            // (1) write a citation file 
            //                String citationFilePrefix = "citationFile_"+ resultInfo.get("PID") + "_";
            //                File tmpcfl = File.createTempFile(citationFilePrefix, ".txt");
            //
            //                zipFileList.add(tmpcfl);
            //                deleteTempFileList.add(tmpcfl);
            //
            //                DvnCitationFileWriter dcfw = new DvnCitationFileWriter(resultInfo);
            //
            //                String fmpcflFullname = tmpcfl.getAbsolutePath();
            //                String fmpcflname = tmpcfl.getName();
            //                dcfw.write(tmpcfl);

            // (2) R command file
            String rhistoryFilePrefix = R_COMMAND_FILE_PREFIX + resultInfo.get("PID") + ".R";
            File tmpRhfl = new File(TEMP_DIR, rhistoryFilePrefix);

            zipFileList.add(tmpRhfl);
            deleteTempFileList.add(tmpRhfl);
            resultInfo.put("dvn_R_helper_file", "dvn_helper.R");
            DvnReplicationCodeFileWriter rcfw = new DvnReplicationCodeFileWriter(resultInfo);
            if (mdlName.equals("xtb")) {
                rcfw.writeXtabCode(tmpRhfl);
            } else {
                rcfw.writeZeligCode(tmpRhfl);
            }

            // (3) RData Replication file
            String wrkspFileName = resultInfo.get("wrkspFileName");
            dbgLog.fine("wrkspFileName=" + wrkspFileName);

            File RwrkspFileName = new File(wrkspFileName);
            if (RwrkspFileName.exists()) {
                dbgLog.fine("RwrkspFileName:length=" + RwrkspFileName.length());

                zipFileList.add(RwrkspFileName);

            } else {
                dbgLog.fine("RwrkspFileName does not exist");
                //msgAdvStatButton.setValue("* The workspace file is not available");
                //msgAdvStatButton.setVisible(true);
                dbgLog.warning("advStatAction(): R workspace file was not transferred");
                //getVDCRequestBean().setSelectedTab("tabAdvStat");

                //return "failure";
            }
            deleteTempFileList.add(RwrkspFileName);

            // vdc_startup.R file
            //                String vdc_startupFileName = resultInfo.get("vdc_startupFileName");
            //                dbgLog.fine("vdc_startupFileName="+vdc_startupFileName);
            //                File vdcstrtFileName = new File(vdc_startupFileName);
            //                if (vdcstrtFileName.exists()){
            //                    dbgLog.fine("vdcstrtFileName:length="+vdcstrtFileName.length());
            //                    zipFileList.add(vdcstrtFileName);
            //                } else {
            //                    dbgLog.fine("vdcstrtFileName does not exist");
            //                    //msgAdvStatButton.setValue("* vdc_startup.R is not available");
            //                    //msgAdvStatButton.setVisible(true);
            //                    dbgLog.warning("advStatAction(): vdc_startup.R was not transferred");
            //                    //getVDCRequestBean().setSelectedTab("tabAdvStat");
            //
            //                    //return "failure";
            //                }
            //                deleteTempFileList.add(vdcstrtFileName);
            // (4) add replication readme file
            String readMeFileName = REP_README_FILE_PREFIX + resultInfo.get("PID") + ".txt";
            File readMeFile = new File(TEMP_DIR, readMeFileName);

            DvnReplicationREADMEFileWriter rw = new DvnReplicationREADMEFileWriter(resultInfo);
            rw.writeREADMEfile(readMeFile);
            //zipFileList.add(REP_README_FILE);
            zipFileList.add(readMeFile);
            deleteTempFileList.add(readMeFile);
            // (5) helper
            zipFileList.add(DVN_R_HELPER_FILE);
            if (mdlName.equals("xtb")) {
                // (6) css file
                zipFileList.add(DVN_R2HTML_CSS_FILE);

            }
            // zip the following files as a replication-pack
            //
            // local     local        local      remote
            // citation, tab-file,   R history,  wrksp

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

            // zipping all required files
            try {
                String zipFilePrefix = "zipFile_" + resultInfo.get("PID") + ".zip";
                File zipFile = new File(TEMP_DIR, zipFilePrefix);

                deleteTempFileList.add(zipFile);
                //res.setContentType("application/zip");
                String zfname = zipFile.getAbsolutePath();
                //res.setHeader("content-disposition", "attachment; filename=" + zfname);

                OutputStream zfout = new FileOutputStream(zipFile);
                //zipFiles(res.getOutputStream(), zipFileList);
                zipFiles(zfout, zipFileList);

                if (zipFile.exists()) {
                    Long zipFileSize = zipFile.length();
                    dbgLog.fine("zip file:length=" + zipFileSize);
                    dbgLog.fine("zip file:name=" + zipFile.getAbsolutePath());
                    if (zipFileSize > 0) {
                        resultInfo.put("replicationZipFile", zfname);
                        resultInfo.put("replicationZipFileName", zipFile.getName());

                    } else {
                        dbgLog.fine("zip file is empty");
                    }
                } else {
                    dbgLog.fine("zip file was not saved");
                }

                // put resultInfo into the session object
                resultInfo.remove("RCommandHistory");
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("resultInfo",
                        resultInfo);

                dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);

                dbgLog.fine("***** within advStatAction(): succcessfully ends here *****");

                return "/subsetting/AnalysisResultsPage?faces-redirect=true" + getContextSuffix(); //"success";

            } catch (IOException e) {
                // file-access problem, etc.
                e.printStackTrace();
                dbgLog.fine("zipping IO exception");
                msgAdvStatButton.setValue("* an IO problem occurred during zipping replication files");
                msgAdvStatButton.setVisible(true);
                dbgLog.warning("exiting edaAction() due to an zipping IO problem ");
                //getVDCRequestBean().setSelectedTab("tabAdvStat");
                dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                return "/subsetting/AnalysisResultsPage?faces-redirect=true" + getContextSuffix(); //"success";
            }
            // end of zipping step

        } catch (IOException e) {
            // io errors caught during writing files
            e.printStackTrace();

            msgAdvStatButton.setValue("* an IO problem occurred");
            msgAdvStatButton.setVisible(true);
            dbgLog.warning("exiting edaAction() due to an IO problem ");
            getVDCRequestBean().setSelectedTab("tabAdvStat");

            return ""; //"failure";
        }

        // end of CheckParameters: OK case
    } else {
        // parameters are not complete: show error message;

        msgAdvStatButton.setValue("* Selection is incomplete");
        msgAdvStatButton.setVisible(true);
        dbgLog.fine("exiting advStatAction(): selection is incomplete");
        getVDCRequestBean().setSelectedTab("tabAdvStat");

        return ""; //"failure";
    }

}

From source file:com.liferay.portal.events.ServicePreActionExt.java

protected void servicePre(HttpServletRequest request, HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession();

    // Company//from w w w. j a va  2s .co  m

    Company company = PortalUtil.getCompany(request);

    long companyId = company.getCompanyId();

    // CDN host

    String cdnHost = null;

    if (request.isSecure()) {
        cdnHost = PortalUtil.getCDNHostHttps();
    } else {
        cdnHost = PortalUtil.getCDNHostHttp();
    }

    cdnHost = ParamUtil.getString(request, "cdn_host", cdnHost);

    // Portal URL

    String portalURL = PortalUtil.getPortalURL(request);

    // Paths

    String contextPath = PortalUtil.getPathContext();
    String friendlyURLPrivateGroupPath = PortalUtil.getPathFriendlyURLPrivateGroup();
    String friendlyURLPrivateUserPath = PortalUtil.getPathFriendlyURLPrivateUser();
    String friendlyURLPublicPath = PortalUtil.getPathFriendlyURLPublic();
    String imagePath = cdnHost.concat(PortalUtil.getPathImage());
    String mainPath = PortalUtil.getPathMain();

    String i18nPath = (String) request.getAttribute(WebKeys.I18N_PATH);

    if (Validator.isNotNull(i18nPath)) {
        if (Validator.isNotNull(contextPath)) {
            String i18nContextPath = contextPath.concat(i18nPath);

            friendlyURLPrivateGroupPath = StringUtil.replaceFirst(friendlyURLPrivateGroupPath, contextPath,
                    i18nContextPath);
            friendlyURLPrivateUserPath = StringUtil.replaceFirst(friendlyURLPrivateUserPath, contextPath,
                    i18nContextPath);
            friendlyURLPublicPath = StringUtil.replaceFirst(friendlyURLPublicPath, contextPath,
                    i18nContextPath);
            mainPath = StringUtil.replaceFirst(mainPath, contextPath, i18nContextPath);
        } else {
            friendlyURLPrivateGroupPath = i18nPath.concat(friendlyURLPrivateGroupPath);
            friendlyURLPrivateUserPath = i18nPath.concat(friendlyURLPrivateUserPath);
            friendlyURLPublicPath = i18nPath.concat(friendlyURLPublicPath);
            mainPath = i18nPath.concat(mainPath);
        }
    }

    // Company logo

    StringBundler sb = new StringBundler(5);

    sb.append(imagePath);
    sb.append("/company_logo?img_id=");
    sb.append(company.getLogoId());
    sb.append("&t=");
    sb.append(ImageServletTokenUtil.getToken(company.getLogoId()));

    String companyLogo = sb.toString();

    Image companyLogoImage = ImageLocalServiceUtil.getCompanyLogo(company.getLogoId());

    int companyLogoHeight = companyLogoImage.getHeight();
    int companyLogoWidth = companyLogoImage.getWidth();

    String realCompanyLogo = companyLogo;
    int realCompanyLogoHeight = companyLogoHeight;
    int realCompanyLogoWidth = companyLogoWidth;

    // User

    User user = null;

    try {
        user = PortalUtil.getUser(request);
    } catch (NoSuchUserException nsue) {
        if (_log.isWarnEnabled()) {
            _log.warn(nsue.getMessage());
        }

        long userId = PortalUtil.getUserId(request);

        if (userId > 0) {
            session.invalidate();
        }

        return;
    }

    boolean signedIn = false;

    if (user == null) {
        user = company.getDefaultUser();
    } else if (!user.isDefaultUser()) {
        signedIn = true;
    }

    User realUser = user;

    Long realUserId = (Long) session.getAttribute(WebKeys.USER_ID);

    if (realUserId != null) {
        if (user.getUserId() != realUserId.longValue()) {
            realUser = UserLocalServiceUtil.getUserById(realUserId.longValue());
        }
    }

    String doAsUserId = ParamUtil.getString(request, "doAsUserId");
    String doAsUserLanguageId = ParamUtil.getString(request, "doAsUserLanguageId");
    long doAsGroupId = ParamUtil.getLong(request, "doAsGroupId");
    long refererPlid = ParamUtil.getLong(request, "refererPlid");

    // Permission checker

    PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user, true);

    PermissionThreadLocal.setPermissionChecker(permissionChecker);

    // Locale

    Locale locale = (Locale) session.getAttribute(Globals.LOCALE_KEY);

    if (Validator.isNotNull(doAsUserLanguageId)) {
        locale = LocaleUtil.fromLanguageId(doAsUserLanguageId);
    }

    String i18nLanguageId = (String) request.getAttribute(WebKeys.I18N_LANGUAGE_ID);

    if (Validator.isNotNull(i18nLanguageId)) {
        locale = LocaleUtil.fromLanguageId(i18nLanguageId);
    } else if (locale == null) {
        if (signedIn) {
            locale = user.getLocale();
        } else {

            // User previously set their preferred language

            String languageId = CookieKeys.getCookie(request, CookieKeys.GUEST_LANGUAGE_ID);

            if (Validator.isNotNull(languageId)) {
                locale = LocaleUtil.fromLanguageId(languageId);
            }

            // Get locale from the request

            if ((locale == null) && PropsValues.LOCALE_DEFAULT_REQUEST) {
                locale = request.getLocale();
            }

            // Get locale from the default user

            if (locale == null) {
                locale = user.getLocale();
            }

            if (Validator.isNull(locale.getCountry())) {

                // Locales must contain a country code

                locale = LanguageUtil.getLocale(locale.getLanguage());
            }

            if (!LanguageUtil.isAvailableLocale(locale)) {
                locale = user.getLocale();
            }
        }

        session.setAttribute(Globals.LOCALE_KEY, locale);

        LanguageUtil.updateCookie(request, response, locale);
    }

    // Cookie support

    try {

        // LEP-4069

        CookieKeys.validateSupportCookie(request);
    } catch (Exception e) {
        CookieKeys.addSupportCookie(request, response);
    }

    // Time zone

    TimeZone timeZone = user.getTimeZone();

    if (timeZone == null) {
        timeZone = company.getTimeZone();
    }

    // Layouts

    if (signedIn) {
        updateUserLayouts(user);
    }

    Layout layout = null;
    List<Layout> layouts = null;

    long plid = ParamUtil.getLong(request, "p_l_id");

    if (plid > 0) {
        layout = LayoutLocalServiceUtil.getLayout(plid);
    } else {
        long groupId = ParamUtil.getLong(request, "groupId");
        boolean privateLayout = ParamUtil.getBoolean(request, "privateLayout");
        long layoutId = ParamUtil.getLong(request, "layoutId");

        if ((groupId > 0) && layoutId > 0) {
            layout = LayoutLocalServiceUtil.getLayout(groupId, privateLayout, layoutId);
        }
    }

    if (layout != null) {
        try {
            Group group = layout.getGroup();

            if (!signedIn && PropsValues.AUTH_FORWARD_BY_REDIRECT) {
                request.setAttribute(WebKeys.REQUESTED_LAYOUT, layout);
            }

            boolean isViewableCommunity = isViewableGroup(user, layout.getGroupId(), layout.isPrivateLayout(),
                    layout.getLayoutId(), permissionChecker);

            if (!isViewableCommunity && group.isStagingGroup()) {
                layout = null;
            } else if (!isViewableCommunity) {
                sb = new StringBundler(6);

                sb.append("User ");
                sb.append(user.getUserId());
                sb.append(" is not allowed to access the ");
                sb.append(layout.isPrivateLayout() ? "private" : "public");
                sb.append(" pages of group ");
                sb.append(layout.getGroupId());

                if (_log.isWarnEnabled()) {
                    _log.warn(sb.toString());
                }

                throw new PrincipalException(sb.toString());
            } else if (isViewableCommunity
                    && !LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.VIEW)) {

                layout = null;
            } else if (group.isLayoutPrototype()) {
                layouts = new ArrayList<Layout>();
            } else {
                layouts = LayoutLocalServiceUtil.getLayouts(layout.getGroupId(), layout.isPrivateLayout(),
                        LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);

                if (!group.isControlPanel()) {
                    doAsGroupId = 0;
                }
            }
        } catch (NoSuchLayoutException nsle) {
        }
    }

    if (layout == null) {
        Object[] defaultLayout = getDefaultLayout(request, user, signedIn);

        layout = (Layout) defaultLayout[0];
        layouts = (List<Layout>) defaultLayout[1];

        request.setAttribute(WebKeys.LAYOUT_DEFAULT, Boolean.TRUE);
    }

    Object[] viewableLayouts = getViewableLayouts(request, user, permissionChecker, layout, layouts);

    String layoutSetLogo = null;

    layout = (Layout) viewableLayouts[0];
    layouts = (List<Layout>) viewableLayouts[1];

    Group group = null;

    if (layout != null) {
        group = layout.getGroup();

        if (!group.isControlPanel()) {
            rememberVisitedGroupIds(request, group.getGroupId());
        }
    }

    LayoutTypePortlet layoutTypePortlet = null;

    layouts = mergeAdditionalLayouts(request, user, permissionChecker, layout, layouts);

    if (layout != null) {
        if (company.isCommunityLogo()) {
            long logoId = 0;

            LayoutSet layoutSet = layout.getLayoutSet();

            if (layoutSet.isLogo()) {
                logoId = layoutSet.getLogoId();
            } else {
                LayoutSet siblingLayoutSet = LayoutSetLocalServiceUtil.getLayoutSet(layout.getGroupId(),
                        !layout.isPrivateLayout());

                if (siblingLayoutSet.isLogo()) {
                    logoId = siblingLayoutSet.getLogoId();
                }
            }

            if (logoId > 0) {
                sb = new StringBundler(5);

                sb.append(imagePath);
                sb.append("/layout_set_logo?img_id=");
                sb.append(logoId);
                sb.append("&t=");
                sb.append(ImageServletTokenUtil.getToken(logoId));

                layoutSetLogo = sb.toString();

                Image layoutSetLogoImage = ImageLocalServiceUtil.getCompanyLogo(logoId);

                companyLogo = layoutSetLogo;
                companyLogoHeight = layoutSetLogoImage.getHeight();
                companyLogoWidth = layoutSetLogoImage.getWidth();
            }
        }

        plid = layout.getPlid();

        // Updates to shared layouts are not reflected until the next time
        // the user logs in because group layouts are cached in the session

        layout = (Layout) ((LayoutImpl) layout).clone();

        layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

        LayoutClone layoutClone = LayoutCloneFactory.getInstance();

        if (layoutClone != null) {
            String typeSettings = layoutClone.get(request, plid);

            if (typeSettings != null) {
                UnicodeProperties props = new UnicodeProperties(true);

                props.load(typeSettings);

                String stateMax = props.getProperty(LayoutTypePortletConstants.STATE_MAX);
                String stateMin = props.getProperty(LayoutTypePortletConstants.STATE_MIN);
                String modeAbout = props.getProperty(LayoutTypePortletConstants.MODE_ABOUT);
                String modeConfig = props.getProperty(LayoutTypePortletConstants.MODE_CONFIG);
                String modeEdit = props.getProperty(LayoutTypePortletConstants.MODE_EDIT);
                String modeEditDefaults = props.getProperty(LayoutTypePortletConstants.MODE_EDIT_DEFAULTS);
                String modeEditGuest = props.getProperty(LayoutTypePortletConstants.MODE_EDIT_GUEST);
                String modeHelp = props.getProperty(LayoutTypePortletConstants.MODE_HELP);
                String modePreview = props.getProperty(LayoutTypePortletConstants.MODE_PREVIEW);
                String modePrint = props.getProperty(LayoutTypePortletConstants.MODE_PRINT);

                layoutTypePortlet.setStateMax(stateMax);
                layoutTypePortlet.setStateMin(stateMin);
                layoutTypePortlet.setModeAbout(modeAbout);
                layoutTypePortlet.setModeConfig(modeConfig);
                layoutTypePortlet.setModeEdit(modeEdit);
                layoutTypePortlet.setModeEditDefaults(modeEditDefaults);
                layoutTypePortlet.setModeEditGuest(modeEditGuest);
                layoutTypePortlet.setModeHelp(modeHelp);
                layoutTypePortlet.setModePreview(modePreview);
                layoutTypePortlet.setModePrint(modePrint);
            }
        }

        request.setAttribute(WebKeys.LAYOUT, layout);
        request.setAttribute(WebKeys.LAYOUTS, layouts);

        if (layout.isPrivateLayout()) {
            permissionChecker.setCheckGuest(false);
        }
    }

    // Scope

    long scopeGroupId = PortalUtil.getScopeGroupId(request);
    long parentGroupId = PortalUtil.getParentGroupId(scopeGroupId);

    // Device
    Device device = DevicesUtil.getDeviceFromRequest(request);
    _log.debug(" Device is: " + device);

    // Theme and color scheme

    Theme theme = null;
    ColorScheme colorScheme = null;

    boolean wapTheme = BrowserSnifferUtil.isWap(request);

    if ((layout != null) && group.isControlPanel()) {

        String themeId = PrefsPropsUtil.getString(companyId, PropsKeys.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID);
        String colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId();

        theme = ThemeLocalServiceUtil.getTheme(companyId, themeId, wapTheme);
        colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId,
                wapTheme);

        if (!wapTheme && theme.isWapTheme()) {
            theme = ThemeLocalServiceUtil.getTheme(companyId, PropsValues.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID,
                    false);
            colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId,
                    false);
        }
    } else {
        DeviceAction deviceAction = DeviceRulesUtil.getAction(device, companyId, group.getGroupId(),
                layout.getPlid());
        if (deviceAction != null && !(deviceAction instanceof NoAction)) {
            if (deviceAction instanceof ChangeThemeAction) {
                ChangeThemeAction changeThemeAction = (ChangeThemeAction) deviceAction;
                ThemeAndColorScheme themeAndColorScheme = changeThemeAction.getThemeAndColorScheme();
                if (themeAndColorScheme != null && themeAndColorScheme.getThemeId() != null) {
                    theme = themeAndColorScheme.getTheme(companyId);
                    _log.debug("Changing theme to " + theme.getThemeId());
                    if (themeAndColorScheme.getColorSchemeId() != null) {
                        colorScheme = themeAndColorScheme.getColorScheme(companyId);
                        _log.debug("Changing color scheme to " + colorScheme.getColorSchemeId());
                    }
                }
            }
            if (deviceAction instanceof RedirectAction) {
                RedirectAction redirectAction = (RedirectAction) deviceAction;
                String url = redirectAction.getUrl();
                if (url != null && !url.trim().isEmpty()) {
                    _log.debug("Redirecting to " + url);
                    response.sendRedirect(url);
                    return;
                }
            }
        } else if (layout != null) {
            if (wapTheme) {
                theme = layout.getWapTheme();
                colorScheme = layout.getWapColorScheme();
            } else {
                theme = layout.getTheme();
                colorScheme = layout.getColorScheme();
            }
        } else {
            String themeId = null;
            String colorSchemeId = null;

            if (wapTheme) {
                themeId = ThemeImpl.getDefaultWapThemeId(companyId);
                colorSchemeId = ColorSchemeImpl.getDefaultWapColorSchemeId();
            } else {
                themeId = ThemeImpl.getDefaultRegularThemeId(companyId);
                colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId();
            }

            theme = ThemeLocalServiceUtil.getTheme(companyId, themeId, wapTheme);
            colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId,
                    wapTheme);
        }
    }

    request.setAttribute(WebKeys.THEME, theme);
    request.setAttribute(WebKeys.COLOR_SCHEME, colorScheme);

    boolean themeCssFastLoad = SessionParamUtil.getBoolean(request, "css_fast_load",
            PropsValues.THEME_CSS_FAST_LOAD);
    boolean themeImagesFastLoad = SessionParamUtil.getBoolean(request, "images_fast_load",
            PropsValues.THEME_IMAGES_FAST_LOAD);

    boolean themeJsBarebone = PropsValues.JAVASCRIPT_BAREBONE_ENABLED;

    if (themeJsBarebone) {
        if (signedIn) {
            themeJsBarebone = false;
        }
    }

    boolean themeJsFastLoad = SessionParamUtil.getBoolean(request, "js_fast_load",
            PropsValues.JAVASCRIPT_FAST_LOAD);

    String lifecycle = ParamUtil.getString(request, "p_p_lifecycle", "0");
    boolean isolated = ParamUtil.getBoolean(request, "p_p_isolated");

    String facebookCanvasPageURL = (String) request.getAttribute(WebKeys.FACEBOOK_CANVAS_PAGE_URL);

    boolean widget = false;

    Boolean widgetObj = (Boolean) request.getAttribute(WebKeys.WIDGET);

    if (widgetObj != null) {
        widget = widgetObj.booleanValue();
    }

    // Theme display

    ThemeDisplay themeDisplay = ThemeDisplayFactory.create();

    // Set the CDN host, portal URL, and Facebook application ID first
    // because other methods (setLookAndFeel) depend on them being set

    themeDisplay.setCDNHost(cdnHost);
    themeDisplay.setPortalURL(portalURL);
    themeDisplay.setFacebookCanvasPageURL(facebookCanvasPageURL);
    themeDisplay.setWidget(widget);

    themeDisplay.setCompany(company);
    themeDisplay.setCompanyLogo(companyLogo);
    themeDisplay.setCompanyLogoHeight(companyLogoHeight);
    themeDisplay.setCompanyLogoWidth(companyLogoWidth);
    themeDisplay.setRealCompanyLogo(realCompanyLogo);
    themeDisplay.setRealCompanyLogoHeight(realCompanyLogoHeight);
    themeDisplay.setRealCompanyLogoWidth(realCompanyLogoWidth);
    themeDisplay.setUser(user);
    themeDisplay.setRealUser(realUser);
    themeDisplay.setDoAsUserId(doAsUserId);
    themeDisplay.setDoAsUserLanguageId(doAsUserLanguageId);
    themeDisplay.setDoAsGroupId(doAsGroupId);
    themeDisplay.setRefererPlid(refererPlid);
    themeDisplay.setLayoutSetLogo(layoutSetLogo);
    themeDisplay.setLayout(layout);
    themeDisplay.setLayouts(layouts);
    themeDisplay.setPlid(plid);
    themeDisplay.setLayoutTypePortlet(layoutTypePortlet);
    themeDisplay.setScopeGroupId(scopeGroupId);
    themeDisplay.setParentGroupId(parentGroupId);
    themeDisplay.setSignedIn(signedIn);
    themeDisplay.setPermissionChecker(permissionChecker);
    themeDisplay.setLocale(locale);
    themeDisplay.setLanguageId(LocaleUtil.toLanguageId(locale));
    themeDisplay.setI18nLanguageId(i18nLanguageId);
    themeDisplay.setI18nPath(i18nPath);
    themeDisplay.setTimeZone(timeZone);
    themeDisplay.setLookAndFeel(contextPath, theme, colorScheme);
    themeDisplay.setThemeCssFastLoad(themeCssFastLoad);
    themeDisplay.setThemeImagesFastLoad(themeImagesFastLoad);
    themeDisplay.setThemeJsBarebone(themeJsBarebone);
    themeDisplay.setThemeJsFastLoad(themeJsFastLoad);
    themeDisplay.setServerName(request.getServerName());
    themeDisplay.setServerPort(request.getServerPort());
    themeDisplay.setSecure(request.isSecure());
    themeDisplay.setLifecycle(lifecycle);
    themeDisplay.setLifecycleAction(lifecycle.equals("1"));
    themeDisplay.setLifecycleRender(lifecycle.equals("0"));
    themeDisplay.setLifecycleResource(lifecycle.equals("2"));
    themeDisplay.setStateExclusive(LiferayWindowState.isExclusive(request));
    themeDisplay.setStateMaximized(LiferayWindowState.isMaximized(request));
    themeDisplay.setStatePopUp(LiferayWindowState.isPopUp(request));
    themeDisplay.setIsolated(isolated);
    themeDisplay.setPathApplet(contextPath.concat("/applets"));
    themeDisplay.setPathCms(contextPath.concat("/cms"));
    themeDisplay.setPathContext(contextPath);
    themeDisplay.setPathFlash(contextPath.concat("/flash"));
    themeDisplay.setPathFriendlyURLPrivateGroup(friendlyURLPrivateGroupPath);
    themeDisplay.setPathFriendlyURLPrivateUser(friendlyURLPrivateUserPath);
    themeDisplay.setPathFriendlyURLPublic(friendlyURLPublicPath);
    themeDisplay.setPathImage(imagePath);
    themeDisplay.setPathJavaScript(cdnHost.concat(contextPath).concat("/html/js"));
    themeDisplay.setPathMain(mainPath);
    themeDisplay.setPathSound(contextPath.concat("/html/sound"));

    // URLs

    themeDisplay.setShowAddContentIcon(false);
    themeDisplay.setShowControlPanelIcon(signedIn);
    themeDisplay.setShowHomeIcon(true);
    themeDisplay.setShowMyAccountIcon(signedIn);
    themeDisplay.setShowPageSettingsIcon(false);
    themeDisplay.setShowPortalIcon(true);
    themeDisplay.setShowSignInIcon(!signedIn);
    themeDisplay.setShowSignOutIcon(signedIn);
    themeDisplay.setShowStagingIcon(false);

    String urlControlPanel = friendlyURLPrivateGroupPath.concat(GroupConstants.CONTROL_PANEL_FRIENDLY_URL);

    if (Validator.isNotNull(doAsUserId)) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "doAsUserId", doAsUserId);
    }

    if (scopeGroupId > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "doAsGroupId", scopeGroupId);
    }

    if (refererPlid > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "refererPlid", refererPlid);
    } else if (plid > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "refererPlid", plid);
    }

    themeDisplay.setURLControlPanel(urlControlPanel);

    PortletURL createAccountURL = new PortletURLImpl(request, PortletKeys.LOGIN, plid,
            PortletRequest.ACTION_PHASE);

    createAccountURL.setWindowState(WindowState.MAXIMIZED);
    createAccountURL.setPortletMode(PortletMode.VIEW);

    createAccountURL.setParameter("saveLastPath", "0");
    createAccountURL.setParameter("struts_action", "/login/create_account");

    themeDisplay.setURLCreateAccount(createAccountURL);

    String currentURL = PortalUtil.getCurrentURL(request);

    themeDisplay.setURLCurrent(currentURL);

    String urlHome = PortalUtil.getHomeURL(request);

    themeDisplay.setURLHome(urlHome);

    if (layout != null) {
        if (layout.isTypePortlet()) {
            boolean freeformLayout = layoutTypePortlet.getLayoutTemplateId().equals("freeform");

            themeDisplay.setFreeformLayout(freeformLayout);

            boolean hasUpdateLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout,
                    ActionKeys.UPDATE);

            if (hasUpdateLayoutPermission) {
                themeDisplay.setShowAddContentIconPermission(true);

                if (!LiferayWindowState.isMaximized(request)) {
                    themeDisplay.setShowAddContentIcon(true);
                }

                themeDisplay.setShowLayoutTemplatesIcon(true);

                themeDisplay.setURLAddContent("Liferay.LayoutConfiguration.toggle('"
                        .concat(PortletKeys.LAYOUT_CONFIGURATION).concat("');"));

                themeDisplay.setURLLayoutTemplates("Liferay.LayoutConfiguration.showTemplates();");
            }
        }

        boolean hasManageLayoutsPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.MANAGE_LAYOUTS);

        if (group.isUser()) {
            if ((layout.isPrivateLayout() && !PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_MODIFIABLE)
                    || (layout.isPublicLayout() && !PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_MODIFIABLE)) {

                hasManageLayoutsPermission = false;
            }
        }

        if (hasManageLayoutsPermission) {
            themeDisplay.setShowPageSettingsIcon(true);

            PortletURL pageSettingsURL = new PortletURLImpl(request, PortletKeys.LAYOUT_MANAGEMENT, plid,
                    PortletRequest.RENDER_PHASE);

            pageSettingsURL.setWindowState(WindowState.MAXIMIZED);
            pageSettingsURL.setPortletMode(PortletMode.VIEW);

            pageSettingsURL.setParameter("struts_action", "/layout_management/edit_pages");

            if (layout.isPrivateLayout()) {
                pageSettingsURL.setParameter("tabs1", "private-pages");
            } else {
                pageSettingsURL.setParameter("tabs1", "public-pages");
            }

            pageSettingsURL.setParameter("redirect", currentURL);
            pageSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId));
            pageSettingsURL.setParameter("selPlid", String.valueOf(plid));

            themeDisplay.setURLPageSettings(pageSettingsURL);
        }

        if (group.hasStagingGroup() && !group.isStagingGroup()) {
            themeDisplay.setShowAddContentIcon(false);
            themeDisplay.setShowLayoutTemplatesIcon(false);
            themeDisplay.setShowPageSettingsIcon(false);
            themeDisplay.setURLPublishToLive(null);
        }

        if (group.isControlPanel()) {
            themeDisplay.setShowPageSettingsIcon(false);
            themeDisplay.setURLPublishToLive(null);
        }

        // LEP-4987

        if (group.isStaged() || group.isStagingGroup()) {
            boolean hasApproveProposalPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                    ActionKeys.APPROVE_PROPOSAL);

            boolean hasPublishStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                    ActionKeys.PUBLISH_STAGING);

            if (hasApproveProposalPermission || hasManageLayoutsPermission || hasPublishStagingPermission) {

                themeDisplay.setShowStagingIcon(true);
            }

            if (hasPublishStagingPermission) {
                PortletURL publishToLiveURL = new PortletURLImpl(request, PortletKeys.LAYOUT_MANAGEMENT, plid,
                        PortletRequest.RENDER_PHASE);

                publishToLiveURL.setWindowState(LiferayWindowState.EXCLUSIVE);
                publishToLiveURL.setPortletMode(PortletMode.VIEW);

                publishToLiveURL.setParameter("struts_action", "/layout_management/export_pages");

                if (layout.isPrivateLayout()) {
                    publishToLiveURL.setParameter("tabs1", "private-pages");
                } else {
                    publishToLiveURL.setParameter("tabs1", "public-pages");
                }

                publishToLiveURL.setParameter("pagesRedirect", currentURL);
                publishToLiveURL.setParameter("groupId", String.valueOf(scopeGroupId));
                publishToLiveURL.setParameter("selPlid", String.valueOf(plid));

                themeDisplay.setURLPublishToLive(publishToLiveURL);
            }
        }

        String myAccountNamespace = PortalUtil.getPortletNamespace(PortletKeys.MY_ACCOUNT);

        String myAccountRedirect = ParamUtil.getString(request, myAccountNamespace.concat("backURL"),
                currentURL);

        Group controlPanelGroup = GroupLocalServiceUtil.getGroup(companyId, GroupConstants.CONTROL_PANEL);

        long controlPanelPlid = LayoutLocalServiceUtil.getDefaultPlid(controlPanelGroup.getGroupId(), true);

        PortletURLImpl myAccountURL = new PortletURLImpl(request, PortletKeys.MY_ACCOUNT, controlPanelPlid,
                PortletRequest.RENDER_PHASE);

        myAccountURL.setWindowState(WindowState.MAXIMIZED);
        myAccountURL.setPortletMode(PortletMode.VIEW);
        myAccountURL.setRefererPlid(plid);

        myAccountURL.setParameter("struts_action", "/my_account/edit_user");
        myAccountURL.setParameter("backURL", myAccountRedirect);

        themeDisplay.setURLMyAccount(myAccountURL);
    }

    if ((!user.isActive()) || (PrefsPropsUtil.getBoolean(companyId, PropsKeys.TERMS_OF_USE_REQUIRED)
            && !user.isAgreedToTermsOfUse())) {

        themeDisplay.setShowAddContentIcon(false);
        themeDisplay.setShowMyAccountIcon(false);
        themeDisplay.setShowPageSettingsIcon(false);
    }

    if (group.isLayoutPrototype()) {
        themeDisplay.setShowControlPanelIcon(false);
        themeDisplay.setShowHomeIcon(false);
        themeDisplay.setShowMyAccountIcon(false);
        themeDisplay.setShowPageSettingsIcon(true);
        themeDisplay.setShowPortalIcon(false);
        themeDisplay.setShowSignInIcon(false);
        themeDisplay.setShowSignOutIcon(false);
        themeDisplay.setShowStagingIcon(false);
    }

    themeDisplay.setURLPortal(portalURL.concat(contextPath));

    String urlSignIn = mainPath.concat("/portal/login");

    if (layout != null) {
        urlSignIn = HttpUtil.addParameter(urlSignIn, "p_l_id", layout.getPlid());
    }

    themeDisplay.setURLSignIn(urlSignIn);

    themeDisplay.setURLSignOut(mainPath.concat("/portal/logout"));

    PortletURL updateManagerURL = new PortletURLImpl(request, PortletKeys.UPDATE_MANAGER, plid,
            PortletRequest.RENDER_PHASE);

    updateManagerURL.setWindowState(WindowState.MAXIMIZED);
    updateManagerURL.setPortletMode(PortletMode.VIEW);

    updateManagerURL.setParameter("struts_action", "/update_manager/view");

    themeDisplay.setURLUpdateManager(updateManagerURL);

    request.setAttribute(WebKeys.THEME_DISPLAY, themeDisplay);

    // Parallel render

    boolean parallelRenderEnable = true;

    if (layout != null) {
        List<String> portletIds = layoutTypePortlet.getPortletIds();

        if (portletIds.size() == 1) {
            String portletId = portletIds.get(0);

            Portlet portlet = PortletLocalServiceUtil.getPortletById(portletId);

            if ((portlet != null) && !portlet.isAjaxable()) {
                parallelRenderEnable = false;
            }
        }
    }

    Boolean parallelRenderEnableObj = Boolean
            .valueOf(ParamUtil.getBoolean(request, "p_p_parallel", parallelRenderEnable));

    request.setAttribute(WebKeys.PORTLET_PARALLEL_RENDER, parallelRenderEnableObj);
}

From source file:com.liferay.portal.events.ServicePreAction.java

public ThemeDisplay initThemeDisplay(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    HttpSession session = request.getSession();

    // Company//w ww .  j ava  2  s .  c o m

    Company company = PortalUtil.getCompany(request);

    long companyId = company.getCompanyId();

    // CDN host

    String cdnHost = PortalUtil.getCDNHost(request);

    String dynamicResourcesCDNHost = StringPool.BLANK;

    boolean cdnDynamicResourceEnabled = PortalUtil.isCDNDynamicResourcesEnabled(request);

    if (cdnDynamicResourceEnabled) {
        dynamicResourcesCDNHost = cdnHost;
    }

    // Portal URL

    String portalURL = PortalUtil.getPortalURL(request);

    // Paths

    String contextPath = PortalUtil.getPathContext();
    String friendlyURLPrivateGroupPath = PortalUtil.getPathFriendlyURLPrivateGroup();
    String friendlyURLPrivateUserPath = PortalUtil.getPathFriendlyURLPrivateUser();
    String friendlyURLPublicPath = PortalUtil.getPathFriendlyURLPublic();
    String imagePath = dynamicResourcesCDNHost.concat(PortalUtil.getPathImage());
    String mainPath = PortalUtil.getPathMain();

    String i18nPath = (String) request.getAttribute(WebKeys.I18N_PATH);

    if (Validator.isNotNull(i18nPath)) {
        if (Validator.isNotNull(contextPath)) {
            String i18nContextPath = contextPath.concat(i18nPath);

            friendlyURLPrivateGroupPath = StringUtil.replaceFirst(friendlyURLPrivateGroupPath, contextPath,
                    i18nContextPath);
            friendlyURLPrivateUserPath = StringUtil.replaceFirst(friendlyURLPrivateUserPath, contextPath,
                    i18nContextPath);
            friendlyURLPublicPath = StringUtil.replaceFirst(friendlyURLPublicPath, contextPath,
                    i18nContextPath);
            mainPath = StringUtil.replaceFirst(mainPath, contextPath, i18nContextPath);
        } else {
            friendlyURLPrivateGroupPath = i18nPath.concat(friendlyURLPrivateGroupPath);
            friendlyURLPrivateUserPath = i18nPath.concat(friendlyURLPrivateUserPath);
            friendlyURLPublicPath = i18nPath.concat(friendlyURLPublicPath);
            mainPath = i18nPath.concat(mainPath);
        }
    }

    // Company logo

    StringBundler sb = new StringBundler(5);

    sb.append(imagePath);
    sb.append("/company_logo?img_id=");
    sb.append(company.getLogoId());
    sb.append("&t=");
    sb.append(WebServerServletTokenUtil.getToken(company.getLogoId()));

    String companyLogo = sb.toString();

    int companyLogoHeight = 0;
    int companyLogoWidth = 0;

    Image companyLogoImage = ImageLocalServiceUtil.getCompanyLogo(company.getLogoId());

    if (companyLogoImage != null) {
        companyLogoHeight = companyLogoImage.getHeight();
        companyLogoWidth = companyLogoImage.getWidth();
    }

    String realCompanyLogo = companyLogo;
    int realCompanyLogoHeight = companyLogoHeight;
    int realCompanyLogoWidth = companyLogoWidth;

    // User

    User user = null;

    try {
        user = PortalUtil.getUser(request);
    } catch (NoSuchUserException nsue) {
        if (_log.isWarnEnabled()) {
            _log.warn(nsue.getMessage());
        }

        long userId = PortalUtil.getUserId(request);

        if (userId > 0) {
            session.invalidate();
        }

        return null;
    }

    boolean signedIn = false;

    if (user == null) {
        user = company.getDefaultUser();
    } else if (!user.isDefaultUser()) {
        signedIn = true;
    }

    if (PropsValues.BROWSER_CACHE_DISABLED || (PropsValues.BROWSER_CACHE_SIGNED_IN_DISABLED && signedIn)) {

        response.setDateHeader(HttpHeaders.EXPIRES, 0);
        response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
        response.setHeader(HttpHeaders.PRAGMA, HttpHeaders.PRAGMA_NO_CACHE_VALUE);
    }

    User realUser = user;

    Long realUserId = (Long) session.getAttribute(WebKeys.USER_ID);

    if (realUserId != null) {
        if (user.getUserId() != realUserId.longValue()) {
            realUser = UserLocalServiceUtil.getUserById(realUserId.longValue());
        }
    }

    String doAsUserId = ParamUtil.getString(request, "doAsUserId");
    String doAsUserLanguageId = ParamUtil.getString(request, "doAsUserLanguageId");
    long doAsGroupId = ParamUtil.getLong(request, "doAsGroupId");

    long refererPlid = ParamUtil.getLong(request, "refererPlid");

    if (LayoutLocalServiceUtil.fetchLayout(refererPlid) == null) {
        refererPlid = 0;
    }

    String controlPanelCategory = ParamUtil.getString(request, "controlPanelCategory");

    // Permission checker

    PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

    PermissionThreadLocal.setPermissionChecker(permissionChecker);
    //Modification start (code changed and moved to the bottom)
    // Locale
    /*
        Locale locale = (Locale)session.getAttribute(Globals.LOCALE_KEY);
            
        if (Validator.isNotNull(doAsUserLanguageId)) {
          locale = LocaleUtil.fromLanguageId(doAsUserLanguageId);
        }
            
        String i18nLanguageId = (String)request.getAttribute(
              WebKeys.I18N_LANGUAGE_ID);
            
        if (Validator.isNotNull(i18nLanguageId)) {
          locale = LocaleUtil.fromLanguageId(i18nLanguageId);
        }
        else if (locale == null) {
          if (signedIn) {
              locale = user.getLocale();
          }
          else {
            
              // User previously set their preferred language
            
              String languageId = CookieKeys.getCookie(
          request, CookieKeys.GUEST_LANGUAGE_ID, false);
            
              if (Validator.isNotNull(languageId)) {
      locale = LocaleUtil.fromLanguageId(languageId);
              }
            
              // Get locale from the request
            
              if ((locale == null) && PropsValues.LOCALE_DEFAULT_REQUEST) {
      Enumeration<Locale> locales = request.getLocales();
            
      while (locales.hasMoreElements()) {
          Locale requestLocale = locales.nextElement();
            
          if (Validator.isNull(requestLocale.getCountry())) {
            
              // Locales must contain a country code
            
              requestLocale = LanguageUtil.getLocale(
                      requestLocale.getLanguage());
          }
            
          if (LanguageUtil.isAvailableLocale(requestLocale)) {
              locale = requestLocale;
            
              break;
          }
      }
              }
            
              // Get locale from the default user
            
              if (locale == null) {
      locale = user.getLocale();
              }
            
              if (Validator.isNull(locale.getCountry())) {
            
      // Locales must contain a country code
            
      locale = LanguageUtil.getLocale(locale.getLanguage());
              }
            
              if (!LanguageUtil.isAvailableLocale(locale)) {
      locale = user.getLocale();
              }
          }
            
          session.setAttribute(Globals.LOCALE_KEY, locale);
            
          LanguageUtil.updateCookie(request, response, locale);
        }*/
    //Modification end
    // Cookie support

    try {

        // LEP-4069

        CookieKeys.validateSupportCookie(request);
    } catch (Exception e) {
        CookieKeys.addSupportCookie(request, response);
    }

    // Time zone

    TimeZone timeZone = user.getTimeZone();

    if (timeZone == null) {
        timeZone = company.getTimeZone();
    }

    // Layouts

    if (signedIn) {
        updateUserLayouts(user);
    }

    Layout layout = null;
    List<Layout> layouts = null;

    long plid = ParamUtil.getLong(request, "p_l_id");

    if (plid > 0) {
        layout = LayoutLocalServiceUtil.getLayout(plid);

        long sourceGroupId = ParamUtil.getLong(request, "p_v_l_s_g_id");

        if ((sourceGroupId > 0) && (sourceGroupId != layout.getGroupId())) {
            Group sourceGroup = GroupLocalServiceUtil.getGroup(sourceGroupId);

            if (layout.isPublicLayout()
                    || SitesUtil.isUserGroupLayoutSetViewable(permissionChecker, layout.getGroup())) {

                layout = new VirtualLayout(layout, sourceGroup);
            } else {
                layout = null;
            }
        }
    } else {
        long groupId = ParamUtil.getLong(request, "groupId");
        boolean privateLayout = ParamUtil.getBoolean(request, "privateLayout");
        long layoutId = ParamUtil.getLong(request, "layoutId");

        if ((groupId > 0) && (layoutId > 0)) {
            layout = LayoutLocalServiceUtil.getLayout(groupId, privateLayout, layoutId);
        }
    }

    Boolean redirectToDefaultLayout = (Boolean) request.getAttribute(WebKeys.REDIRECT_TO_DEFAULT_LAYOUT);

    if (redirectToDefaultLayout == null) {
        redirectToDefaultLayout = Boolean.FALSE;
    }

    if (layout != null) {
        Group group = layout.getGroup();

        if (!signedIn && PropsValues.AUTH_FORWARD_BY_REDIRECT) {
            request.setAttribute(WebKeys.REQUESTED_LAYOUT, layout);
        }

        String ppid = ParamUtil.getString(request, "p_p_id");

        if (Validator.isNull(controlPanelCategory) && Validator.isNotNull(ppid)
                && (LiferayWindowState.isPopUp(request) || LiferayWindowState.isExclusive(request))) {

            controlPanelCategory = _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + ppid;
        }

        boolean viewableGroup = LayoutPermissionUtil.contains(permissionChecker, layout, controlPanelCategory,
                true, ActionKeys.VIEW);
        boolean viewableStaging = GroupPermissionUtil.contains(permissionChecker, group.getGroupId(),
                ActionKeys.VIEW_STAGING);

        if (viewableStaging) {
            layouts = LayoutLocalServiceUtil.getLayouts(layout.getGroupId(), layout.isPrivateLayout(),
                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
        } else if (!viewableGroup && group.isStagingGroup()) {
            layout = null;
        } else
        /* Permissions are managed by Mobile Portlet
        if (!isLoginRequest(request) &&
            (!viewableGroup ||
                (!redirectToDefaultLayout &&
          !LayoutPermissionUtil.contains(
              permissionChecker, layout, false,
              ActionKeys.VIEW)))) {
                
          if (user.isDefaultUser() &&
              PropsValues.AUTH_LOGIN_PROMPT_ENABLED) {
                
            throw new PrincipalException("User is not authenticated");
          }
                
          sb = new StringBundler(6);
                
          sb.append("User ");
          sb.append(user.getUserId());
          sb.append(" is not allowed to access the ");
          sb.append(layout.isPrivateLayout() ? "private" : "public");
          sb.append(" pages of group ");
          sb.append(layout.getGroupId());
                
          if (_log.isWarnEnabled()) {
            _log.warn(sb.toString());
          }
                
          throw new NoSuchLayoutException(sb.toString());
        } else*/ if (isLoginRequest(request) && !viewableGroup) {
            layout = null;
        } else if (group.isLayoutPrototype()) {
            layouts = new ArrayList<Layout>();
        } else {
            layouts = LayoutLocalServiceUtil.getLayouts(layout.getGroupId(), layout.isPrivateLayout(),
                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);

            if (!group.isControlPanel()) {
                doAsGroupId = 0;
            }
        }
    }

    List<Layout> unfilteredLayouts = layouts;

    if (layout == null) {
        Object[] defaultLayout = getDefaultLayout(request, user, signedIn);

        layout = (Layout) defaultLayout[0];
        layouts = (List<Layout>) defaultLayout[1];

        request.setAttribute(WebKeys.LAYOUT_DEFAULT, Boolean.TRUE);
    }

    Object[] viewableLayouts = getViewableLayouts(request, user, permissionChecker, layout, layouts);

    String layoutSetLogo = null;

    layout = (Layout) viewableLayouts[0];
    layouts = (List<Layout>) viewableLayouts[1];

    Group group = null;

    if (layout != null) {
        group = layout.getGroup();

        if (!group.isControlPanel()) {
            rememberVisitedGroupIds(request, group.getGroupId());
        }
    }

    LayoutTypePortlet layoutTypePortlet = null;

    layouts = mergeAdditionalLayouts(request, user, permissionChecker, layout, layouts);

    LayoutSet layoutSet = null;

    boolean hasCustomizeLayoutPermission = false;
    boolean hasUpdateLayoutPermission = false;

    boolean customizedView = SessionParamUtil.getBoolean(request, "customized_view", true);

    if (layout != null) {
        hasCustomizeLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout,
                ActionKeys.CUSTOMIZE);
        hasUpdateLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.UPDATE);

        layoutSet = layout.getLayoutSet();

        if (company.isSiteLogo()) {
            long logoId = 0;

            if (layoutSet.isLogo()) {
                logoId = layoutSet.getLogoId();

                if (logoId == 0) {
                    logoId = layoutSet.getLiveLogoId();
                }
            } else {
                LayoutSet siblingLayoutSet = LayoutSetLocalServiceUtil.getLayoutSet(layout.getGroupId(),
                        !layout.isPrivateLayout());

                if (siblingLayoutSet.isLogo()) {
                    logoId = siblingLayoutSet.getLogoId();
                }
            }

            if (logoId > 0) {
                sb = new StringBundler(5);

                sb.append(imagePath);
                sb.append("/layout_set_logo?img_id=");
                sb.append(logoId);
                sb.append("&t=");
                sb.append(WebServerServletTokenUtil.getToken(logoId));

                layoutSetLogo = sb.toString();

                Image layoutSetLogoImage = ImageLocalServiceUtil.getCompanyLogo(logoId);

                companyLogo = layoutSetLogo;
                companyLogoHeight = layoutSetLogoImage.getHeight();
                companyLogoWidth = layoutSetLogoImage.getWidth();
            }
        }

        plid = layout.getPlid();

        // Updates to shared layouts are not reflected until the next time
        // the user logs in because group layouts are cached in the session

        layout = (Layout) layout.clone();

        layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

        boolean customizable = layoutTypePortlet.isCustomizable();

        if (!customizable || (group.isLayoutPrototype() || group.isLayoutSetPrototype())) {

            customizedView = false;
        }

        layoutTypePortlet.setCustomizedView(customizedView);
        layoutTypePortlet.setUpdatePermission(hasUpdateLayoutPermission);

        if (signedIn && customizable && customizedView && hasCustomizeLayoutPermission) {

            PortalPreferences portalPreferences = PortletPreferencesFactoryUtil.getPortalPreferences(companyId,
                    user.getUserId(), true);

            layoutTypePortlet.setPortalPreferences(portalPreferences);
        }

        LayoutClone layoutClone = LayoutCloneFactory.getInstance();

        if (layoutClone != null) {
            String typeSettings = layoutClone.get(request, plid);

            if (typeSettings != null) {
                UnicodeProperties typeSettingsProperties = new UnicodeProperties(true);

                typeSettingsProperties.load(typeSettings);

                String stateMax = typeSettingsProperties.getProperty(LayoutTypePortletConstants.STATE_MAX);
                String stateMin = typeSettingsProperties.getProperty(LayoutTypePortletConstants.STATE_MIN);
                String modeAbout = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_ABOUT);
                String modeConfig = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_CONFIG);
                String modeEdit = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_EDIT);
                String modeEditDefaults = typeSettingsProperties
                        .getProperty(LayoutTypePortletConstants.MODE_EDIT_DEFAULTS);
                String modeEditGuest = typeSettingsProperties
                        .getProperty(LayoutTypePortletConstants.MODE_EDIT_GUEST);
                String modeHelp = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_HELP);
                String modePreview = typeSettingsProperties
                        .getProperty(LayoutTypePortletConstants.MODE_PREVIEW);
                String modePrint = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_PRINT);

                layoutTypePortlet.setStateMax(stateMax);
                layoutTypePortlet.setStateMin(stateMin);
                layoutTypePortlet.setModeAbout(modeAbout);
                layoutTypePortlet.setModeConfig(modeConfig);
                layoutTypePortlet.setModeEdit(modeEdit);
                layoutTypePortlet.setModeEditDefaults(modeEditDefaults);
                layoutTypePortlet.setModeEditGuest(modeEditGuest);
                layoutTypePortlet.setModeHelp(modeHelp);
                layoutTypePortlet.setModePreview(modePreview);
                layoutTypePortlet.setModePrint(modePrint);
            }
        }

        request.setAttribute(WebKeys.LAYOUT, layout);
        request.setAttribute(WebKeys.LAYOUTS, layouts);
    }

    // Scope

    long scopeGroupId = PortalUtil.getScopeGroupId(request);

    if ((scopeGroupId <= 0) && (doAsGroupId > 0)) {
        scopeGroupId = doAsGroupId;
    }

    long parentGroupId = PortalUtil.getParentGroupId(scopeGroupId);

    // Theme and color scheme

    Theme theme = null;
    ColorScheme colorScheme = null;

    boolean wapTheme = BrowserSnifferUtil.isWap(request);

    if ((layout != null) && group.isControlPanel()) {
        String themeId = PrefsPropsUtil.getString(companyId, PropsKeys.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID);
        String colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId();

        theme = ThemeLocalServiceUtil.getTheme(companyId, themeId, wapTheme);
        colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId,
                wapTheme);

        if (!wapTheme && theme.isWapTheme()) {
            theme = ThemeLocalServiceUtil.getTheme(companyId, PropsValues.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID,
                    false);
            colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId,
                    false);
        }

        request.setAttribute(WebKeys.THEME, theme);
        request.setAttribute(WebKeys.COLOR_SCHEME, colorScheme);
    }

    boolean themeCssFastLoad = SessionParamUtil.getBoolean(request, "css_fast_load",
            PropsValues.THEME_CSS_FAST_LOAD);
    boolean themeImagesFastLoad = SessionParamUtil.getBoolean(request, "images_fast_load",
            PropsValues.THEME_IMAGES_FAST_LOAD);

    boolean themeJsBarebone = PropsValues.JAVASCRIPT_BAREBONE_ENABLED;

    if (themeJsBarebone) {
        if (signedIn) {
            themeJsBarebone = false;
        }
    }

    boolean themeJsFastLoad = SessionParamUtil.getBoolean(request, "js_fast_load",
            PropsValues.JAVASCRIPT_FAST_LOAD);

    String lifecycle = ParamUtil.getString(request, "p_p_lifecycle", "0");

    lifecycle = ParamUtil.getString(request, "p_t_lifecycle", lifecycle);

    boolean isolated = ParamUtil.getBoolean(request, "p_p_isolated");

    String facebookCanvasPageURL = (String) request.getAttribute(WebKeys.FACEBOOK_CANVAS_PAGE_URL);

    boolean widget = false;

    Boolean widgetObj = (Boolean) request.getAttribute(WebKeys.WIDGET);

    if (widgetObj != null) {
        widget = widgetObj.booleanValue();
    }

    ////////// Modification start //////////

    // Locale
    Locale locale = null;
    String[] languageIds = request.getParameterMap().get("languageId");
    if (languageIds != null && languageIds.length > 0 && StringUtils.isNotEmpty(languageIds[0])) {
        Locale localeFromLanguageId = LocaleUtil.fromLanguageId(languageIds[0]);
        session.setAttribute(Globals.LOCALE_KEY, localeFromLanguageId);
    }
    try {
        locale = (Locale) session.getAttribute(Globals.LOCALE_KEY);
    } catch (IllegalStateException e) {
        _log.warn("Can't get locale from session, session is invalidated");
    }
    if (Validator.isNotNull(doAsUserLanguageId)) {
        locale = LocaleUtil.fromLanguageId(doAsUserLanguageId);
    }

    String i18nLanguageId = (String) request.getAttribute(WebKeys.I18N_LANGUAGE_ID);
    if (Validator.isNotNull(i18nLanguageId)) {
        locale = LocaleUtil.fromLanguageId(i18nLanguageId);
    }

    if (locale == null) {
        locale = LanguageDetectionUtil.detectLocale(request);
    }

    ////////// Modification end //////////

    // Theme display

    ThemeDisplay themeDisplay = ThemeDisplayFactory.create();
    //Modification start
    //    themeDisplay.setHttpServletRequest(request);
    //Modification end

    // Set the CDN host, portal URL, and Facebook application ID first
    // because other methods (setLookAndFeel) depend on them being set

    themeDisplay.setCDNHost(cdnHost);
    themeDisplay.setCDNDynamicResourcesHost(dynamicResourcesCDNHost);
    themeDisplay.setPortalURL(portalURL);
    themeDisplay.setFacebookCanvasPageURL(facebookCanvasPageURL);
    themeDisplay.setWidget(widget);

    themeDisplay.setCompany(company);
    themeDisplay.setCompanyLogo(companyLogo);
    themeDisplay.setCompanyLogoHeight(companyLogoHeight);
    themeDisplay.setCompanyLogoWidth(companyLogoWidth);
    themeDisplay.setRealCompanyLogo(realCompanyLogo);
    themeDisplay.setRealCompanyLogoHeight(realCompanyLogoHeight);
    themeDisplay.setRealCompanyLogoWidth(realCompanyLogoWidth);
    themeDisplay.setUser(user);
    themeDisplay.setRealUser(realUser);
    themeDisplay.setDoAsUserId(doAsUserId);
    themeDisplay.setDoAsUserLanguageId(doAsUserLanguageId);
    themeDisplay.setDoAsGroupId(doAsGroupId);
    themeDisplay.setRefererPlid(refererPlid);
    themeDisplay.setControlPanelCategory(controlPanelCategory);
    themeDisplay.setLayoutSet(layoutSet);
    themeDisplay.setLayoutSetLogo(layoutSetLogo);
    themeDisplay.setLayout(layout);
    themeDisplay.setLayouts(layouts);
    themeDisplay.setUnfilteredLayouts(unfilteredLayouts);
    themeDisplay.setPlid(plid);
    themeDisplay.setLayoutTypePortlet(layoutTypePortlet);
    themeDisplay.setScopeGroupId(scopeGroupId);
    themeDisplay.setParentGroupId(parentGroupId);
    themeDisplay.setSignedIn(signedIn);
    themeDisplay.setPermissionChecker(permissionChecker);
    themeDisplay.setLocale(locale);
    themeDisplay.setLanguageId(LocaleUtil.toLanguageId(locale));
    themeDisplay.setI18nLanguageId(i18nLanguageId);
    themeDisplay.setI18nPath(i18nPath);
    themeDisplay.setTimeZone(timeZone);
    themeDisplay.setLookAndFeel(theme, colorScheme);
    themeDisplay.setThemeCssFastLoad(themeCssFastLoad);
    themeDisplay.setThemeImagesFastLoad(themeImagesFastLoad);
    themeDisplay.setThemeJsBarebone(themeJsBarebone);
    themeDisplay.setThemeJsFastLoad(themeJsFastLoad);
    themeDisplay.setServerName(request.getServerName());
    themeDisplay.setServerPort(request.getServerPort());
    themeDisplay.setSecure(request.isSecure());
    themeDisplay.setLifecycle(lifecycle);
    themeDisplay.setLifecycleAction(lifecycle.equals("1"));
    themeDisplay.setLifecycleRender(lifecycle.equals("0"));
    themeDisplay.setLifecycleResource(lifecycle.equals("2"));
    themeDisplay.setStateExclusive(LiferayWindowState.isExclusive(request));
    themeDisplay.setStateMaximized(LiferayWindowState.isMaximized(request));
    themeDisplay.setStatePopUp(LiferayWindowState.isPopUp(request));
    themeDisplay.setIsolated(isolated);
    themeDisplay.setPathApplet(contextPath.concat("/applets"));
    themeDisplay.setPathCms(contextPath.concat("/cms"));
    themeDisplay.setPathContext(contextPath);
    themeDisplay.setPathFlash(contextPath.concat("/flash"));
    themeDisplay.setPathFriendlyURLPrivateGroup(friendlyURLPrivateGroupPath);
    themeDisplay.setPathFriendlyURLPrivateUser(friendlyURLPrivateUserPath);
    themeDisplay.setPathFriendlyURLPublic(friendlyURLPublicPath);
    themeDisplay.setPathImage(imagePath);
    themeDisplay.setPathJavaScript(contextPath.concat("/html/js"));
    themeDisplay.setPathMain(mainPath);
    themeDisplay.setPathSound(contextPath.concat("/html/sound"));

    // Icons

    themeDisplay.setShowAddContentIcon(false);
    themeDisplay.setShowControlPanelIcon(signedIn);
    themeDisplay.setShowHomeIcon(true);
    themeDisplay.setShowMyAccountIcon(signedIn);
    themeDisplay.setShowPageSettingsIcon(false);
    themeDisplay.setShowPortalIcon(true);
    themeDisplay.setShowSignInIcon(!signedIn);
    themeDisplay.setShowSignOutIcon(signedIn);

    boolean showSiteContentIcon = false;

    long controlPanelPlid = 0;

    if (signedIn) {
        Group controlPanelGroup = GroupLocalServiceUtil.getGroup(companyId, GroupConstants.CONTROL_PANEL);

        controlPanelPlid = LayoutLocalServiceUtil.getDefaultPlid(controlPanelGroup.getGroupId(), true);

        List<Portlet> siteContentPortlets = PortalUtil.getControlPanelPortlets(PortletCategoryKeys.CONTENT,
                themeDisplay);

        Portlet groupPagesPortlet = PortletLocalServiceUtil.getPortletById(PortletKeys.GROUP_PAGES);

        siteContentPortlets.remove(groupPagesPortlet);

        Portlet siteMembershipsAdminPortlet = PortletLocalServiceUtil
                .getPortletById(PortletKeys.SITE_MEMBERSHIPS_ADMIN);

        siteContentPortlets.remove(siteMembershipsAdminPortlet);

        Portlet siteSettingsPortlet = PortletLocalServiceUtil.getPortletById(PortletKeys.SITE_SETTINGS);

        siteContentPortlets.remove(siteSettingsPortlet);

        showSiteContentIcon = PortletPermissionUtil.contains(permissionChecker, scopeGroupId, controlPanelPlid,
                siteContentPortlets, ActionKeys.VIEW);
    }

    themeDisplay.setShowSiteContentIcon(showSiteContentIcon);

    themeDisplay.setShowStagingIcon(false);

    // Session

    if (PropsValues.SESSION_ENABLE_URL_WITH_SESSION_ID && !CookieKeys.hasSessionId(request)) {

        themeDisplay.setAddSessionIdToURL(true);
        themeDisplay.setSessionId(session.getId());
    }

    // URLs

    String urlControlPanel = friendlyURLPrivateGroupPath.concat(GroupConstants.CONTROL_PANEL_FRIENDLY_URL);

    if (Validator.isNotNull(doAsUserId)) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "doAsUserId", doAsUserId);
    }

    if (scopeGroupId > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "doAsGroupId", scopeGroupId);
    }

    if (refererPlid > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "refererPlid", refererPlid);
    } else if (plid > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "refererPlid", plid);
    }

    if (themeDisplay.isAddSessionIdToURL()) {
        urlControlPanel = PortalUtil.getURLWithSessionId(urlControlPanel, session.getId());
    }

    themeDisplay.setURLControlPanel(urlControlPanel);

    String siteContentURL = urlControlPanel;

    siteContentURL = HttpUtil.addParameter(siteContentURL, "controlPanelCategory", PortletCategoryKeys.CONTENT);

    themeDisplay.setURLSiteContent(siteContentURL);

    String currentURL = PortalUtil.getCurrentURL(request);

    themeDisplay.setURLCurrent(currentURL);

    String urlHome = PortalUtil.getHomeURL(request);

    themeDisplay.setURLHome(urlHome);

    if (layout != null) {
        if (layout.isTypePortlet()) {
            boolean freeformLayout = layoutTypePortlet.getLayoutTemplateId().equals("freeform");

            themeDisplay.setFreeformLayout(freeformLayout);

            if (hasUpdateLayoutPermission) {
                themeDisplay.setShowAddContentIconPermission(true);

                if (!LiferayWindowState.isMaximized(request)) {
                    themeDisplay.setShowAddContentIcon(true);
                }

                themeDisplay.setShowLayoutTemplatesIcon(true);

                if (!group.isUser()) {
                    themeDisplay.setShowPageCustomizationIcon(true);
                }

                themeDisplay.setURLAddContent("Liferay.LayoutConfiguration.toggle('"
                        .concat(PortletKeys.LAYOUT_CONFIGURATION).concat("');"));

                themeDisplay.setURLLayoutTemplates("Liferay.LayoutConfiguration.showTemplates();");
            }

            if (hasCustomizeLayoutPermission && customizedView) {
                themeDisplay.setShowAddContentIconPermission(true);

                if (!LiferayWindowState.isMaximized(request)) {
                    themeDisplay.setShowAddContentIcon(true);
                }

                themeDisplay.setURLAddContent("Liferay.LayoutConfiguration.toggle('"
                        .concat(PortletKeys.LAYOUT_CONFIGURATION).concat("');"));
            }
        }

        if (hasUpdateLayoutPermission) {
            themeDisplay.setShowPageSettingsIcon(true);

            LiferayPortletURL pageSettingsURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN,
                    controlPanelPlid, PortletRequest.RENDER_PHASE);

            pageSettingsURL.setControlPanelCategory(
                    _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.LAYOUTS_ADMIN);
            pageSettingsURL.setDoAsGroupId(scopeGroupId);
            pageSettingsURL.setParameter("struts_action", "/layouts_admin/edit_layouts");

            if (layout.isPrivateLayout()) {
                pageSettingsURL.setParameter("tabs1", "private-pages");
            } else {
                pageSettingsURL.setParameter("tabs1", "public-pages");
            }

            pageSettingsURL.setParameter("closeRedirect", currentURL);
            pageSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId));
            pageSettingsURL.setParameter("selPlid", String.valueOf(plid));
            pageSettingsURL.setPortletMode(PortletMode.VIEW);
            pageSettingsURL.setWindowState(LiferayWindowState.POP_UP);

            themeDisplay.setURLPageSettings(pageSettingsURL);

            boolean site = group.isSite();

            if (!site && group.isStagingGroup()) {
                Group liveGroup = group.getLiveGroup();

                site = liveGroup.isSite();
            }

            if (site && GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                    ActionKeys.ASSIGN_MEMBERS)) {

                themeDisplay.setShowManageSiteMembershipsIcon(true);

                LiferayPortletURL manageSiteMembershipsURL = new PortletURLImpl(request,
                        PortletKeys.SITE_MEMBERSHIPS_ADMIN, controlPanelPlid, PortletRequest.RENDER_PHASE);

                manageSiteMembershipsURL.setControlPanelCategory(
                        _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.SITE_MEMBERSHIPS_ADMIN);
                manageSiteMembershipsURL.setDoAsGroupId(scopeGroupId);
                manageSiteMembershipsURL.setParameter("struts_action", "/sites_admin/edit_site_assignments");
                manageSiteMembershipsURL.setParameter("groupId", String.valueOf(scopeGroupId));
                manageSiteMembershipsURL.setParameter("selPlid", String.valueOf(plid));
                manageSiteMembershipsURL.setPortletMode(PortletMode.VIEW);
                manageSiteMembershipsURL.setWindowState(LiferayWindowState.POP_UP);

                themeDisplay.setURLManageSiteMemberships(manageSiteMembershipsURL);
            } else {
                themeDisplay.setShowManageSiteMembershipsIcon(false);
            }
        }

        boolean hasAddLayoutGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.ADD_LAYOUT);
        boolean hasAddLayoutLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout,
                ActionKeys.ADD_LAYOUT);
        boolean hasManageLayoutsGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.MANAGE_LAYOUTS);
        boolean hasManageStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.MANAGE_STAGING);
        boolean hasPublishStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.PUBLISH_STAGING);
        boolean hasUpdateGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.UPDATE);
        boolean hasViewStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.VIEW_STAGING);

        if (!group.isControlPanel() && !group.isUser() && !group.isUserGroup() && hasUpdateGroupPermission) {

            themeDisplay.setShowSiteSettingsIcon(true);

            LiferayPortletURL siteSettingsURL = new PortletURLImpl(request, PortletKeys.SITE_SETTINGS,
                    controlPanelPlid, PortletRequest.RENDER_PHASE);

            siteSettingsURL.setControlPanelCategory(
                    _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.SITE_SETTINGS);
            siteSettingsURL.setDoAsGroupId(scopeGroupId);
            siteSettingsURL.setParameter("struts_action", "/sites_admin/edit_site");
            siteSettingsURL.setParameter("closeRedirect", currentURL);
            siteSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId));
            siteSettingsURL.setPortletMode(PortletMode.VIEW);
            siteSettingsURL.setWindowState(LiferayWindowState.POP_UP);

            themeDisplay.setURLSiteSettings(siteSettingsURL);
        }

        if (!group.isLayoutPrototype() && (hasAddLayoutGroupPermission || hasAddLayoutLayoutPermission
                || hasManageLayoutsGroupPermission || hasUpdateGroupPermission)) {

            themeDisplay.setShowSiteMapSettingsIcon(true);

            LiferayPortletURL siteMapSettingsURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN,
                    controlPanelPlid, PortletRequest.RENDER_PHASE);

            siteMapSettingsURL.setControlPanelCategory(
                    _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.LAYOUTS_ADMIN);
            siteMapSettingsURL.setDoAsGroupId(scopeGroupId);
            siteMapSettingsURL.setParameter("struts_action", "/layouts_admin/edit_layouts");

            if (layout.isPrivateLayout()) {
                siteMapSettingsURL.setParameter("tabs1", "private-pages");
            } else {
                siteMapSettingsURL.setParameter("tabs1", "public-pages");
            }

            siteMapSettingsURL.setParameter("closeRedirect", currentURL);
            siteMapSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId));
            siteMapSettingsURL.setPortletMode(PortletMode.VIEW);
            siteMapSettingsURL.setWindowState(LiferayWindowState.POP_UP);

            themeDisplay.setURLSiteMapSettings(siteMapSettingsURL);
        }

        if (group.hasStagingGroup() && !group.isStagingGroup()) {
            themeDisplay.setShowAddContentIcon(false);
            themeDisplay.setShowLayoutTemplatesIcon(false);
            themeDisplay.setShowPageSettingsIcon(false);
            themeDisplay.setURLPublishToLive(null);
        }

        if (group.isControlPanel()) {
            themeDisplay.setShowPageSettingsIcon(false);
            themeDisplay.setURLPublishToLive(null);
        }

        // LEP-4987

        if (group.isStaged() || group.isStagingGroup()) {
            if (hasManageStagingPermission || hasPublishStagingPermission || hasUpdateLayoutPermission
                    || hasViewStagingPermission) {

                themeDisplay.setShowStagingIcon(true);
            }

            if (hasPublishStagingPermission) {
                PortletURL publishToLiveURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN, plid,
                        PortletRequest.RENDER_PHASE);

                publishToLiveURL.setParameter("struts_action", "/layouts_admin/publish_layouts");

                if (layout.isPrivateLayout()) {
                    publishToLiveURL.setParameter("tabs1", "private-pages");
                } else {
                    publishToLiveURL.setParameter("tabs1", "public-pages");
                }

                publishToLiveURL.setParameter("pagesRedirect", currentURL);
                publishToLiveURL.setParameter("groupId", String.valueOf(scopeGroupId));
                publishToLiveURL.setParameter("selPlid", String.valueOf(plid));
                publishToLiveURL.setPortletMode(PortletMode.VIEW);
                publishToLiveURL.setWindowState(LiferayWindowState.EXCLUSIVE);

                themeDisplay.setURLPublishToLive(publishToLiveURL);
            }
        }

        PortletURLImpl myAccountURL = new PortletURLImpl(request, PortletKeys.MY_ACCOUNT, controlPanelPlid,
                PortletRequest.RENDER_PHASE);

        if (scopeGroupId > 0) {
            myAccountURL.setDoAsGroupId(scopeGroupId);
        }

        myAccountURL.setParameter("struts_action", "/my_account/edit_user");
        myAccountURL.setPortletMode(PortletMode.VIEW);

        if (refererPlid > 0) {
            myAccountURL.setRefererPlid(refererPlid);
        } else {
            myAccountURL.setRefererPlid(plid);
        }

        myAccountURL.setWindowState(WindowState.MAXIMIZED);

        themeDisplay.setURLMyAccount(myAccountURL);
    }

    if (!user.isActive() || (PrefsPropsUtil.getBoolean(companyId, PropsKeys.TERMS_OF_USE_REQUIRED)
            && !user.isAgreedToTermsOfUse())) {

        themeDisplay.setShowAddContentIcon(false);
        themeDisplay.setShowMyAccountIcon(false);
        themeDisplay.setShowPageSettingsIcon(false);
    }

    if (layout.isLayoutPrototypeLinkActive()) {
        themeDisplay.setShowPageCustomizationIcon(false);
    }

    if (group.isLayoutPrototype()) {
        themeDisplay.setShowControlPanelIcon(false);
        themeDisplay.setShowHomeIcon(false);
        themeDisplay.setShowManageSiteMembershipsIcon(false);
        themeDisplay.setShowMyAccountIcon(false);
        themeDisplay.setShowPageCustomizationIcon(false);
        themeDisplay.setShowPageSettingsIcon(true);
        themeDisplay.setShowPortalIcon(false);
        themeDisplay.setShowSignInIcon(false);
        themeDisplay.setShowSignOutIcon(false);
        themeDisplay.setShowSiteContentIcon(false);
        themeDisplay.setShowSiteSettingsIcon(false);
        themeDisplay.setShowStagingIcon(false);
    }

    if (group.isLayoutSetPrototype()) {
        themeDisplay.setShowPageCustomizationIcon(false);
        themeDisplay.setShowSiteSettingsIcon(false);
    }

    if (group.hasStagingGroup() && !group.isStagingGroup()) {
        themeDisplay.setShowLayoutTemplatesIcon(false);
        themeDisplay.setShowPageCustomizationIcon(false);
        themeDisplay.setShowPageSettingsIcon(false);
        themeDisplay.setShowSiteContentIcon(false);
        themeDisplay.setShowSiteMapSettingsIcon(false);
        themeDisplay.setShowSiteSettingsIcon(false);
    }

    themeDisplay.setURLPortal(portalURL.concat(contextPath));

    String urlSignIn = mainPath.concat("/portal/login");

    urlSignIn = HttpUtil.addParameter(urlSignIn, "p_l_id", layout.getPlid());

    themeDisplay.setURLSignIn(urlSignIn);

    themeDisplay.setURLSignOut(mainPath.concat("/portal/logout"));

    PortletURL updateManagerURL = new PortletURLImpl(request, PortletKeys.UPDATE_MANAGER, plid,
            PortletRequest.RENDER_PHASE);

    updateManagerURL.setParameter("struts_action", "/update_manager/view");
    updateManagerURL.setPortletMode(PortletMode.VIEW);
    updateManagerURL.setWindowState(WindowState.MAXIMIZED);

    themeDisplay.setURLUpdateManager(updateManagerURL);

    return themeDisplay;
}