Example usage for javax.servlet.jsp JspWriter print

List of usage examples for javax.servlet.jsp JspWriter print

Introduction

In this page you can find the example usage for javax.servlet.jsp JspWriter print.

Prototype


abstract public void print(Object obj) throws IOException;

Source Link

Document

Print an object.

Usage

From source file:com.redhat.rhn.frontend.taglibs.AddressTag.java

/** {@inheritDoc}
 * @throws JspException//from   w ww.j ava  2s . c om
 */
public int doStartTag() throws JspException {

    JspWriter out = null;
    try {
        out = pageContext.getOut();
        LocalizationService ls = LocalizationService.getInstance();

        StringBuilder result = new StringBuilder();
        StringBuilder key = new StringBuilder("address type ");
        key.append(type);
        result.append("<strong>");
        result.append(ls.getMessage(key.toString()));
        result.append("</strong>");
        if (user == null) {
            throw new IllegalArgumentException("User is null");
        }

        // If this Address is new
        if (address != null && StringUtils.isNotBlank(address.getCity())
                && StringUtils.isNotBlank(address.getZip())) {
            result.append("<address>");
            // Address 1 and 2
            result.append(address.getAddress1());
            result.append("<br />");
            if (StringUtils.isNotBlank(address.getAddress2())) {
                result.append(address.getAddress2());
                result.append("<br />");
            }

            // City
            result.append(address.getCity());
            if (StringUtils.isNotBlank(address.getState())) {
                result.append(", ");
                result.append(address.getState());
            }

            result.append(" ");
            result.append(address.getZip());
            result.append("<br />");

            // Phones
            result.append(ls.getMessage("phone"));
            result.append(": ");
            result.append(address.getPhone());
            result.append("<br />");
            if (StringUtils.isNotBlank(address.getFax())) {
                result.append(ls.getMessage("fax"));
                result.append(": ");
                result.append(address.getFax());
                result.append("<br />");
            }

            result.append("</address>");

            result.append("<p>");
            result.append("<a ").append("class=\"btn btn-primary\"").append(" href=\"").append(getActionUrl())
                    .append("/EditAddress.do?type=").append(type).append("&amp;uid=")
                    .append(String.valueOf(user.getId())).append("\">")
                    .append(ls.getMessage("Edit this address")).append("</a>");
            result.append("</p>");
        } else {
            result.append("<div class=\"alert alert-info\">");
            result.append(ls.getMessage("address not filled in"));
            result.append("</div>");
            result.append("<p>");
            result.append("<a ").append("class=\"btn btn-primary\"").append(" href=\"").append(getActionUrl())
                    .append("/EditAddress.do?type=").append(type).append("&amp;uid=")
                    .append(String.valueOf(user.getId())).append("\">")
                    .append(ls.getMessage("Fill in this address")).append("</a>");
            result.append("</p>");
        }

        out.print(result);
    } catch (IOException ioe) {
        throw new JspException("IO error writing to JSP file:", ioe);
    }

    return (SKIP_BODY);
}

From source file:org.codelabor.system.web.taglib.PaginationTag.java

@Override
public void doTag() throws JspException, IOException {
    logger.debug("doTag");

    // if numberOfRow is 0, do nothing
    if (numberOfRow == 0) {
        return;/*from  w w  w .ja  va2  s .c om*/
    }

    PageContext context = (PageContext) this.getJspContext();
    HttpServletRequest request = (HttpServletRequest) context.getRequest();
    JspWriter out = context.getOut();

    // queryString
    queryString = request.getQueryString();

    // max row per page
    String maxRowPerPageString = request.getParameter(maxRowPerPageParamName);
    if (!StringUtils.isBlank(maxRowPerPageString)) {
        maxRowPerPage = Integer.parseInt(maxRowPerPageString);
    }

    // total count
    int totalPageCount = (int) Math.ceil((double) numberOfRow / (double) maxRowPerPage);

    // page number
    int firstPageNo = 1;
    lastPageNo = totalPageCount;
    currentPageNo = 1;
    String pageNoString = request.getParameter(pageNoParamName);
    if (!StringUtils.isBlank(pageNoString)) {
        currentPageNo = Integer.parseInt(pageNoString);
    }

    // validation
    if (currentPageNo > lastPageNo) {
        StringBuilder sb = new StringBuilder();
        sb.append(pageNoParamName).append(" is exeeded.");
        sb.append(" (");
        sb.append("requested page number: ").append(currentPageNo).append(", ");
        sb.append("last page number: ").append(lastPageNo).append(")");
        throw new JspException(sb.toString());
    }

    // current index
    lastPageNoOnCurrentIndex = ((int) Math.ceil((double) currentPageNo / (double) maxIndexPerPage))
            * maxIndexPerPage;
    firstPageNoOnCurrentIndex = (lastPageNoOnCurrentIndex - maxIndexPerPage) + 1;

    // compensate page number
    if (lastPageNoOnCurrentIndex > lastPageNo) {
        lastPageNoOnCurrentIndex = lastPageNo;
    }

    // first page number on previous, next index
    firstPageNoOnPreviousIndex = firstPageNoOnCurrentIndex - maxIndexPerPage;
    firstPageNoOnNextIndex = lastPageNoOnCurrentIndex + 1;

    // compensate page number
    if (firstPageNoOnPreviousIndex < firstPageNo) {
        firstPageNoOnPreviousIndex = firstPageNo;
    }
    if (firstPageNoOnNextIndex > lastPageNo) {
        firstPageNoOnNextIndex = lastPageNo;
    }

    // first page number of first index
    firstPageNoOnFirstIndex = firstPageNo;

    // last page number of last index
    lastPageNoOnLastIndex = ((int) Math.ceil((double) numberOfRow / (double) maxRowPerPage));

    // debug
    logger.debug("queryString: {}", queryString);
    logger.debug("numberOfRow: {}", numberOfRow);
    logger.debug("totalPageCount: {}", totalPageCount);
    logger.debug("firstPageNo: {}", firstPageNo);
    logger.debug("lastPageNo: {}", lastPageNo);

    // write html tag
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter();
    sb.append("<div");
    if (!StringUtils.isBlank(cssClass)) {
        sb.append(" class=\"").append(cssClass).append("\"");
    }
    sb.append(" />");
    getJspBody().invoke(sw);
    sb.append(sw.getBuffer());
    sb.append("</ div>");
    out.print(sb.toString());
}

