001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.xslcontent.util;
016    
017    import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream;
018    import com.liferay.portal.kernel.io.unsync.UnsyncStringReader;
019    import com.liferay.portal.kernel.util.HttpUtil;
020    
021    import java.io.IOException;
022    
023    import java.net.URL;
024    
025    import javax.xml.transform.Transformer;
026    import javax.xml.transform.TransformerException;
027    import javax.xml.transform.TransformerFactory;
028    import javax.xml.transform.stream.StreamResult;
029    import javax.xml.transform.stream.StreamSource;
030    
031    /**
032     * @author Brian Wing Shun Chan
033     */
034    public class XSLContentUtil {
035    
036            public static final String DEFAULT_XML_URL =
037                    "@portal_url@/html/portlet/xsl_content/example.xml";
038    
039            public static final String DEFAULT_XSL_URL =
040                    "@portal_url@/html/portlet/xsl_content/example.xsl";
041    
042            public static String transform(URL xmlUrl, URL xslUrl)
043                    throws IOException, TransformerException {
044    
045                    String xml = HttpUtil.URLtoString(xmlUrl);
046                    String xsl = HttpUtil.URLtoString(xslUrl);
047    
048                    StreamSource xmlSource = new StreamSource(new UnsyncStringReader(xml));
049                    StreamSource xslSource = new StreamSource(new UnsyncStringReader(xsl));
050    
051                    TransformerFactory transformerFactory =
052                            TransformerFactory.newInstance();
053    
054                    Transformer transformer = transformerFactory.newTransformer(xslSource);
055    
056                    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream =
057                            new UnsyncByteArrayOutputStream();
058    
059                    transformer.transform(
060                            xmlSource, new StreamResult(unsyncByteArrayOutputStream));
061    
062                    return unsyncByteArrayOutputStream.toString();
063            }
064    
065    }