Example usage for org.xml.sax ContentHandler endElement

List of usage examples for org.xml.sax ContentHandler endElement

Introduction

In this page you can find the example usage for org.xml.sax ContentHandler endElement.

Prototype

public void endElement(String uri, String localName, String qName) throws SAXException;

Source Link

Document

Receive notification of the end of an element.

Usage

From source file:uk.ac.cam.caret.sakai.rwiki.component.service.impl.XSLTEntityHandler.java

/**
 * {@inheritDoc}//from w  w  w .j a va  2 s .  c o  m
 */
public void outputContent(final Entity entity, final Entity sideBar, final HttpServletRequest request,
        final HttpServletResponse res) {
    if (!isAvailable())
        return;
    if (!(entity instanceof RWikiEntity))
        return;

    try {
        String skin = ServerConfigurationService.getString("skin.default"); //$NON-NLS-1$
        String skinRepo = ServerConfigurationService.getString("skin.repo"); //$NON-NLS-1$
        request.setAttribute("sakai.skin.repo", skinRepo); //$NON-NLS-1$
        request.setAttribute("sakai.skin", skin); //$NON-NLS-1$

        HttpSession s = request.getSession();
        PageVisits pageVisits = (PageVisits) s
                .getAttribute(XSLTEntityHandler.class.getName() + this.getMinorType() + "_visits");

        boolean withBreadcrumbs = !"0".equals(request.getParameter(breadCrumbParameter));
        if (pageVisits == null) {
            pageVisits = new PageVisits();
            s.setAttribute(XSLTEntityHandler.class.getName() + this.getMinorType() + "_visits", pageVisits);
        }
        RWikiEntity rwe = (RWikiEntity) entity;
        if (!rwe.isContainer()) {
            RWikiObject rwo = rwe.getRWikiObject();
            pageVisits.addPage(rwo.getName());
        }

        setCurrentRequest(request);

        if (responseHeaders != null) {
            for (Iterator i = responseHeaders.keySet().iterator(); i.hasNext();) {
                String name = (String) i.next();
                String value = (String) responseHeaders.get(name);
                res.setHeader(name, value);

            }

        }

        OutputStream out = res.getOutputStream();

        ContentHandler opch = getOutputHandler(out);
        ContentHandler ch = null;
        if (false) {
            ch = new DebugContentHandler(opch);
        } else {
            ch = opch;
        }

        Attributes dummyAttributes = new AttributesImpl();

        ch.startDocument();
        ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ENTITYSERVICE, SchemaNames.EL_NSENTITYSERVICE,
                dummyAttributes);

        AttributesImpl propA = new AttributesImpl();
        propA.addAttribute("", SchemaNames.ATTR_REQUEST_PATH_INFO, //$NON-NLS-1$
                SchemaNames.ATTR_REQUEST_PATH_INFO, "string", request //$NON-NLS-1$
                        .getPathInfo());
        propA.addAttribute("", SchemaNames.ATTR_REQUEST_USER, //$NON-NLS-1$
                SchemaNames.ATTR_REQUEST_USER, "string", request //$NON-NLS-1$
                        .getRemoteUser());
        propA.addAttribute("", SchemaNames.ATTR_REQUEST_PROTOCOL, //$NON-NLS-1$
                SchemaNames.ATTR_REQUEST_PROTOCOL, "string", request //$NON-NLS-1$
                        .getProtocol());
        propA.addAttribute("", SchemaNames.ATTR_REQUEST_SERVER_NAME, //$NON-NLS-1$
                SchemaNames.ATTR_REQUEST_SERVER_NAME, "string", request //$NON-NLS-1$
                        .getServerName());
        propA.addAttribute("", SchemaNames.ATTR_REQUEST_SERVER_PORT, //$NON-NLS-1$
                SchemaNames.ATTR_REQUEST_SERVER_PORT, "string", String //$NON-NLS-1$
                        .valueOf(request.getServerPort()));
        propA.addAttribute("", SchemaNames.ATTR_REQUEST_REQUEST_URL, //$NON-NLS-1$
                SchemaNames.ATTR_REQUEST_REQUEST_URL, "string", String //$NON-NLS-1$
                        .valueOf(request.getRequestURL()));

        ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_PROPERTIES,
                SchemaNames.EL_NSREQUEST_PROPERTIES, propA);
        addRequestAttributes(ch, request);
        addRequestParameters(ch, request);

        ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_PROPERTIES,
                SchemaNames.EL_NSREQUEST_PROPERTIES);

        if (withBreadcrumbs) {
            ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_PAGEVISITS, SchemaNames.EL_NSPAGEVISITS,
                    dummyAttributes);

            List<String[]> pv = pageVisits.getPageNames(this.getMinorType());

            for (Iterator<String[]> i = pv.iterator(); i.hasNext();) {
                String[] visit = i.next();
                propA = new AttributesImpl();
                propA.addAttribute("", SchemaNames.ATTR_URL, SchemaNames.ATTR_URL, "string", visit[0]);
                addElement(ch, SchemaNames.NS_CONTAINER, SchemaNames.EL_PAGEVISIT, SchemaNames.EL_NSPAGEVISIT,
                        propA, visit[1]);
            }
            ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_PAGEVISITS, SchemaNames.EL_NSPAGEVISITS);
        }

        ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ENTITY, SchemaNames.EL_NSENTITY,
                dummyAttributes);
        ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_XMLPROPERTIES, SchemaNames.EL_NSXMLPROPERTIES,
                dummyAttributes);
        ResourceProperties rp = entity.getProperties();

        for (Iterator i = rp.getPropertyNames(); i.hasNext();) {
            Object key = i.next();
            String name = String.valueOf(key);
            String value = String.valueOf(rp.getProperty(name));
            propA = new AttributesImpl();
            propA.addAttribute("", SchemaNames.ATTR_NAME, //$NON-NLS-1$
                    SchemaNames.ATTR_NAME, "string", name); //$NON-NLS-1$
            addElement(ch, SchemaNames.NS_CONTAINER, SchemaNames.EL_XMLPROPERTY, SchemaNames.EL_NSXMLPROPERTY,
                    propA, value);
        }
        propA = new AttributesImpl();
        propA.addAttribute("", SchemaNames.ATTR_NAME, //$NON-NLS-1$
                SchemaNames.ATTR_NAME, "string", "_handler"); //$NON-NLS-1$ //$NON-NLS-2$
        addElement(ch, SchemaNames.NS_CONTAINER, SchemaNames.EL_XMLPROPERTY, SchemaNames.EL_NSXMLPROPERTY,
                propA, " XSLTEntity Handler"); //$NON-NLS-1$

        if (!rwe.isContainer()) {
            RWikiObject rwo = rwe.getRWikiObject();
            propA = new AttributesImpl();
            propA.addAttribute("", SchemaNames.ATTR_NAME, //$NON-NLS-1$
                    SchemaNames.ATTR_NAME, "string", "_title"); //$NON-NLS-1$ //$NON-NLS-2$
            addElement(ch, SchemaNames.NS_CONTAINER, SchemaNames.EL_XMLPROPERTY, SchemaNames.EL_NSXMLPROPERTY,
                    propA, NameHelper.localizeName(rwo.getName(), rwo.getRealm()));

        } else {
            propA = new AttributesImpl();
            propA.addAttribute("", SchemaNames.ATTR_NAME, //$NON-NLS-1$
                    SchemaNames.ATTR_NAME, "string", "_title"); //$NON-NLS-1$ //$NON-NLS-2$
            addElement(ch, SchemaNames.NS_CONTAINER, SchemaNames.EL_XMLPROPERTY, SchemaNames.EL_NSXMLPROPERTY,
                    propA, entity.getReference());

        }
        ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_XMLPROPERTIES, SchemaNames.EL_NSXMLPROPERTIES);

        /* http://jira.sakaiproject.org/browse/SAK-13281
         * escapeXML is controlled via config settings
         */

        if (!rwe.isContainer()) {
            RWikiObject rwo = rwe.getRWikiObject();
            ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_RENDEREDCONTENT,
                    SchemaNames.EL_NSRENDEREDCONTENT, dummyAttributes);

            renderToXML(rwo, ch, withBreadcrumbs, this.escaped);
            ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_RENDEREDCONTENT,
                    SchemaNames.EL_NSRENDEREDCONTENT);
        }
        ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ENTITY, SchemaNames.EL_NSENTITY);

        if (sideBar != null && sideBar instanceof RWikiEntity) {

            RWikiEntity sbrwe = (RWikiEntity) sideBar;
            RWikiObject sbrwo = sbrwe.getRWikiObject();
            ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_SIDEBAR, SchemaNames.EL_NSSIDEBAR,
                    dummyAttributes);

            ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_XMLPROPERTIES,
                    SchemaNames.EL_NSXMLPROPERTIES, dummyAttributes);
            propA = new AttributesImpl();
            propA.addAttribute("", SchemaNames.ATTR_NAME, //$NON-NLS-1$
                    SchemaNames.ATTR_NAME, "string", "_title"); //$NON-NLS-1$ //$NON-NLS-2$
            addElement(ch, SchemaNames.NS_CONTAINER, SchemaNames.EL_XMLPROPERTY, SchemaNames.EL_NSXMLPROPERTY,
                    propA, NameHelper.localizeName(sbrwo.getName(), sbrwo.getRealm()));
            ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_XMLPROPERTIES,
                    SchemaNames.EL_NSXMLPROPERTIES);

            ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_RENDEREDCONTENT,
                    SchemaNames.EL_NSRENDEREDCONTENT, dummyAttributes);
            renderToXML(sbrwo, ch, withBreadcrumbs, this.escaped);
            ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_RENDEREDCONTENT,
                    SchemaNames.EL_NSRENDEREDCONTENT);

            ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_SIDEBAR, SchemaNames.EL_NSSIDEBAR);

        }

        ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ENTITYSERVICE, SchemaNames.EL_NSENTITYSERVICE);

        ch.endDocument();

    } catch (Throwable ex) {
        log.info("Failed to serialize " + ex.getMessage()); //$NON-NLS-1$
        ex.printStackTrace();
        throw new RuntimeException(Messages.getString("XSLTEntityHandler.68") //$NON-NLS-1$
                + ex.getLocalizedMessage(), ex);
    } finally {
        setCurrentRequest(null);
    }
}