From source file:org.apache.jsp.happyaxis_jsp.java

public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;/*from   w ww.  ja  v a  2s  . c o  m*/
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
        response.setContentType("text/html; charset=utf-8");
        pageContext = _jspxFactory.getPageContext(this, request, response, null, false, 8192, true);
        _jspx_page_context = pageContext;
        application = pageContext.getServletContext();
        config = pageContext.getServletConfig();
        out = pageContext.getOut();
        _jspx_out = out;

        out.write("<html>\n");
        out.write("\n");

        /*
         * Copyright 2002,2004,2005 The Apache Software Foundation.
         *
         * Licensed under the Apache License, Version 2.0 (the "License");
         * you may not use this file except in compliance with the License.
         * You may obtain a copy of the License at
         *
         *      http://www.apache.org/licenses/LICENSE-2.0
         *
         * Unless required by applicable law or agreed to in writing, software
         * distributed under the License is distributed on an "AS IS" BASIS,
         * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
         * See the License for the specific language governing permissions and
         * limitations under the License.
         */

        out.write('\n');
        out.write('\n');
        out.write('\n');
        out.write('\n');
        out.write('\n');

        /*
         * Copyright 2005 The Apache Software Foundation.
         *
         * Licensed under the Apache License, Version 2.0 (the "License");
         * you may not use this file except in compliance with the License.
         * You may obtain a copy of the License at
         *
         *      http://www.apache.org/licenses/LICENSE-2.0
         *
         * Unless required by applicable law or agreed to in writing, software
         * distributed under the License is distributed on an "AS IS" BASIS,
         * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
         * See the License for the specific language governing permissions and
         * limitations under the License.
         */

        out.write('\n');
        out.write('\n');
        out.write('\n');
        out.write('\n');

        // initialize a private HttpServletRequest
        setRequest(request);

        // set a resouce base
        setResouceBase("i18n");

        out.write("\n");
        out.write("\n");
        out.write("<head>\n");
        out.write("<title>");
        out.print(getMessage("pageTitle"));
        out.write("</title>\n");
        out.write("</head>\n");
        out.write("<body bgcolor='#ffffff'>\n");
        out.write("\n");

        out.print("<h1>" + getMessage("pageTitle") + "</h1>");
        out.print("<h2>" + getMessage("pageRole") + "</h2><p/>");

        out.write('\n');
        out.write('\n');
        out.print(getLocaleChoice());
        out.write('\n');
        out.write('\n');

        out.print("<h3>" + getMessage("neededComponents") + "</h3>");

        out.write("\n");
        out.write("\n");
        out.write("<UL>\n");

        int needed = 0, wanted = 0;

        /**
         * the essentials, without these Axis is not going to work
         */

        // need to check if the available version of SAAJ API meets requirements
        String className = "javax.xml.soap.SOAPPart";
        String interfaceName = "org.w3c.dom.Document";
        Class clazz = classExists(className);
        if (clazz == null || implementsInterface(clazz, interfaceName)) {
            needed = needClass(out, "javax.xml.soap.SOAPMessage", "saaj.jar", "SAAJ API",
                    getMessage("criticalErrorMessage"), "http://ws.apache.org/axis/");
        } else {
            String location = getLocation(out, clazz);

            out.print(getMessage("invalidSAAJ", location));
            out.print(getMessage("criticalErrorMessage"));
            out.print(getMessage("seeHomepage", "http://ws.apache.org/axis/java/install.html",
                    getMessage("axisInstallation")));
            out.print("<br>");
        }

        needed += needClass(out, "javax.xml.rpc.Service", "jaxrpc.jar", "JAX-RPC API",
                getMessage("criticalErrorMessage"), "http://ws.apache.org/axis/");

        needed += needClass(out, "org.apache.axis.transport.http.AxisServlet", "axis.jar", "Apache-Axis",
                getMessage("criticalErrorMessage"), "http://ws.apache.org/axis/");

        needed += needClass(out, "org.apache.commons.discovery.Resource", "commons-discovery.jar",
                "Jakarta-Commons Discovery", getMessage("criticalErrorMessage"),
                "http://jakarta.apache.org/commons/discovery/");

        needed += needClass(out, "org.apache.commons.logging.Log", "commons-logging.jar",
                "Jakarta-Commons Logging", getMessage("criticalErrorMessage"),
                "http://jakarta.apache.org/commons/logging/");

        needed += needClass(out, "org.apache.log4j.Layout", "log4j-1.2.8.jar", "Log4j",
                getMessage("uncertainErrorMessage"), "http://jakarta.apache.org/log4j");

        //should we search for a javax.wsdl file here, to hint that it needs
        //to go into an approved directory? because we dont seem to need to do that.
        needed += needClass(out, "com.ibm.wsdl.factory.WSDLFactoryImpl", "wsdl4j.jar", "IBM's WSDL4Java",
                getMessage("criticalErrorMessage"), null);

        needed += needClass(out, "javax.xml.parsers.SAXParserFactory", "xerces.jar", "JAXP implementation",
                getMessage("criticalErrorMessage"), "http://xml.apache.org/xerces-j/");

        needed += needClass(out, "javax.activation.DataHandler", "activation.jar", "Activation API",
                getMessage("criticalErrorMessage"), "http://java.sun.com/products/javabeans/glasgow/jaf.html");

        out.write("\n");
        out.write("</UL>\n");

        out.print("<h3>" + getMessage("optionalComponents") + "</h3>");

        out.write("\n");
        out.write("<UL>\n");

        /*
         * now the stuff we can live without
         */
        wanted += wantClass(out, "javax.mail.internet.MimeMessage", "mail.jar", "Mail API",
                getMessage("attachmentsError"), "http://java.sun.com/products/javamail/");

        wanted += wantClass(out, "org.apache.xml.security.Init", "xmlsec.jar", "XML Security API",
                getMessage("xmlSecurityError"), "http://xml.apache.org/security/");

        wanted += wantClass(out, "javax.net.ssl.SSLSocketFactory", "jsse.jar or java1.4+ runtime",
                "Java Secure Socket Extension", getMessage("httpsError"), "http://java.sun.com/products/jsse/");
        /*
         * resources on the classpath path
         */
        /* add more libraries here */

        out.write("\n");
        out.write("</UL>\n");

        out.write("<h3>");
        //is everythng we need here
        if (needed == 0) {
            //yes, be happy
            out.write(getMessage("happyResult00"));
        } else {
            //no, be very unhappy
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write(getMessage("unhappyResult00", Integer.toString(needed)));
        }
        //now look at wanted stuff
        if (wanted > 0) {
            out.write(getMessage("unhappyResult01", Integer.toString(wanted)));
        } else {
            out.write(getMessage("happyResult01"));
        }
        out.write("</h3>");

        out.write("\n");
        out.write("<UL>\n");

        //hint if anything is missing
        if (needed > 0 || wanted > 0) {
            out.write(getMessage("hintString"));
        }

        out.write(getMessage("noteString"));

        out.write("\n");
        out.write("</UL>\n");
        out.write("\n");
        out.write("    <h2>");
        out.print(getMessage("apsExamining"));
        out.write("</h2>\n");
        out.write("\n");
        out.write("<UL>\n");
        out.write("    ");

        String servletVersion = getServletVersion();
        String xmlParser = getParserName();
        String xmlParserLocation = getParserLocation(out);

        out.write("\n");
        out.write("    <table border=\"1\" cellpadding=\"10\">\n");
        out.write("        <tr><td>Servlet version</td><td>");
        out.print(servletVersion);
        out.write("</td></tr>\n");
        out.write("        <tr><td>XML Parser</td><td>");
        out.print(xmlParser);
        out.write("</td></tr>\n");
        out.write("        <tr><td>XML ParserLocation</td><td>");
        out.print(xmlParserLocation);
        out.write("</td></tr>\n");
        out.write("    </table>\n");
        out.write("</UL>\n");
        out.write("\n");
        if (xmlParser.indexOf("crimson") >= 0) {
            out.write("\n");
            out.write("    <p>\n");
            out.write("    ");
            out.print(getMessage("recommendedParser"));
            out.write("\n");
            out.write("    </p>\n");
        }
        out.write("\n");
        out.write("\n");
        out.write("    <h2>");
        out.print(getMessage("sysExamining"));
        out.write("</h2>\n");
        out.write("<UL>\n");

        /**
         * Dump the system properties
         */
        java.util.Enumeration e = null;
        try {
            e = System.getProperties().propertyNames();
        } catch (SecurityException se) {
        }
        if (e != null) {
            out.write("<pre>");
            for (; e.hasMoreElements();) {
                String key = (String) e.nextElement();
                out.write(key + "=" + System.getProperty(key) + "\n");
            }
            out.write("</pre><p>");
        } else {
            out.write(getMessage("sysPropError"));
        }

        out.write("\n");
        out.write("</UL>\n");
        out.write("    <hr>\n");
        out.write("    ");
        out.print(getMessage("apsPlatform"));
        out.write(":\n");
        out.write("    ");
        out.print(getServletConfig().getServletContext().getServerInfo());
        out.write("\n");
        out.write("</body>\n");
        out.write("</html>\n");
    } catch (Throwable t) {
        if (!(t instanceof SkipPageException)) {
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0)
                try {
                    out.clearBuffer();
                } catch (java.io.IOException e) {
                }
            if (_jspx_page_context != null)
                _jspx_page_context.handlePageException(t);
        }
    } finally {
        _jspxFactory.releasePageContext(_jspx_page_context);
    }
}

