Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * #%L
   * JRst :: Api
   * 
   * $Id: JRST.java 610 2011-08-18 12:24:08Z sletellier $
   * $HeadURL: http://svn.nuiton.org/svn/jrst/tags/jrst-1.4/jrst/src/main/java/org/nuiton/jrst/JRST.java $
   * %%
   * Copyright (C) 2004 - 2011 CodeLutin, Chatellier Eric
   * %%
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU Lesser General Public License as 
  * published by the Free Software Foundation, either version 3 of the 
  * License, or (at your option) any later version.
  * 
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Lesser Public License for more details.
  * 
  * You should have received a copy of the GNU General Lesser Public 
  * License along with this program.  If not, see
  * <http://www.gnu.org/licenses/lgpl-3.0.html>.
  * #L%
  */
 
 package org.nuiton.jrst;
 
 import java.io.*;
 import java.net.URL;
 import java.util.List;
 import java.util.Map;
 
 
FIXME: 'JRST --help' doesn't work, but 'JRST --help toto' work :( FIXME: 'JRST -c' doesn't work, but 'JRST -c toto' Created: 3 nov. 06 20:56:00

Author(s):
poussin
Version:
$Revision: 610 $ Last update: $Date: 2011-08-18 14:24:08 +0200 (Thu, 18 Aug 2011) $ by : $Author: sletellier $
 
 public class JRST {
 
     public static final String UTF_8 = "UTF-8";
 
     public enum Overwrite {
         NEVER, IFNEWER, ALLTIME
     }

    
to use log facility, just put in your code: log.info("...");
 
     protected static Log log = LogFactory.getLog(JRST.class);

    
XSL Stylesheet to transform RST into HTML.
 
     protected static final String rst2xhtml = "/xsl/rst2xhtml.xsl";
    
XSL Stylesheet to transform RST into HTML (but only inner body fragment).
 
     protected static final String rst2xhtmlInnerBody = "/xsl/rst2xhtmlInnerBody.xsl";
    
XSL Stylesheet to transform RST into Xdoc.
 
    protected static final String rst2xdoc = "/xsl/rst2xdoc.xsl";
    
XSL Stylesheet to transform RST into Docbook.
    protected static final String rst2docbook = "/xsl/dn2dbk.xsl";

    
XSL Stylesheet to transform Docbook into xHTML.
    protected static final String docbook2xhtml = "/docbook/xhtml/docbook.xsl";
    
XSL Stylesheet to transform Docbook into javahelp.
    protected static final String docbook2javahelp = "/docbook/javahelp/javahelp.xsl";
    
XSL Stylesheet to transform Docbook into htmlhelp.
    protected static final String docbook2htmlhelp = "/docbook/htmlhelp/htmlhelp.xsl";
    
//    /** XSL Stylesheet to transform xml into rst. */
//    protected static final String rst2rst = "JRSTWriter";

    
XSL Stylesheet to transform Docbook into PDF.
    protected static final String docbook2fo = "/docbook/fo/docbook.xsl";
    public static final String PATTERN_TYPE = "xml|xhtml|docbook|html|htmlInnerBody|xdoc|rst|fo|pdf|odt|rtf";

    
HTML output format type
    public static final String TYPE_HTML = "html";

    
HTML output format type
    public static final String TYPE_HTML_INNER_BODY = "htmlInnerBody";

    
XDOC output format type
    public static final String TYPE_XDOC = "xdoc";

    
DOCBOOK output format type
    public static final String TYPE_DOCBOOK = "docbook";

    
XHTML output format type
    public static final String TYPE_XHTML = "xhtml";

    
JAVA HELP output format type
    public static final String TYPE_JAVAHELP = "javahelp";

    
HTML HELP output format type
    public static final String TYPE_HTMLHELP = "htmlhelp";

    
RST output format type
    public static final String TYPE_RST = "rst";

    
ODT output format type
    public static final String TYPE_ODT = "odt";

    
FO output format type
    public static final String TYPE_FO = "fo";

    
PDF output format type
    public static final String TYPE_PDF = "pdf";

    
key, Out type; value: chain of XSL file to provide wanted file for output
    protected static Map<StringStringstylesheets;
    
Mime type associated with type
    protected static Map<StringStringmimeType;
    static {
         = new HashMap<StringString>();
        .put();
        .put( + "," + );
        .put("");
        //stylesheets.put(TYPE_ODT, rst2docbook + "," + docbook2odf);
        .put( + "," + );
        .put( + "," + );
         = new HashMap<StringString>();
        .put("text/html");
        .put("text/html");
        .put("text/xml");
        .put("text/xml");
        .put("text/html");
        .put("text/plain");
        .put("text/html");
        .put("text/plain");
        .put("application/vnd.oasis.opendocument.text");
        .put("text/xml");
        .put("application/pdf");
    }
    static public String getMimeType(String generationType) {
        String result = .get(generationType);
        if (result == null) {
            result = "application/octet-stream";
        }
        return result;
    }

    
Main method.

Parameters:
args main args
Throws:
java.lang.Exception
    public static void main(String[] argsthrows Exception {
        
        I18n.init(new ClassPathI18nInitializer(), .);
        if (args.length == 0) {
            args = askOption();
        }
        if (args == null) {
            System.exit(0);
        }
        ApplicationConfig config = JRSTConfig.getConfig(args);
        config.doAction(0);
        // parse options
        String xslList = ..getOption(config);
        if (xslList == null) {
            xslList = ..getOption(config);
        }
        List<Stringunparsed = config.getUnparsed();
        if (unparsed.isEmpty()) {
            JRSTConfig.help();
        }
        File inputFile = new File(config.getUnparsed().get(0));
        File ouputFile = ..getOptionAsFile(config);
        Overwrite overwrite = .;
        if (..getOptionAsBoolean(config)) {
            overwrite = .;
        }
        
        generate(xslListinputFileouputFileoverwrite);
    }
    private static String[] askOption() throws SecurityException,
            NoSuchMethodExceptionIOException {
        String[] result = null;
        try {
            GraphicsEnvironment ge = GraphicsEnvironment
                    .getLocalGraphicsEnvironment();
            GraphicsDevice[] gs = ge.getScreenDevices();
            if (!(gs == null)) {
                if (gs.length > 0) {
                    result = askOptionGraph();
                }
            }
        } catch (java.awt.HeadlessException e) {
            result = null;
        }
        return result;
    }

    
    protected static String[] askOptionGraph() throws SecurityException,
            NoSuchMethodException {
        JRSTInterface graph = new JRSTInterface();
        return graph.getCmd();
    }
    public static void generate(String xslListOrOutTypeFile fileIn,
            File fileOutOverwrite overwritethrows Exception {
        generate(xslListOrOutTypefileInfileOutoverwrite);
    }
    public static void generate(String xslListOrOutTypeFile fileInString inputEncoding,
            File fileOutString outputEncodingOverwrite overwritethrows Exception {
        if (fileOut != null
                && fileOut.exists()
                && (overwrite == . || (overwrite == . && FileUtil
                        .isNewer(fileInfileOut)))) {
            // System.err.println("Don't generate file " + fileOut +
            // ", because already exists");
            .info("Don't generate file " + fileOut
                    + ", because already exists");
        } else {
            // In
            URL url = fileIn.toURI().toURL();
            Reader reader = new InputStreamReader(url.openStream(), inputEncoding);
            // Out
            FileOutputStream outputStream = new FileOutputStream(fileOut);
            OutputStreamWriter writer = new OutputStreamWriter(outputStreamoutputEncoding);
            // Generate
            String result = generateString(xslListOrOutTypereader);
            fileOut.getAbsoluteFile().getParentFile().mkdirs();
            // generation PDF
            if (xslListOrOutType.equals("pdf")) {
                FopFactory fopFactory = FopFactory.newInstance();
                // OutputStream outPDF = new BufferedOutputStream(new
                // FileOutputStream(new File("C:/Temp/myfile.pdf")));
                OutputStream outPDF = new BufferedOutputStream(new FileOutputStream(
                        fileOut));
                FOUserAgent userAgent = fopFactory.newFOUserAgent();
                // Step 3: Construct fop with desired output format
                Fop fop = fopFactory.newFop(.,
                        userAgentoutPDF);
                // Step 4: Setup JAXP using identity transformer
                TransformerFactory factory = TransformerFactory
                        .newInstance();
                Transformer transformer = factory.newTransformer(); // identity
                // transformer
                // Step 5: Setup input and output for XSLT transformation
                // Setup input stream
                Source src = new StreamSource(new StringReader(result));
                // Resulting SAX events (the generated FO) must be piped
                // through to FOP
                Result res = new SAXResult(fop.getDefaultHandler());
                // Step 6: Start XSLT transformation and FOP processing
                transformer.transform(srcres);
                outPDF.close();
            } else {
                // write generated document
                writer.write(result);
                writer.close();
            }
        }
    }

    

Parameters:
xslListOrOutType
in
Throws:
java.lang.Exception
    public static String generate(String xslListOrOutTypeString inthrows Exception {
        return generateString(xslListOrOutTypenew StringReader(in));
    }

    

Parameters:
xslListOrOutType
in
Throws:
java.lang.Exception
   public static Writer generate(String xslListOrOutTypeReader inthrows Exception {
       StringWriter writer = new StringWriter();
       writer.write(generateString(xslListOrOutType,in));
       return writer;
   }
   
   
   

Parameters:
xslListOrOutType
in
Throws:
java.lang.Exception
  public static StringBuffer generate(String xslListOrOutTypeStringBuffer inthrows Exception {
      return new StringBuffer(generate(xslListOrOutTypein.toString()));
  }
   
   
    

Parameters:
xslListOrOutType
in
Throws:
java.lang.Exception
    public static String generateString(String xslListOrOutTypeReader inthrows Exception {
        Document doc = generateXML(in);
        // Sortie vers rst
        if (xslListOrOutType.equals()){
            return generateRST(doc);
        } else if (!StringUtils.isEmpty(xslListOrOutType)) {
            doc = applyXsls(docxslListOrOutType);
        }
        return doc.asXML();
    }
    
    
    
    private static Document applyXsls(Document docString xslListOrOutTypethrows IOExceptionFileNotFoundExceptionTransformerException {
        // search xsl file list to apply
        String xslList = .get(xslListOrOutType);
        if (xslListOrOutType == null) {
            xslList = xslListOrOutType;
        }
        // apply xsl on rst xml document
        JRSTGenerator gen = new JRSTGenerator();
        String[] xsls = StringUtil.split(xslList",");
        for (String xsl : xsls) {
            URL stylesheet = null;
            File file = new File(xsl);
            if (file.exists()) {
                stylesheet = file.toURI().toURL();
            } else {
                //stylesheet = JRST.class.getResource(xsl);
                stylesheet = Resource.getURL(xsl);
            }
            if (stylesheet == null) {
                throw new FileNotFoundException("Can't find stylesheet: "
                        + xsl);
            }
            final String finalXsl = xsl;
            // add entity resolver
            gen.setUriResolver(new URIResolver() {
                public Source resolve(String hrefString base) {
                    if (.isDebugEnabled()) {
                        .debug("RESOLVING: href: "+href+" base: "+base);
                    }
                    String xslDir = finalXsl.substring(0, finalXsl.lastIndexOf('/') + 1);
                    String resouceFullName = xslDir + href;
                    if (.isDebugEnabled()) {
                        .debug("RESOLVING: resouceFullName: "+resouceFullName);
                    }
                    try {
                        InputStream stream = null;
                        File file = new File(resouceFullName);
                        if (file.exists()) {
                            stream = new FileInputStream(file);
                        } else {
                            try {
                                stream = Resource.getURL(resouceFullName).openStream();
                            }
                            catch (Exception e) {
                                stream = Resource.getURL("/docbook/common/" + href).openStream();
                            }
                        }
                        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
                        SAXParser saxParser = parserFactory.newSAXParser();
                        XMLReader xmlReader = saxParser.getXMLReader();
                        xmlReader.setEntityResolver(new EntityResolver() {
                            @Override
                            public InputSource resolveEntity(String publicIdString systemId)
                                    throws SAXExceptionIOException {
                                InputSource source = null;
                                String smallSystemId = systemId.substring(systemId.lastIndexOf("/") + 1);
                                URL url = Resource.getURL("/docbook/common/" + smallSystemId);
                                if (url != null) {
                                    if (.isDebugEnabled()) {
                                        .debug("Resolved entity url : " + url);
                                    }
                                    InputStream stream = url.openStream();
                                    source = new InputSource(stream);
                                }
                                return source;
                            }
                        });
                        InputSource inSrc = new InputSource(stream);
                        SAXSource saxs = new SAXSource(xmlReaderinSrc);
                        return saxs;
                    } catch (IOException e) {
                        e.printStackTrace();
                        return null;
                    } catch (ParserConfigurationException e) {
                        e.printStackTrace();
                        return null;
                    } catch (SAXException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            });
            doc = gen.transform(docstylesheet);
        }
        return doc;
    }
    public static Document generateXML(Reader inthrows Exception {
        // parse rst file
        JRSTReader jrst = new JRSTReader();
        return jrst.read(in);
    }
    public static String generateRST(Document docthrows IOException {
        // Creation d'un visitor qui convertie de l'xml vers le rst
        DocUtilsVisitor visitor = new DocUtils2RST();
        // Atacher le visitor au document
        // il va parcourir tout les elements et reconstruire du rst
        doc.accept(visitor);
        // Recuperation du resultat
        String result = visitor.getResult();
        // nettoyage du visiteur
        visitor.clear();
        return result;
    }
New to GrepCode? Check out our FAQ X