From source file:uk.ac.cam.caret.sakai.rwiki.component.service.impl.XSLTEntityHandler.java

/**
 * Adds an element to the content handler.
 * //  w w  w  .jav  a  2s  . c o  m
 * @param ch
 *        the content handler
 * @param ns
 *        the name space of the element
 * @param lname
 *        the local name
 * @param qname
 *        the qname
 * @param attr
 *        the attribute list
 * @param content
 *        content of the element
 * @throws SAXException
 *         if the underlying sax chain has a problem
 */
public void addElement(final ContentHandler ch, final String ns, final String lname, final String qname,
        final Attributes attr, final Object content) throws SAXException {

    ch.startElement(ns, lname, qname, attr);
    try {
        if (content != null) {
            char[] c = String.valueOf(content).toCharArray();
            ch.characters(c, 0, c.length);
        }
    } finally {
        ch.endElement(ns, lname, qname);
    }
}

From source file:uk.ac.cam.caret.sakai.rwiki.component.service.impl.XSLTEntityHandler.java

/**
 * Serialises the rendered content of the RWiki Object to SAX
 * //from w  w w .jav  a 2  s. c  o m
 * @param rwo
 * @param ch
 * @param withBreadCrumb 
 */
public void renderToXML(RWikiObject rwo, final ContentHandler ch, boolean withBreadCrumb, boolean escapeXML)
        throws SAXException, IOException {

    String renderedPage;
    try {
        renderedPage = render(rwo, withBreadCrumb);
    } catch (Exception e) {
        renderedPage = Messages.getString("XSLTEntityHandler.32") + rwo.getName() //$NON-NLS-1$
                + Messages.getString("XSLTEntityHandler.33") + e.getClass() //$NON-NLS-1$
                + Messages.getString("XSLTEntityHandler.34") + e.getMessage(); //$NON-NLS-1$
        log.info(renderedPage, e);
    }
    String contentDigest = DigestHtml.digest(renderedPage);
    if (contentDigest.length() > 500) {
        contentDigest = contentDigest.substring(0, 500);
    }
    if (renderedPage == null || renderedPage.trim().length() == 0) {
        renderedPage = Messages.getString("XSLTEntityHandler.35"); //$NON-NLS-1$
    }
    if (contentDigest == null || contentDigest.trim().length() == 0) {
        contentDigest = Messages.getString("XSLTEntityHandler.36"); //$NON-NLS-1$
    }

    String cdataEscapedRendered = renderedPage.replaceAll("]]>", "]]>]]&gt;<![CDATA["); //$NON-NLS-1$ //$NON-NLS-2$
    String cdataContentDigest = contentDigest.replaceAll("]]>", "]]>]]&gt;<![CDATA["); //$NON-NLS-1$ //$NON-NLS-2$

    /* http://jira.sakaiproject.org/browse/SAK-13281
     * ensure all page content is escaped or double escaped before it goes into the parser,
     * if this is not done then the parser will unescape html entities during processing
     */
    renderedPage = "<content><rendered>" //$NON-NLS-1$
            + (escapeXML ? StringEscapeUtils.escapeXml(renderedPage) : renderedPage) + "</rendered><rendered-cdata><![CDATA[" + cdataEscapedRendered //$NON-NLS-1$
            + "]]></rendered-cdata><contentdigest><![CDATA[" + cdataContentDigest //$NON-NLS-1$
            + "]]></contentdigest></content>"; //$NON-NLS-1$

    try {
        parseToSAX(renderedPage, ch);
    } catch (SAXException ex) {
        SimpleCoverage.cover("Failed to parse renderedPage from " + rwo.getName()); //$NON-NLS-1$
        Attributes dummyAttributes = new AttributesImpl();
        ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERROR, SchemaNames.EL_NSERROR,
                dummyAttributes);
        ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERRORDESC, SchemaNames.EL_NSERRORDESC,
                dummyAttributes);
        String s = Messages.getString("XSLTEntityHandler.46") //$NON-NLS-1$
                + ex.getMessage();
        ch.characters(s.toCharArray(), 0, s.length());
        ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERRORDESC, SchemaNames.EL_NSERRORDESC);
        ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_RAWCONTENT, SchemaNames.EL_NSRAWCONTENT,
                dummyAttributes);
        ch.characters(renderedPage.toCharArray(), 0, renderedPage.length());
        ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_RAWCONTENT, SchemaNames.EL_NSRAWCONTENT);
        ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERROR, SchemaNames.EL_NSERROR);

    }

    // SimpleCoverage.cover("Failed to parse ::\n" + renderedPage
    // + "\n:: from ::\n" + rwo.getContent());
    // Attributes dummyAttributes = new AttributesImpl();
    // ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERROR,
    // SchemaNames.EL_NSERROR, dummyAttributes);
    // ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERRORDESC,
    // SchemaNames.EL_NSERRORDESC, dummyAttributes);
    // String s = "The Rendered Content did not parse correctly "
    // + ex.getMessage();
    // ch.characters(s.toCharArray(), 0, s.length());
    // ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERRORDESC,
    // SchemaNames.EL_NSERRORDESC);
    // ch.startElement(SchemaNames.NS_CONTAINER,
    // SchemaNames.EL_RAWCONTENT, SchemaNames.EL_NSRAWCONTENT,
    // dummyAttributes);
    // ch.characters(renderedPage.toCharArray(), 0, renderedPage.length());
    // ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_RAWCONTENT,
    // SchemaNames.EL_NSRAWCONTENT);
    // ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERROR,
    // SchemaNames.EL_NSERROR);

}