From source file:org.dspace.app.webui.jsptag.ItemTag.java

/**
 * Render an item in the given style/*  w  w  w .java2s.  c om*/
 */
private void render() throws IOException, SQLException, DCInputsReaderException {
    JspWriter out = pageContext.getOut();
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    Context context = UIUtil.obtainContext(request);
    Locale sessionLocale = UIUtil.getSessionLocale(request);
    String configLine = styleSelection.getConfigurationForStyle(style);

    if (configLine == null) {
        configLine = defaultFields;
    }

    out.println("<center><table class=\"itemDisplayTable\">");

    /*
     * Break down the configuration into fields and display them
     * 
     * FIXME?: it may be more efficient to do some processing once, perhaps
     * to a more efficient intermediate class, but then it would become more
     * difficult to reload the configuration "on the fly".
     */
    StringTokenizer st = new StringTokenizer(configLine, ",");

    while (st.hasMoreTokens()) {
        String field = st.nextToken().trim();
        boolean isDate = false;
        boolean isLink = false;
        boolean isResolver = false;
        boolean isNoBreakLine = false;
        boolean isDisplay = false;

        String style = null;
        Matcher fieldStyleMatcher = fieldStylePatter.matcher(field);
        if (fieldStyleMatcher.matches()) {
            style = fieldStyleMatcher.group(1);
        }

        String browseIndex;
        try {
            browseIndex = getBrowseField(field);
        } catch (BrowseException e) {
            log.error(e);
            browseIndex = null;
        }

        // Find out if the field should rendered with a particular style

        if (style != null) {
            isDate = style.contains("date");
            isLink = style.contains("link");
            isNoBreakLine = style.contains("nobreakline");
            isDisplay = style.equals("inputform");
            isResolver = style.contains("resolver") || urn2baseurl.keySet().contains(style);
            field = field.replaceAll("\\(" + style + "\\)", "");
        }

        // Get the separate schema + element + qualifier

        String[] eq = field.split("\\.");
        String schema = eq[0];
        String element = eq[1];
        String qualifier = null;
        if (eq.length > 2 && eq[2].equals("*")) {
            qualifier = Item.ANY;
        } else if (eq.length > 2) {
            qualifier = eq[2];
        }

        // check for hidden field, even if it's configured..
        if (MetadataExposure.isHidden(context, schema, element, qualifier)) {
            continue;
        }

        // FIXME: Still need to fix for metadata language?
        DCValue[] values = item.getMetadata(schema, element, qualifier, Item.ANY);

        if (values.length > 0) {
            out.print("<tr><td class=\"metadataFieldLabel\">");

            String label = null;
            try {
                label = I18nUtil.getMessage("metadata." + (style != null ? style + "." : "") + field, context);
            } catch (MissingResourceException e) {
                // if there is not a specific translation for the style we
                // use the default one
                label = LocaleSupport.getLocalizedMessage(pageContext, "metadata." + field);
            }

            out.print(label);
            out.print(":&nbsp;</td><td class=\"metadataFieldValue\">");

            //If the values are in controlled vocabulary and the display value should be shown
            if (isDisplay) {
                List<String> displayValues = new ArrayList<String>();

                displayValues = Util.getControlledVocabulariesDisplayValueLocalized(item, values, schema,
                        element, qualifier, sessionLocale);

                if (displayValues != null && !displayValues.isEmpty()) {
                    for (int d = 0; d < displayValues.size(); d++) {
                        out.print(displayValues.get(d));
                        if (d < displayValues.size() - 1)
                            out.print(" <br/>");

                    }
                }
                out.print("</td>");
                continue;
            }
            for (int j = 0; j < values.length; j++) {
                if (values[j] != null && values[j].value != null) {
                    if (j > 0) {
                        if (isNoBreakLine) {
                            String separator = ConfigurationManager
                                    .getProperty("webui.itemdisplay.nobreakline.separator");
                            if (separator == null) {
                                separator = ";&nbsp;";
                            }
                            out.print(separator);
                        } else {
                            out.print("<br />");
                        }
                    }

                    if (isLink) {
                        out.print("<a href=\"" + values[j].value + "\">" + Utils.addEntities(values[j].value)
                                + "</a>");
                    } else if (isDate) {
                        DCDate dd = new DCDate(values[j].value);

                        // Parse the date
                        out.print(UIUtil.displayDate(dd, false, false,
                                (HttpServletRequest) pageContext.getRequest()));
                    } else if (isResolver) {
                        String value = values[j].value;
                        if (value.startsWith("http://") || value.startsWith("https://")
                                || value.startsWith("ftp://") || value.startsWith("ftps://")) {
                            // Already a URL, print as if it was a regular link
                            out.print("<a href=\"" + value + "\">" + Utils.addEntities(value) + "</a>");
                        } else {
                            String foundUrn = null;
                            if (!style.equals("resolver")) {
                                foundUrn = style;
                            } else {
                                for (String checkUrn : urn2baseurl.keySet()) {
                                    if (value.startsWith(checkUrn)) {
                                        foundUrn = checkUrn;
                                    }
                                }
                            }

                            if (foundUrn != null) {

                                if (value.startsWith(foundUrn + ":")) {
                                    value = value.substring(foundUrn.length() + 1);
                                }

                                String url = urn2baseurl.get(foundUrn);
                                out.print("<a href=\"" + url + value + "\">"
                                        + Utils.addEntities(values[j].value) + "</a>");
                            } else {
                                out.print(value);
                            }
                        }

                    } else if (browseIndex != null) {
                        String argument, value;
                        if (values[j].authority != null && values[j].confidence >= MetadataAuthorityManager
                                .getManager()
                                .getMinConfidence(values[j].schema, values[j].element, values[j].qualifier)) {
                            argument = "authority";
                            value = values[j].authority;
                        } else {
                            argument = "value";
                            value = values[j].value;
                        }
                        out.print("<a class=\"" + ("authority".equals(argument) ? "authority " : "")
                                + browseIndex + "\"" + "href=\"" + request.getContextPath() + "/browse?type="
                                + browseIndex + "&amp;" + argument + "=" + URLEncoder.encode(value, "UTF-8")
                                + "\">" + Utils.addEntities(values[j].value) + "</a>");
                    } else {
                        out.print(Utils.addEntities(values[j].value));
                    }
                }
            }

            out.println("</td></tr>");
        }
    }

    listCollections();

    out.println("</table></center><br/>");

    listBitstreams();

    if (ConfigurationManager.getBooleanProperty("webui.licence_bundle.show"))

    {
        out.println("<br/><br/>");
        showLicence();
    }
}