From source file:uk.ac.cam.caret.sakai.rwiki.component.service.impl.XSLTEntityHandler.java

public void parseToSAX(final String toRender, final ContentHandler ch) throws IOException, SAXException {
    /**/*from  w ww.  j  a  va2s  .  c  o  m*/
     * create a proxy for the stream, filtering out the start element and
     * end element events
     */
    ContentHandler proxy = new ContentHandler() {
        public void setDocumentLocator(Locator arg0) {
            ch.setDocumentLocator(arg0);
        }

        public void startDocument() throws SAXException {
            // ignore
        }

        public void endDocument() throws SAXException {
            // ignore
        }

        public void startPrefixMapping(String arg0, String arg1) throws SAXException {
            ch.startPrefixMapping(arg0, arg1);
        }

        public void endPrefixMapping(String arg0) throws SAXException {
            ch.endPrefixMapping(arg0);
        }

        public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException {
            ch.startElement(arg0, arg1, arg2, arg3);
        }

        public void endElement(String arg0, String arg1, String arg2) throws SAXException {
            ch.endElement(arg0, arg1, arg2);
        }

        public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
            ch.characters(arg0, arg1, arg2);
        }

        public void ignorableWhitespace(char[] arg0, int arg1, int arg2) throws SAXException {
            ch.ignorableWhitespace(arg0, arg1, arg2);
        }

        public void processingInstruction(String arg0, String arg1) throws SAXException {
            ch.processingInstruction(arg0, arg1);
        }

        public void skippedEntity(String arg0) throws SAXException {
            ch.skippedEntity(arg0);
        }

    };
    InputSource ins = new InputSource(new StringReader(toRender));
    XMLReader xmlReader;
    try {
        SAXParser saxParser = saxParserFactory.newSAXParser();

        xmlReader = saxParser.getXMLReader();
    }

    catch (Exception e) {
        log.error("SAXException when creating XMLReader", e); //$NON-NLS-1$
        // rethrow!!
        throw new SAXException(e);
    }
    xmlReader.setContentHandler(proxy);
    xmlReader.parse(ins);
}