From source file:org.opencms.setup.CmsSetupBean.java

/**
 * Generates the output for step 8b of the setup wizard.<p>
 * /*  w ww. j  ava 2s .com*/
 * @param out the JSP print stream
 * @throws IOException in case errors occur while writing to "out"
 */
public void prepareStep8bOutput(JspWriter out) throws IOException {

    if ((m_workplaceImportThread == null) || (m_workplaceImportThread.getLoggingThread() == null)) {
        return;
    }
    m_oldLoggingOffset = m_newLoggingOffset;
    m_newLoggingOffset = m_workplaceImportThread.getLoggingThread().getMessages().size();
    if (isInitialized()) {
        for (int i = m_oldLoggingOffset; i < m_newLoggingOffset; i++) {
            String str = m_workplaceImportThread.getLoggingThread().getMessages().get(i).toString();
            str = CmsEncoder.escapeWBlanks(str, CmsEncoder.ENCODING_UTF_8);
            out.println("output[" + (i - m_oldLoggingOffset) + "] = \"" + str + "\";");
        }
    } else {
        out.println("output[0] = 'ERROR';");
    }

    boolean threadFinished = m_workplaceImportThread.isFinished();
    boolean allWritten = m_oldLoggingOffset >= m_workplaceImportThread.getLoggingThread().getMessages().size();

    out.println("function initThread() {");
    if (isInitialized()) {
        out.print("send();");
        if (threadFinished && allWritten) {
            out.println("setTimeout('top.display.finish()', 1000);");
        } else {
            int timeout = 5000;
            if (getWorkplaceImportThread().getLoggingThread().getMessages().size() < 20) {
                timeout = 2000;
            }
            out.println("setTimeout('location.reload()', " + timeout + ");");
        }
    }
    out.println("}");
}

From source file:org.apache.jsp.jsp.SchedulerAdmin_jsp.java

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

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;

    try {// w  w  w .j a  v a2  s  . c om
        response.setContentType("text/html");
        pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
        _jspx_page_context = pageContext;
        application = pageContext.getServletContext();
        config = pageContext.getServletConfig();
        session = pageContext.getSession();
        out = pageContext.getOut();
        _jspx_out = out;

        out.write('\r');
        out.write('\n');

        /*
        * Copyright 2006 Pentaho Corporation.  All rights reserved. 
        * This software was developed by Pentaho Corporation and is provided under the terms 
        * of the Mozilla Public License, Version 1.1, or any later version. You may not use 
        * this file except in compliance with the license. If you need a copy of the license, 
        * please go to http://www.mozilla.org/MPL/MPL-1.1.txt. The Original Code is the Pentaho 
        * BI Platform.  The Initial Developer is Pentaho Corporation.
        *
        * Software distributed under the Mozilla Public License is distributed on an "AS IS" 
        * basis, WITHOUT WARRANTY OF ANY KIND, either express or  implied. Please refer to 
        * the license for the specific language governing your rights and limitations.
        */
        response.setCharacterEncoding(LocaleHelper.getSystemEncoding());
        String baseUrl = PentahoSystem.getApplicationContext().getBaseUrl();

        IPentahoSession userSession = PentahoHttpSessionHelper.getPentahoSession(request);
        HttpRequestParameterProvider requestParameters = new HttpRequestParameterProvider(request);
        HttpSessionParameterProvider sessionParameters = new HttpSessionParameterProvider(userSession);
        String thisUrl = baseUrl + "./SchedulerAdmin?"; //$NON-NLS-1$

        String mimeType = request.getParameter("requestedMimeType");
        if (StringUtils.isEmpty(mimeType)) {
            mimeType = "text/html";
        }

        SimpleUrlFactory urlFactory = new SimpleUrlFactory(thisUrl);
        ArrayList messages = new ArrayList();

        SchedulerAdminUIComponent admin = new SchedulerAdminUIComponent(urlFactory, messages); //$NON-NLS-1$

        admin.validate(userSession, null);

        admin.setParameterProvider(HttpRequestParameterProvider.SCOPE_REQUEST, requestParameters); //$NON-NLS-1$
        admin.setParameterProvider(HttpSessionParameterProvider.SCOPE_SESSION, sessionParameters); //$NON-NLS-1$

        String content = admin.getContent(mimeType);
        if ("text/html".equals(mimeType)) {
            if (content == null) {
                StringBuffer buffer = new StringBuffer();
                PentahoSystem.get(IMessageFormatter.class, userSession).formatErrorMessage("text/html", //$NON-NLS-1$
                        Messages.getErrorString("SCHEDULER_ADMIN.ERROR_0001_DISPLAY_ERROR"), messages, buffer); //$NON-NLS-1$
                content = buffer.toString();
            }

            String intro = "";
            String footer = "";
            IUITemplater templater = PentahoSystem.get(IUITemplater.class, userSession);
            if (templater != null) {
                String sections[] = templater.breakTemplate("template.html", "", userSession); //$NON-NLS-1$ //$NON-NLS-2$
                if (sections != null && sections.length > 0) {
                    intro = sections[0];
                }
                if (sections != null && sections.length > 1) {
                    footer = sections[1];
                }
            } else {
                intro = Messages.getString("UI.ERROR_0002_BAD_TEMPLATE_OBJECT");
            }

            // Content had $ signs - the regex stuff messes up with $ and \ so...
            content = content.replaceAll("\\\\", "\\\\\\\\");
            content = content.replaceAll("\\$", "\\\\\\$");

            out.print(intro);
            out.write("\r\n");
            out.write("\t\t");
            out.print(content);
            out.write("\r\n");
            out.write("\t\t");
            out.print(footer);

        } else {
            if (content == null) {
                content = "<error msg='" + Messages.getErrorString("SCHEDULER_ADMIN.ERROR_0001_DISPLAY_ERROR")
                        + "'></error>";
            }

            out.print(content);

        }

    } catch (java.lang.Throwable t) {
        if (!(t instanceof javax.servlet.jsp.SkipPageException)) {
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0)
                try {
                    out.clearBuffer();
                } catch (java.io.IOException e) {
                }
            if (_jspx_page_context != null)
                _jspx_page_context.handlePageException(t);
            else
                throw new ServletException(t);
        }
    } finally {
        _jspxFactory.releasePageContext(_jspx_page_context);
    }
}

From source file:jp.terasoluna.fw.web.struts.taglib.PageLinksTag.java

/**
 * HTML`?o?B/*from w ww .  j a v a  2  s  . com*/
 * 
 * @param row \?s?
 * @param startIndex \JnCfbNX
 * @param totalCount S??
 * @throws JspException JSPO
 */