From source file:uk.ac.cam.caret.sakai.rwiki.component.service.impl.XSLTEntityHandler.java

public void addRequestAttributes(ContentHandler ch, HttpServletRequest request) throws Exception {
    if (!isAvailable())
        return;//from   w ww  .j av  a 2  s.c  om

    // add the attributes
    AttributesImpl dummyAttributes = new AttributesImpl();
    ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_ATTRIBUTES,
            SchemaNames.EL_NSREQUEST_ATTRIBUTES, dummyAttributes);
    for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        Object attr = request.getAttribute(name);
        AttributesImpl propA = new AttributesImpl();
        propA.addAttribute("", SchemaNames.ATTR_NAME, //$NON-NLS-1$
                SchemaNames.ATTR_NAME, "string", name); //$NON-NLS-1$
        if (attr instanceof Object[]) {
            Object[] oattr = (Object[]) attr;
            ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_ATTRIBUTE,
                    SchemaNames.EL_NSREQUEST_ATTRIBUTE, propA);
            for (int i = 0; i < oattr.length; i++) {
                addElement(ch, SchemaNames.NS_CONTAINER, SchemaNames.EL_VALUE, SchemaNames.EL_NSVALUE,
                        dummyAttributes, oattr[i]);
            }
            ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_ATTRIBUTE,
                    SchemaNames.EL_NSREQUEST_ATTRIBUTE);
        } else {
            ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_ATTRIBUTE,
                    SchemaNames.EL_NSREQUEST_ATTRIBUTE, propA);
            addElement(ch, SchemaNames.NS_CONTAINER, SchemaNames.EL_VALUE, SchemaNames.EL_NSVALUE,
                    dummyAttributes, attr);
            ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_ATTRIBUTE,
                    SchemaNames.EL_NSREQUEST_ATTRIBUTE);
        }
    }

    ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_ATTRIBUTES,
            SchemaNames.EL_NSREQUEST_ATTRIBUTES);
}