protected void defineHtml(int row, int startIndex, int totalCount) throws JspException {

    JspWriter writer = pageContext.getOut();
    try {

        //OHidden^O?o?AtOm?B
        if (!getPageContextFlg(pageContext, PAGELINKS_JAVASCRIPT_KEY + rowProperty)) {

            //\??Hidden^O
            writer.println("<input type=\"hidden\" name=\"" + rowProperty + "\" value=\"" + row + "\"/>");

            //?otO?B
            setPageContextFlg(pageContext, PAGELINKS_JAVASCRIPT_KEY + rowProperty);
        }

        //OHidden^O?o?AtOm?B
        if (!getPageContextFlg(pageContext, PAGELINKS_JAVASCRIPT_KEY + indexProperty)) {

            //\JnCfbNXHidden^O
            writer.println(
                    "<input type=\"hidden\" name=\"" + indexProperty + "\" value=\"" + startIndex + "\"/>");

            //?otO?B
            setPageContextFlg(pageContext, PAGELINKS_JAVASCRIPT_KEY + indexProperty);
        }

        //OHidden^O?o?AtOm?B
        if (!getPageContextFlg(pageContext, PAGELINKS_JAVASCRIPT_KEY + event) && forward) {

            //\JnCfbNXHidden^O
            writer.println("<input type=\"hidden\" name=\"" + event + "\" value=\"\"/>");

            //?otO?B
            setPageContextFlg(pageContext, PAGELINKS_JAVASCRIPT_KEY + event);
        }

        //OHidden^O?o?AtOm?B
        if (!getPageContextFlg(pageContext, PAGELINKS_JAVASCRIPT_KEY + "resetIndex") && resetIndex) {

            //startIndexHidden^O
            if (!"startIndex".equals(indexProperty)) {
                writer.println(
                        "<input type=\"hidden\" name=\"" + "startIndex\" value=\"" + startIndex + "\"/>");
            }

            //endIndexHidden^O
            int endIndex = startIndex + row - 1;
            if (endIndex >= totalCount) {
                writer.println(
                        "<input type=\"hidden\" name=\"" + "endIndex\" value=\"" + (totalCount - 1) + "\"/>");
            } else {
                writer.println("<input type=\"hidden\" name=\"" + "endIndex\" value=\"" + endIndex + "\"/>");
            }

            //?otO?B
            setPageContextFlg(pageContext, PAGELINKS_JAVASCRIPT_KEY + "resetIndex");
        }

        //tH?[
        String formName = ActionFormUtil.getActionFormName((HttpServletRequest) pageContext.getRequest());

        //Tu~bg?sJavaScript?B
        //?Ay?[WN^O?L?q??P
        if (!getPageContextFlg(pageContext, PAGELINKS_JAVASCRIPT_KEY)) {
            writer.println("<script type=\"text/javascript\">");
            writer.println("<!--");
            writer.println("  function pageLinkSubmit(rowObj, indexObj," + " row, startIndex){");
            writer.println("    rowObj.value = row;");
            writer.println("    indexObj.value = startIndex;");

            //forward?true???Aevent?Hidden^O
            //p??[^??B
            if (forward) {
                writer.print("    document.");
                writer.print(formName);
                writer.print(".");
                writer.print(event);
                writer.print(".value = \"");
                writer.print(FORWARD_NAME);
                writer.println("\";");
            }

            writer.print("    document.");
            writer.print(formName);
            writer.println(".submit();");
            writer.println("  }");
            writer.println("// -->");
            writer.println("</script>");

            //?otO?B
            setPageContextFlg(pageContext, PAGELINKS_JAVASCRIPT_KEY);
        }

    } catch (IOException e) {
        log.error(e.getMessage());
        throw new JspTagException(e.toString());
    }
}

From source file:gov.nih.nci.ispy.web.taglib.CorrScatterPlotTag.java

public int doStartTag() {
    chart = null;/* ww  w  .  j  a  va 2  s .  co  m*/
    plotPoints.clear();

    ServletRequest request = pageContext.getRequest();
    HttpSession session = pageContext.getSession();
    Object o = request.getAttribute(beanName);
    JspWriter out = pageContext.getOut();
    ServletResponse response = pageContext.getResponse();

    try {
        //retrieve the Finding from cache and build the list of PCAData points
        ISPYCorrelationFinding corrFinding = (ISPYCorrelationFinding) businessTierCache
                .getSessionFinding(session.getId(), taskId);

        Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>();
        List<String> sampleIds = new ArrayList<String>();

        List<DataPoint> points = corrFinding.getDataPoints();

        ClinicalDataService cqs = ClinicalDataServiceFactory.getInstance();
        IdMapperFileBasedService idMapper = IdMapperFileBasedService.getInstance();

        List<ISPYPlotPoint> plotPoints = new ArrayList<ISPYPlotPoint>();
        ISPYPlotPoint pp;
        SampleInfo si;
        ISPYclinicalDataQueryDTO dto;
        Set<String> sampleHolder = new HashSet<String>(); //set just holds one entry need this for the dto
        Set<PatientData> dataHolder = new HashSet<PatientData>();
        PatientData pd = null;
        for (DataPoint p : points) {
            pp = new ISPYPlotPoint(p.getId());
            pp.setX(p.getX());
            pp.setY(p.getY());
            pp.setZ(p.getZ());

            String patientId = null;

            if (corrFinding.isSampleBased()) {
                si = idMapper.getSampleInfoForLabtrackId(p.getId());
                if (si != null) {
                    pp.setSampleInfo(si);
                    patientId = si.getISPYId();
                } else {
                    logger.warn("Could not get sample info for DataPoint=" + p.getId());
                }
            } else if (corrFinding.isPatientBased()) {
                patientId = p.getId();
            }

            if (patientId != null) {
                dto = new ISPYclinicalDataQueryDTO();
                sampleHolder.clear();
                sampleHolder.add(patientId);
                dto.setRestrainingSamples(sampleHolder);
                dataHolder.clear();
                dataHolder = cqs.getClinicalData(dto);

                if (dataHolder.size() == 1) {
                    Iterator i = dataHolder.iterator();
                    pd = (PatientData) i.next();
                    pp.setPatientData(pd);
                } else {
                    logger.error("Internal Error. Did not get back correct patient data for  patientId="
                            + patientId);
                }
            }

            plotPoints.add(pp);
        }

        ISPYCorrelationScatterPlot plot = new ISPYCorrelationScatterPlot(plotPoints,
                corrFinding.getGroup1Name(), corrFinding.getGroup2Name(), corrFinding.getContinuousType1(),
                corrFinding.getContinuousType2(), corrFinding.getCorrelationValue(),
                ColorByType.valueOf(ColorByType.class, colorBy.toUpperCase()));
        chart = plot.getChart();
        ISPYImageFileHandler imageHandler = new ISPYImageFileHandler(session.getId(), "png", 650, 600);
        //The final complete path to be used by the webapplication
        String finalPath = imageHandler.getSessionTempFolder();
        String finalURLpath = imageHandler.getFinalURLPath();
        /*
         * Create the actual charts, writing it to the session temp folder
        */
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        String mapName = imageHandler.createUniqueMapName();
        //PrintWriter writer = new PrintWriter(new FileWriter(mapName));
        ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 650, 600, info);
        //ImageMapUtil.writeBoundingRectImageMap(writer,"PCAimageMap",info,true);
        //writer.close();

        /*   This is here to put the thread into a loop while it waits for the
         *   image to be available.  It has an unsophisticated timer but at 
         *   least it is something to avoid an endless loop.
         **/
        boolean imageReady = false;
        int timeout = 1000;
        FileInputStream inputStream = null;
        while (!imageReady) {
            timeout--;
            try {
                inputStream = new FileInputStream(finalPath);
                inputStream.available();
                imageReady = true;
                inputStream.close();
            } catch (IOException ioe) {
                imageReady = false;
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            if (timeout <= 1) {

                break;
            }
        }

        out.print(ImageMapUtil.getBoundingRectImageMapTag(mapName, true, info));
        finalURLpath = finalURLpath.replace("\\", "/");
        long randomness = System.currentTimeMillis(); //prevent image caching
        out.print("<img id=\"geneChart\" name=\"geneChart\" src=\"" + finalURLpath + "?" + randomness
                + "\" usemap=\"#" + mapName + "\" border=\"0\" />");

        //(imageHandler.getImageTag(mapFileName));

    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        logger.error(sw.toString());
    } catch (Throwable t) {
        logger.error(t);
    }

    return EVAL_BODY_INCLUDE;
}

From source file:com.redhat.rhn.frontend.taglibs.ListDisplayTag.java

/** {@inheritDoc} */
@Override//from  w  ww. j  a  v  a 2  s. com
public int doEndTag() throws JspException {
    JspWriter out = null;
    try {
        if (getPageList().isEmpty()) {
            return EVAL_PAGE;
        }

        if (isExport()) {
            ExportWriter eh = createExportWriter();
            String[] columns = StringUtils.split(this.getExportColumns(), ',');
            eh.setColumns(Arrays.asList(columns));
            ServletExportHandler seh = new ServletExportHandler(eh);
            pageContext.getOut().clear();
            pageContext.getOut().clearBuffer();
            pageContext.getResponse().reset();
            seh.writeExporterToOutput((HttpServletResponse) pageContext.getResponse(), getPageList());
            return SKIP_PAGE;
        }

        // Get the JSPWriter that the body used, then pop the
        // bodyContent, so that we can get the real JspWriter with getOut.
        BodyContent body = getBodyContent();
        pageContext.popBody();
        out = pageContext.getOut();

        if (body != null) {
            String bodyString = body.getString();
            // The toReplace string is kind of odd, but it is because
            // HtmlTag doesn't understand adding a property to be replaced.
            if (numItemsChecked == getPageList().size()) {
                bodyString = bodyString.replaceFirst("@@CHECKED@@=\"\"", "checked=\"1\"");
            } else {
                bodyString = bodyString.replaceFirst("@@CHECKED@@=\"\"", "");
            }
            out.println(bodyString);
        }
        out.println("</tbody>");

        out.println("</table>");

        /* If the type is a half-table, we must draw an extra row on the
         * end of the table if the reflink has been set
         */
        out.println("<div class=\"panel-footer\">");
        out.println("<div class=\"spacewalk-list-footer-addons\">");
        out.println("<div class=\"spacewalk-list-footer-addons-extra\">");
        renderSetButtons(out);
        out.println("</div>");
        out.println("<div class=\"spacewalk-list-reflinks\">");
        if (reflink != null) {
            setColumnCount(0);
            out.println("<a href=\"" + reflink + "\" >");

            /*
             * Here we render the reflink and its key. If the key hasn't
             * been set we just display the link address itself.
             */
            if (reflinkkey != null) {
                Object[] args = new Object[2];

                args[0] = new Integer(getPageList().getTotalSize());
                args[1] = reflinkkeyarg0;

                String message = LocalizationService.getInstance().getMessage(reflinkkey, args);
                out.println(message);
            } else {
                out.println(reflink);
            }

            out.println("</a>");
        }
        out.println("</div>");
        out.println("</div>");

        // close footer
        out.println("</div>");

        // close panel
        out.println("</div>");

        out.println("<div class=\"spacewalk-list-bottom-addons\">");
        out.println("<div class=\"spacewalk-list-pagination\">");
        /* If paging is on, we render the pagination */
        if (isPaging()) {
            renderPagination(out, false);
        }
        /* If paging is off and we are rendering a normal list,
         * we show a count of the results in the lower left corner
         * of the list
         */
        else if (type.equals("list")) {

            int finalResult = getPageList().getEnd();
            if (finalResult > getPageList().getTotalSize()) {
                finalResult = getPageList().getTotalSize();
            }

            Object[] args = new Object[4];
            args[0] = new Integer(getPageList().getStart());
            args[1] = new Integer(finalResult);
            args[2] = new Integer(getPageList().getTotalSize());
            args[3] = LocalizationService.getInstance().getMessage(description);

            out.print("<span class=\"text-right\">\n");
            out.print(LocalizationService.getInstance().getMessage("message.range.withtypedescription", args));
            out.println("</span>");
        }
        out.println("</div>");
        if (isPaging()) {
            out.print("<div class=\"row-0\">\n");
            renderActionButtons(out);
            out.println("</div>");
        }
        out.println("</div>");

        // close list
        out.println("</div>");

        // export button goes outside of the list because in the new
        // implementation it is data-set dependent and not list dependent
        if (getExportColumns() != null) {
            renderExport(out);
        }

        setColumnCount(0);
        setNumberOfColumns(0);
    } catch (IOException e) {
        throw new JspException("IO error" + e.getMessage());
    } finally {
        pageContext.setAttribute("current", null);
    }

    return EVAL_PAGE;
}