From source file:uk.ac.cam.caret.sakai.rwiki.component.service.impl.XSLTEntityHandler.java

public void addRequestParameters(ContentHandler ch, HttpServletRequest request) throws Exception {
    if (!isAvailable())
        return;//from w  w w  .  j a v  a  2 s . c  o m

    AttributesImpl dummyAttributes = new AttributesImpl();

    // add the request parameters
    ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_PARAMS, SchemaNames.EL_NSREQUEST_PARAMS,
            dummyAttributes);
    for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        String[] attr = request.getParameterValues(name);
        AttributesImpl propA = new AttributesImpl();
        propA.addAttribute("", SchemaNames.ATTR_NAME, //$NON-NLS-1$
                SchemaNames.ATTR_NAME, "string", name); //$NON-NLS-1$
        ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_PARAM, SchemaNames.EL_NSREQUEST_PARAM,
                propA);
        for (int i = 0; i < attr.length; i++) {
            addElement(ch, SchemaNames.NS_CONTAINER, SchemaNames.EL_VALUE, SchemaNames.EL_NSVALUE,
                    dummyAttributes, attr[i]);
        }
        ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_PARAM, SchemaNames.EL_NSREQUEST_PARAM);
    }

    ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_PARAMS, SchemaNames.EL_REQUEST_PARAMS);
}

From source file:uk.ac.ebi.arrayexpress.utils.saxon.FlatFileXMLReader.java

public void parse(InputSource input) throws IOException, SAXException {
    int headerRows = getIntOptionValue(OPTION_HEADER_ROWS, 0);
    int page = getIntOptionValue(OPTION_PAGE, 0);
    int pageSize = getIntOptionValue(OPTION_PAGE_SIZE, -1);
    Integer sortBy = getIntOptionValue(OPTION_SORT_BY, null);
    String sortOrder = getStringOptionValue(OPTION_SORT_ORDER, "a");

    ContentHandler ch = getContentHandler();
    if (null == ch) {
        return;//from   w  ww  .j  a v a  2  s.co m
    }

    Reader inStream;
    if (input.getCharacterStream() != null) {
        inStream = input.getCharacterStream();
    } else if (input.getByteStream() != null) {
        inStream = new InputStreamReader(input.getByteStream());
    } else if (input.getSystemId() != null) {
        URL url = new URL(input.getSystemId());
        inStream = new InputStreamReader(url.openStream());
    } else {
        throw new SAXException("Invalid InputSource object");
    }

    CSVReader ffReader = new CSVReader(new BufferedReader(inStream), this.columnDelimiter,
            this.columnQuoteChar);

    List<String[]> ff = ffReader.readAll();
    int cols = ff.size() > 0 ? ff.get(0).length : 0;

    // verify that sort by column is with in range of columns
    // if not then sort will not be performed
    // else - switch from 1-based to 0-based index
    if (null != sortBy) {
        if (sortBy < 1 || sortBy > cols) {
            sortBy = null;
        } else {
            sortBy = sortBy - 1;
        }
    }

    // 1. removes all dodgy rows (that have less columns than the first one)
    // 2. determines if column to be sorted is numeric
    ColDataType sortColDataType = ColDataType.INTEGER;
    int colTypeSkipRows = headerRows;
    for (Iterator<String[]> iterator = ff.iterator(); iterator.hasNext();) {
        String[] row = iterator.next();
        if (row.length != cols || isRowBlank(row)) {
            iterator.remove();
        } else {
            if (null != sortBy && 0 == colTypeSkipRows && ColDataType.STRING != sortColDataType) {
                ColDataType dataType = getColDataType(row[sortBy]);

                // downgrade from int to decimal or string
                if (ColDataType.INTEGER == sortColDataType && ColDataType.INTEGER != dataType) {
                    sortColDataType = dataType;
                }
                // downgrade from decimal to string only
                if (ColDataType.DECIMAL == sortColDataType && ColDataType.STRING == dataType) {
                    sortColDataType = dataType;
                }
            }
            if (colTypeSkipRows > 0) {
                colTypeSkipRows--;
            }
        }
    }

    int rows = ff.size() > 0 ? ff.size() - headerRows : 0;

    if (-1 == pageSize) {
        page = 1;
        pageSize = rows;
    }

    ch.startDocument();

    AttributesImpl tableAttrs = new AttributesImpl();
    tableAttrs.addAttribute(EMPTY_NAMESPACE, "rows", "rows", CDATA_TYPE, String.valueOf(rows));
    ch.startElement(EMPTY_NAMESPACE, "table", "table", tableAttrs);

    for (Iterator<String[]> iterator = ff.iterator(); iterator.hasNext() && headerRows > 0; headerRows--) {
        String[] row = iterator.next();
        outputRow(ch, true, null, row);
        iterator.remove();
    }

    if (null != sortBy) {
        Collections.sort(ff, new SortColumnComparator(sortBy, sortOrder, sortColDataType));
    }

    int rowSeq = 1;
    for (String[] row : ff) {
        if (rowSeq > (pageSize * (page - 1)) && rowSeq <= (pageSize * page)) {
            outputRow(ch, false, String.valueOf(rowSeq), row);
        }
        ++rowSeq;
    }

    ch.endElement(EMPTY_NAMESPACE, "table", "table");
    ch.endDocument();
}

From source file:uk.ac.ebi.arrayexpress.utils.saxon.FlatFileXMLReader.java

private void outputRow(ContentHandler ch, boolean isHeader, String seqValue, String[] rowData)
        throws SAXException {
    String rowElement = isHeader ? "header" : "row";

    AttributesImpl rowAttrs = new AttributesImpl();
    if (null != seqValue) {
        rowAttrs.addAttribute(EMPTY_NAMESPACE, "seq", "seq", CDATA_TYPE, seqValue);
    }//from   www .ja v a  2  s.  co  m
    rowAttrs.addAttribute(EMPTY_NAMESPACE, "cols", "cols", CDATA_TYPE, String.valueOf(rowData.length));
    ch.startElement(EMPTY_NAMESPACE, rowElement, rowElement, rowAttrs);

    for (String col : rowData) {
        if (isHeader) {
            col = StringUtils.trimToEmpty(col);
        }
        ch.startElement(EMPTY_NAMESPACE, "col", "col", EMPTY_ATTR);
        ch.characters(col.toCharArray(), 0, col.length());
        ch.endElement(EMPTY_NAMESPACE, "col", "col");
    }
    ch.endElement(EMPTY_NAMESPACE, rowElement, rowElement);
}