From source file:org.apache.jsp.registration_jsp.java

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

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;

    try {//ww w.j a  va 2s  .  co m
        response.setContentType("text/html");
        pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
        _jspx_page_context = pageContext;
        application = pageContext.getServletContext();
        config = pageContext.getServletConfig();
        session = pageContext.getSession();
        out = pageContext.getOut();
        _jspx_out = out;

        /**
        * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
        *
        * WSO2 Inc. licenses this file to you under the Apache License,
        * Version 2.0 (the "License"); you may not use this file except
        * in compliance with the License.
        * You may obtain a copy of the License at
        *
        * http://www.apache.org/licenses/LICENSE-2.0
        *
        * Unless required by applicable law or agreed to in writing,
        * software distributed under the License is distributed on an
        * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
        * KIND, either express or implied. See the License for the
        * specific language governing permissions and limitations
        * under the License.
        */
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");

        String forwardTo;
        try {

            UserRegistrationAdminServiceClient registrationClient = new UserRegistrationAdminServiceClient();
            boolean isExistingUser = registrationClient.isUserExist(request.getParameter("reg_username"));

            if (StringUtils.equals(request.getParameter("is_validation"), "true")) {
                if (isExistingUser) {
                    out.write("User Exist");
                } else {
                    out.write("Ok");
                }
                return;
            }

            if (isExistingUser) {
                throw new Exception("User exist");
            }

            List<UserFieldDTO> fields = (List<UserFieldDTO>) session.getAttribute("fields");

            for (UserFieldDTO userFieldDTO : fields) {
                userFieldDTO.setFieldValue(request.getParameter(userFieldDTO.getFieldName()));
            }

            String username = request.getParameter("reg_username");
            char[] password = request.getParameter("reg_password").toCharArray();
            registrationClient.addUser(username, password, fields);

            forwardTo = "../dashboard/index.jag";

        } catch (Exception e) {
            String error = "An internal error occurred.";
            response.sendRedirect("create-account.jsp?sessionDataKey=" + request.getParameter("sessionDataKey")
                    + "&failedPrevious=true&errorCode=" + error);
            return;
        }

        out.write("\n");
        out.write("<html>\n");
        out.write("<head>\n");
        out.write("    <link href=\"libs/bootstrap_3.3.5/css/bootstrap.min.css\" rel=\"stylesheet\">\n");
        out.write("    <link href=\"css/Roboto.css\" rel=\"stylesheet\">\n");
        out.write("    <link href=\"css/custom-common.css\" rel=\"stylesheet\">\n");
        out.write("</head>\n");
        out.write("<body>\n");
        out.write("<div class=\"container\">\n");
        out.write("    <div id=\"infoModel\" class=\"modal fade\" role=\"dialog\">\n");
        out.write("        <div class=\"modal-dialog\">\n");
        out.write("            <div class=\"modal-content\">\n");
        out.write("                <div class=\"modal-header\">\n");
        out.write(
                "                    <button type=\"button\" class=\"close\" data-dismiss=\"modal\">&times;</button>\n");
        out.write("                    <h4 class=\"modal-title\">Information</h4>\n");
        out.write("                </div>\n");
        out.write("                <div class=\"modal-body\">\n");
        out.write("                    <p>User details successfully submitted</p>\n");
        out.write("                </div>\n");
        out.write("                <div class=\"modal-footer\">\n");
        out.write(
                "                    <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n");
        out.write("                </div>\n");
        out.write("            </div>\n");
        out.write("        </div>\n");
        out.write("    </div>\n");
        out.write("</div>\n");
        out.write("<script src=\"libs/jquery_1.11.3/jquery-1.11.3.js\"></script>\n");
        out.write("<script src=\"libs/bootstrap_3.3.5/js/bootstrap.min.js\"></script>\n");
        out.write("<script type=\"application/javascript\" >\n");
        out.write("    $(document).ready(function () {\n");
        out.write("        var infoModel = $(\"#infoModel\");\n");
        out.write("        infoModel.modal(\"show\");\n");
        out.write("        infoModel.on('hidden.bs.modal', function() {\n");
        out.write("            location.href = \"");
        out.print(Encode.forJavaScriptBlock(forwardTo));
        out.write("\";\n");
        out.write("        })\n");
        out.write("    });\n");
        out.write("</script>\n");
        out.write("</body>\n");
        out.write("</html>");
    } catch (java.lang.Throwable t) {
        if (!(t instanceof javax.servlet.jsp.SkipPageException)) {
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0)
                try {
                    if (response.isCommitted()) {
                        out.flush();
                    } else {
                        out.clearBuffer();
                    }
                } catch (java.io.IOException e) {
                }
            if (_jspx_page_context != null)
                _jspx_page_context.handlePageException(t);
            else
                throw new ServletException(t);
        }
    } finally {
        _jspxFactory.releasePageContext(_jspx_page_context);
    }
}