Logback added

This commit is contained in:
Georgy Litvinov 2020-08-14 12:58:55 +02:00
parent 1a78f4242f
commit 83045e9422
10 changed files with 412 additions and 389 deletions

View file

@ -4,6 +4,7 @@ import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext; import com.sun.star.uno.XComponentContext;
import pro.litvinovg.w2phtml.gui.ConfigurationWindow; import pro.litvinovg.w2phtml.gui.ConfigurationWindow;
import pro.litvinovg.w2phtml.gui.ConversionExecutor;
import pro.litvinovg.w2phtml.gui.Document; import pro.litvinovg.w2phtml.gui.Document;
import com.sun.star.lib.uno.helper.Factory; import com.sun.star.lib.uno.helper.Factory;
@ -13,6 +14,9 @@ import java.util.Comparator;
import javax.swing.UnsupportedLookAndFeelException; import javax.swing.UnsupportedLookAndFeelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.star.beans.Property; import com.sun.star.beans.Property;
import com.sun.star.beans.XPropertyContainer; import com.sun.star.beans.XPropertyContainer;
import com.sun.star.beans.XPropertySet; import com.sun.star.beans.XPropertySet;
@ -40,6 +44,8 @@ public final class W2PHTMLExtension extends WeakBase
private XDocumentPropertiesSupplier documentPropertiesSupplier; private XDocumentPropertiesSupplier documentPropertiesSupplier;
private static final String m_implementationName = W2PHTMLExtension.class.getName(); private static final String m_implementationName = W2PHTMLExtension.class.getName();
private static final String[] m_serviceNames = { "pro.litvinovg.libreoffice.Writer2PaginatedHTML" }; private static final String[] m_serviceNames = { "pro.litvinovg.libreoffice.Writer2PaginatedHTML" };
private static final Logger logger = LoggerFactory.getLogger(W2PHTMLExtension.class);
public W2PHTMLExtension(XComponentContext componentContext) { public W2PHTMLExtension(XComponentContext componentContext) {

View file

@ -5,7 +5,6 @@ import java.awt.EventQueue;
import javax.swing.JFrame; import javax.swing.JFrame;
import javax.swing.UIManager; import javax.swing.UIManager;
import com.github.andrewoma.dexx.collection.Map;
import com.sun.star.uno.XComponentContext; import com.sun.star.uno.XComponentContext;
import pro.litvinovg.xml.Debug; import pro.litvinovg.xml.Debug;
@ -963,7 +962,7 @@ public class ConfigurationWindow extends JFrame {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Throwable e) { } catch (Throwable e) {
String message = e.getLocalizedMessage(); String message = e.getLocalizedMessage();
Debug.printLog(message, context); JOptionPane.showMessageDialog(singleFrame, message);
} }
EventQueue.invokeLater(new Runnable() { EventQueue.invokeLater(new Runnable() {
public void run() { public void run() {
@ -976,8 +975,7 @@ public class ConfigurationWindow extends JFrame {
} catch (Throwable e) { } catch (Throwable e) {
String message = e.getLocalizedMessage(); String message = e.getLocalizedMessage();
JOptionPane.showMessageDialog(singleFrame, message);
Debug.printLog(message, context);
} }
} }
}); });

View file

@ -5,6 +5,7 @@ import java.io.File;
import java.io.FilenameFilter; import java.io.FilenameFilter;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -18,13 +19,18 @@ import javax.swing.JOptionPane;
import javax.swing.JPanel; import javax.swing.JPanel;
import javax.swing.JTextField; import javax.swing.JTextField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.star.uno.XComponentContext; import com.sun.star.uno.XComponentContext;
import w2phtml.Application; import w2phtml.Application;
import w2phtml.rdf.Metadata;
public class ConversionExecutor { public class ConversionExecutor {
HashMap<String,String> options = new HashMap<String,String>(); HashMap<String,String> options = new HashMap<String,String>();
private static final Logger logger = LoggerFactory.getLogger(ConversionExecutor.class);
private String format = null; private String format = null;
private String inputFilePath = null; private String inputFilePath = null;
private String outputFilePath = null; private String outputFilePath = null;
@ -175,12 +181,22 @@ public class ConversionExecutor {
if (inputFile.isDirectory()) { if (inputFile.isDirectory()) {
convertAllInDir(); convertAllInDir();
} else { } else {
Application.main(prepareArgs()); tryConversion();
JOptionPane.showMessageDialog(frame, "Conversion completed."); JOptionPane.showMessageDialog(frame, "Conversion completed.");
} }
} }
private void tryConversion() {
try {
Application.main(prepareArgs());
} catch (Exception e ) {
logger.error("Conversion failed.");
logger.error("Params: " + Arrays.toString(prepareArgs()));
}
}
private void convertAllInDir() { private void convertAllInDir() {
File inputDir = new File(inputFilePath); File inputDir = new File(inputFilePath);
if (!inputDir.isDirectory()) { if (!inputDir.isDirectory()) {
@ -228,7 +244,7 @@ public class ConversionExecutor {
} }
inputFilePath = inputFile.getAbsolutePath(); inputFilePath = inputFile.getAbsolutePath();
Application.main(prepareArgs()); tryConversion();
} }

View file

@ -2,34 +2,17 @@ package pro.litvinovg.w2phtml.gui;
import java.io.File; import java.io.File;
import java.net.URI; import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import com.sun.star.beans.IllegalTypeException; import org.slf4j.Logger;
import com.sun.star.beans.NotRemoveableException; import org.slf4j.LoggerFactory;
import com.sun.star.beans.Property;
import com.sun.star.beans.PropertyExistException;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.beans.UnknownPropertyException;
import com.sun.star.beans.XPropertyContainer;
import com.sun.star.beans.XPropertySet;
import com.sun.star.beans.XPropertySetInfo;
import com.sun.star.document.XDocumentProperties; import com.sun.star.document.XDocumentProperties;
import com.sun.star.document.XDocumentPropertiesSupplier; import com.sun.star.document.XDocumentPropertiesSupplier;
import com.sun.star.frame.XController;
import com.sun.star.frame.XDesktop; import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XDispatch;
import com.sun.star.frame.XDispatchHelper;
import com.sun.star.frame.XDispatchProvider; import com.sun.star.frame.XDispatchProvider;
import com.sun.star.frame.XFrame; import com.sun.star.frame.XFrame;
import com.sun.star.frame.XModel; import com.sun.star.frame.XModel;
import com.sun.star.frame.XStorable; import com.sun.star.frame.XStorable;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XComponent; import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XMultiServiceFactory;
@ -39,12 +22,12 @@ import com.sun.star.text.XTextDocument;
import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext; import com.sun.star.uno.XComponentContext;
import com.sun.star.util.XModifiable; import com.sun.star.util.XModifiable;
import com.sun.star.view.XViewSettingsSupplier;
import pro.litvinovg.xml.Debug;
public class Document { public class Document {
private static final Logger logger = LoggerFactory.getLogger(Document.class);
private XComponentContext context; private XComponentContext context;
private XDesktop xDesktop; private XDesktop xDesktop;
private XMultiComponentFactory multiComponentFactory; private XMultiComponentFactory multiComponentFactory;
@ -78,7 +61,7 @@ public class Document {
} }
XTextDocument textDoc = UnoRuntime.queryInterface(XTextDocument.class, currentDocument); XTextDocument textDoc = UnoRuntime.queryInterface(XTextDocument.class, currentDocument);
if (textDoc == null) { if (textDoc == null) {
Debug.printLog("Error. TextDoc is null.", componentContext); logger.error("Error. TextDoc is null.");
return; return;
} }
XStorable storable = UnoRuntime.queryInterface(XStorable.class, textDoc); XStorable storable = UnoRuntime.queryInterface(XStorable.class, textDoc);
@ -92,12 +75,12 @@ public class Document {
XModifiable modifieable = UnoRuntime.queryInterface(XModifiable.class, textDoc); XModifiable modifieable = UnoRuntime.queryInterface(XModifiable.class, textDoc);
if (modifieable == null || modifieable.isModified()) { if (modifieable == null || modifieable.isModified()) {
Debug.printLog("Document is modified. Save changes before conversion.", componentContext); logger.error("Document is modified. Save changes before conversion.");
} else { } else {
//Debug.printLog("Document isn't modified", componentContext); //Debug.printLog("Document isn't modified", componentContext);
} }
if (!storable.hasLocation()) { if (!storable.hasLocation()) {
Debug.printLog("Document is not saved. Save document before conversion.", componentContext); logger.error("Document is not saved. Save document before conversion.");
return; return;
} }
String url = model.getURL(); String url = model.getURL();
@ -108,7 +91,7 @@ public class Document {
} }
} catch (Throwable e) { } catch (Throwable e) {
Debug.printLog(e.getStackTrace().toString(), componentContext); logger.error(e.toString());
return; return;
} }
} }

View file

@ -0,0 +1,43 @@
package pro.litvinovg.w2phtml.gui;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import ch.qos.logback.core.AppenderBase;
public class LogAppender<ILoggingEvent> extends AppenderBase<ILoggingEvent> {
private Map eventMap = new ConcurrentHashMap();
private String prefix;
private static LogAppender LOG_APPENDER_INSTANCE = null;
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
@Override
protected void append(ILoggingEvent event) {
if (prefix == null || "".equals(prefix)) {
addError("Prefix is not set for LogAppender.");
return;
}
eventMap.put(prefix + System.currentTimeMillis(), event);
}
public LogAppender createInstance() {
if (LOG_APPENDER_INSTANCE == null) {
LOG_APPENDER_INSTANCE = new LogAppender();
}
return LOG_APPENDER_INSTANCE;
}
public void putEvent(String key, String value) {
eventMap.put(key, value);
}
public Map getEventMap() {
return eventMap;
}
}

View file

@ -8,9 +8,6 @@ import org.w3c.dom.ls.LSSerializer;
import com.sun.star.uno.XComponentContext; import com.sun.star.uno.XComponentContext;
import pro.litvinovg.w2phtml.DialogHelper;
public class Debug { public class Debug {
public static void printNode(Node node){ public static void printNode(Node node){
Document document = node.getOwnerDocument(); Document document = node.getOwnerDocument();
@ -26,11 +23,4 @@ public class Debug {
} }
} }
public static void printLog(String message, XComponentContext context) {
if (context != null) {
DialogHelper.showErrorMessage(context, null, message);
} else {
System.out.println(message);
}
}
} }

View file

@ -37,6 +37,9 @@ import java.util.Hashtable;
import java.util.Set; import java.util.Set;
import java.util.Vector; import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pro.litvinovg.w2phtml.gui.ConfigurationWindow; import pro.litvinovg.w2phtml.gui.ConfigurationWindow;
import w2phtml.api.Converter; import w2phtml.api.Converter;
import w2phtml.api.ConverterFactory; import w2phtml.api.ConverterFactory;
@ -44,363 +47,340 @@ import w2phtml.api.ConverterResult;
import w2phtml.api.MIMETypes; import w2phtml.api.MIMETypes;
import w2phtml.util.Misc; import w2phtml.util.Misc;
/**
* <p>Command line utility to convert an OpenOffice.org Writer XML file into XHTML/LaTeX/BibTeX</p>
* <p>The utility is invoked with the following command line:</p>
* <pre>java -jar writer2latex.jar [options] source [target]</pre>
* <p>Where the available options are
* <ul>
* <li><code>-html5</code>, <code>-xhtml</code>,
<code>-xhtml+mathml</code>, <code>-epub</code>, <code>-epub3</code>
* <li><code>-recurse</code>
* <li><code>-ultraclean</code>, <code>-clean</code>, <code>-pdfscreen</code>,
* <code>-pdfprint</code>, <code>-cleanxhtml</code>
* <li><code>-config[=]filename</code>
* <li><code>-template[=]filename</code>
* <li><code>-stylesheet[=]filename</code>
* <li><code>-resource[=]filename[::media type]</code>
* <li><code>-option[=]value</code>
* </ul>
* <p>where <code>option</code> can be any simple option known to Writer2LaTeX
* (see documentation for the configuration file).</p>
*/
public final class Application { public final class Application {
/* Based on command-line parameters. */ private static final Logger logger = LoggerFactory.getLogger(Application.class);
private String sTargetMIME = MIMETypes.HTML5; /* Based on command-line parameters. */
private Vector<String> configFileNames = new Vector<String>(); private String sTargetMIME = MIMETypes.HTML5;
private String sTemplateFileName = null; private Vector<String> configFileNames = new Vector<String>();
private String sStyleSheetFileName = null; private String sTemplateFileName = null;
private Set<String> resources = new HashSet<String>(); private String sStyleSheetFileName = null;
private Hashtable<String,String> options = new Hashtable<String,String>(); private Set<String> resources = new HashSet<String>();
private String sSource = null; private Hashtable<String, String> options = new Hashtable<String, String>();
private String sTarget = null; private String sSource = null;
private String sTarget = null;
/** /**
* Main method * Main method
* *
* @param args The argument passed on the command line. * @param args
*/ * The argument passed on the command line.
public static final void main (String[] args){ */
if (args.length == 0) { public static final void main(String[] args) throws Exception {
showUsage(""); if (args.length == 0) {
ConfigurationWindow.runGUI(null); showUsage("");
} else { ConfigurationWindow.runGUI(null);
try { } else {
//long time = System.currentTimeMillis(); try {
Application app = new Application(); long time = System.currentTimeMillis();
app.parseCommandLine(args); Application app = new Application();
app.doConversion(); app.parseCommandLine(args);
//System.out.println("Total conversion time was "+(System.currentTimeMillis()-time)+" miliseconds"); app.doConversion();
} catch (IllegalArgumentException ex) { logger.debug("Total conversion time was " + (System.currentTimeMillis() - time) + " miliseconds");
String msg = ex.getMessage(); } catch (IllegalArgumentException ex) {
showUsage(msg); String msg = ex.getMessage();
} showUsage(msg);
} }
}
} }
// Convert the directory or file // Convert the directory or file
private void doConversion() { private void doConversion() throws Exception {
sayHello(); sayHello();
File source = new File(sSource); File source = new File(sSource);
examineSource(source); examineSource(source);
// Step 3: Examine target // Step 3: Examine target
File target; File target;
target = examineTarget(source); target = examineTarget(source);
// Step 4: Create converters // Step 4: Create converters
Converter converter = ConverterFactory.createConverter(sTargetMIME); Converter converter = ConverterFactory.createConverter(sTargetMIME);
if (converter==null) { if (converter == null) {
System.out.println("Failed to create converter for "+sTargetMIME); logger.error("Failed to create converter for " + sTargetMIME);
System.exit(1); throw new Exception("Conversion failed.");
} }
// Step 5a: Read template
if (sTemplateFileName != null) {
try {
logger.info("Reading template " + sTemplateFileName);
byte[] templateBytes = Misc.inputStreamToByteArray(new FileInputStream(sTemplateFileName));
converter.readTemplate(new ByteArrayInputStream(templateBytes));
} catch (FileNotFoundException e) {
logger.error("--> This file does not exist!");
logger.error(" " + e.getMessage());
} catch (IOException e) {
logger.error("--> Failed to read the template file!");
logger.error(" " + e.getMessage());
}
}
// Step 5a: Read template // Step 5b: Read style sheet
if (sTemplateFileName!=null) { if (sStyleSheetFileName != null) {
try { try {
System.out.println("Reading template "+sTemplateFileName); logger.info("Reading style sheet " + sStyleSheetFileName);
byte [] templateBytes = Misc.inputStreamToByteArray(new FileInputStream(sTemplateFileName)); byte[] styleSheetBytes = Misc.inputStreamToByteArray(new FileInputStream(sStyleSheetFileName));
converter.readTemplate(new ByteArrayInputStream(templateBytes)); converter.readStyleSheet(new ByteArrayInputStream(styleSheetBytes));
} } catch (FileNotFoundException e) {
catch (FileNotFoundException e) { logger.error("--> This file does not exist!");
System.out.println("--> This file does not exist!"); logger.error(" " + e.getMessage());
System.out.println(" "+e.getMessage()); } catch (IOException e) {
} logger.error("--> Failed to read the style sheet file!");
catch (IOException e) { logger.error(" " + e.getMessage());
System.out.println("--> Failed to read the template file!"); }
System.out.println(" "+e.getMessage()); }
}
}
// Step 5b: Read style sheet // Step 5c: Read style resources
if (sStyleSheetFileName!=null) { for (String sResource : resources) {
try { String sMediaType;
System.out.println("Reading style sheet "+sStyleSheetFileName); String sFileName;
byte [] styleSheetBytes = Misc.inputStreamToByteArray(new FileInputStream(sStyleSheetFileName)); int nSeparator = sResource.indexOf("::");
converter.readStyleSheet(new ByteArrayInputStream(styleSheetBytes)); if (nSeparator > -1) {
} sFileName = sResource.substring(0, nSeparator);
catch (FileNotFoundException e) { sMediaType = sResource.substring(nSeparator + 2);
System.out.println("--> This file does not exist!");
System.out.println(" "+e.getMessage());
}
catch (IOException e) {
System.out.println("--> Failed to read the style sheet file!");
System.out.println(" "+e.getMessage());
}
}
// Step 5c: Read style resources
for (String sResource : resources) {
String sMediaType;
String sFileName;
int nSeparator = sResource.indexOf("::");
if (nSeparator>-1) {
sFileName = sResource.substring(0,nSeparator);
sMediaType = sResource.substring(nSeparator+2);
}
else {
sFileName = sResource;
sMediaType = null;
}
System.out.println("Reading resource file "+sFileName);
try {
byte [] resourceBytes = Misc.inputStreamToByteArray(new FileInputStream(sFileName));
converter.readResource(new ByteArrayInputStream(resourceBytes),sFileName,sMediaType);
} catch (IOException e) {
System.out.println("--> Failed to read the resource file!");
System.out.println(" "+e.getMessage());
}
}
// Step 6: Read config
for (int i=0; i<configFileNames.size(); i++) {
String sConfigFileName = (String) configFileNames.get(i);
if (sConfigFileName.startsWith("*")) {
sConfigFileName = sConfigFileName.substring(1);
System.out.println("Reading default configuration "+sConfigFileName);
try {
converter.getConfig().readDefaultConfig(sConfigFileName);
}
catch (IllegalArgumentException e) {
System.err.println("--> This configuration is unknown!");
System.out.println(" "+e.getMessage());
}
}
else {
System.out.println("Reading configuration file "+sConfigFileName);
try {
byte[] configBytes = Misc.inputStreamToByteArray(new FileInputStream(sConfigFileName));
converter.getConfig().read(new ByteArrayInputStream(configBytes));
}
catch (IOException e) {
System.err.println("--> Failed to read the configuration!");
System.out.println(" "+e.getMessage());
}
}
}
// Step 7: Set options from command line
Enumeration<String> keys = options.keys();
while (keys.hasMoreElements()) {
String sKey = keys.nextElement();
String sValue = (String) options.get(sKey);
converter.getConfig().setOption(sKey,sValue);
}
// Step 8: Perform conversion
System.out.println("Converting "+source.getPath());
ConverterResult dataOut = null;
try {
dataOut = converter.convert(source,target.getName());
}
catch (FileNotFoundException e) {
System.out.println("--> The file "+source.getPath()+" does not exist!");
System.out.println(" "+e.getMessage());
System.exit(1);
}
catch (IOException e) {
System.out.println("--> Failed to convert the file "+source.getPath()+"!");
System.out.println(" "+e.getMessage());
System.out.println(" Please make sure the file is in OpenDocument format");
System.exit(1);
}
// TODO: Should do some further checking on the feasability of writing
// the directory and the files.
File targetDir = target.getParentFile();
if (targetDir!=null && !targetDir.exists()) { targetDir.mkdirs(); }
try {
dataOut.write(targetDir);
}
catch (IOException e) {
System.out.println("--> Error writing out file!");
System.out.println(" "+e.getMessage());
System.exit(1);
}
// Step 9: Say goodbye!
System.out.println("Done!");
}
private File examineTarget(File source) {
File target;
if (sTarget == null) {
target = new File(source.getParent(), Misc.removeExtension(source.getName()));
} else { } else {
target = new File(sTarget); sFileName = sResource;
if (sTarget.endsWith(File.separator)) { sMediaType = null;
target = new File(target, Misc.removeExtension(source.getName())); }
logger.info("Reading resource file " + sFileName);
try {
byte[] resourceBytes = Misc.inputStreamToByteArray(new FileInputStream(sFileName));
converter.readResource(new ByteArrayInputStream(resourceBytes), sFileName, sMediaType);
} catch (IOException e) {
logger.error("--> Failed to read the resource file!");
logger.error(" " + e.getMessage());
}
}
// Step 6: Read config
for (int i = 0; i < configFileNames.size(); i++) {
String sConfigFileName = (String) configFileNames.get(i);
if (sConfigFileName.startsWith("*")) {
sConfigFileName = sConfigFileName.substring(1);
logger.info("Reading default configuration " + sConfigFileName);
try {
converter.getConfig().readDefaultConfig(sConfigFileName);
} catch (IllegalArgumentException e) {
logger.error("--> This configuration is unknown!");
logger.error(" " + e.getMessage());
}
} else {
logger.info("Reading configuration file " + sConfigFileName);
try {
byte[] configBytes = Misc.inputStreamToByteArray(new FileInputStream(sConfigFileName));
converter.getConfig().read(new ByteArrayInputStream(configBytes));
} catch (IOException e) {
logger.error("--> Failed to read the configuration!");
logger.error(" " + e.getMessage());
} }
} }
return target;
} }
private void examineSource(File source) { // Step 7: Set options from command line
if (!source.exists()) { Enumeration<String> keys = options.keys();
System.out.println("I'm sorry, I can't find "+sSource); while (keys.hasMoreElements()) {
System.exit(1); String sKey = keys.nextElement();
} String sValue = (String) options.get(sKey);
if (!source.canRead()) { converter.getConfig().setOption(sKey, sValue);
System.out.println("I'm sorry, I can't read "+sSource); }
System.exit(1);
// Step 8: Perform conversion
logger.info("Converting " + source.getPath());
ConverterResult dataOut = null;
try {
dataOut = converter.convert(source, target.getName());
} catch (FileNotFoundException e) {
logger.error("--> The file " + source.getPath() + " does not exist!");
logger.error(" " + e.getMessage());
throw new Exception("Conversion failed.");
} catch (IOException e) {
logger.error("--> Failed to convert the file " + source.getPath() + "!");
logger.error(" " + e.getMessage());
logger.error(" Please make sure the file is in OpenDocument format");
throw new Exception("Conversion failed.");
}
// TODO: Should do some further checking on the feasability of writing
// the directory and the files.
File targetDir = target.getParentFile();
if (targetDir != null && !targetDir.exists()) {
targetDir.mkdirs();
}
try {
dataOut.write(targetDir);
} catch (IOException e) {
logger.error("--> Error writing out file!");
logger.error(" " + e.getMessage());
throw new Exception("Conversion failed.");
}
// Step 9: Say goodbye!
logger.info("Done!");
}
private File examineTarget(File source) {
File target;
if (sTarget == null) {
target = new File(source.getParent(), Misc.removeExtension(source.getName()));
} else {
target = new File(sTarget);
if (sTarget.endsWith(File.separator)) {
target = new File(target, Misc.removeExtension(source.getName()));
} }
} }
private void sayHello() { return target;
System.out.println(); }
System.out.println("This is w2phtml, Version " + ConverterFactory.getVersion() +
" (" + ConverterFactory.getDate() + ")"); private void examineSource(File source) throws Exception {
System.out.println(); if (!source.exists()) {
System.out.println("Starting conversion..."); logger.error("I'm sorry, I can't find " + sSource);
throw new Exception("Conversion failed.");
} }
if (!source.canRead()) {
logger.error("I'm sorry, I can't read " + sSource);
throw new Exception("Conversion failed.");
}
}
private void sayHello() {
logger.info("This is w2phtml, Version " + ConverterFactory.getVersion() + " (" + ConverterFactory.getDate() + ")");
logger.info("Starting conversion...");
}
/** /**
* Display usage. * Display usage.
*/ */
private static void showUsage(String msg) { private static void showUsage(String msg) {
System.out.println(); System.out.println();
System.out.println("This is w2phtml, Version " + ConverterFactory.getVersion() System.out.println("This is w2phtml, Version " + ConverterFactory.getVersion() + " (" + ConverterFactory.getDate() + ")");
+ " (" + ConverterFactory.getDate() + ")"); System.out.println();
System.out.println(); if (msg != null)
if (msg != null) System.out.println(msg); System.out.println(msg);
System.out.println(); System.out.println();
System.out.println("Usage:"); System.out.println("Usage:");
System.out.println(" java -jar <path>/w2phtml.jar <options> <source file/directory> [<target file/directory>]"); System.out.println(" java -jar <path>/w2phtml.jar <options> <source file/directory> [<target file/directory>]");
System.out.println("where the available options are:"); System.out.println("where the available options are:");
System.out.println(" -xhtml"); System.out.println(" -xhtml");
System.out.println(" -xhtml11"); System.out.println(" -xhtml11");
System.out.println(" -xhtml+mathml"); System.out.println(" -xhtml+mathml");
System.out.println(" -html5"); System.out.println(" -html5");
System.out.println(" -epub"); System.out.println(" -epub");
System.out.println(" -epub3"); System.out.println(" -epub3");
System.out.println(" -template[=]<template file>"); System.out.println(" -template[=]<template file>");
System.out.println(" -stylesheet[=]<style sheet file>"); System.out.println(" -stylesheet[=]<style sheet file>");
System.out.println(" -resource[=]<resource file>[::<media type>]"); System.out.println(" -resource[=]<resource file>[::<media type>]");
System.out.println(" -cleanxhtml"); System.out.println(" -cleanxhtml");
System.out.println(" -config[=]<configuration file>"); System.out.println(" -config[=]<configuration file>");
System.out.println(" -<configuration option>[=]<value>"); System.out.println(" -<configuration option>[=]<value>");
System.out.println("See the documentation for the available configuration options"); System.out.println("See the documentation for the available configuration options");
} }
/** /**
* Parse command-line arguments. * Parse command-line arguments.
* *
* @param args Array of command line arguments. * @param args
* * Array of command line arguments.
* @throws IllegalArgumentException If an argument is invalid. *
*/ * @throws IllegalArgumentException
private void parseCommandLine(String sArgs[]) * If an argument is invalid.
throws IllegalArgumentException { */
private void parseCommandLine(String sArgs[]) throws IllegalArgumentException {
int i = 0; int i = 0;
while (i<sArgs.length) { while (i < sArgs.length) {
String sArg = getArg(i++,sArgs); String sArg = getArg(i++, sArgs);
if (sArg.startsWith("-")) { // found an option if (sArg.startsWith("-")) { // found an option
if ("-html5".equals(sArg)) { sTargetMIME = MIMETypes.HTML5; } if ("-html5".equals(sArg)) {
else if ("-xhtml".equals(sArg)) { sTargetMIME = MIMETypes.XHTML; } sTargetMIME = MIMETypes.HTML5;
else if ("-xhtml11".equals(sArg)) { sTargetMIME = MIMETypes.XHTML11; } } else if ("-xhtml".equals(sArg)) {
else if ("-xhtml+mathml".equals(sArg)) { sTargetMIME = MIMETypes.XHTML_MATHML; } sTargetMIME = MIMETypes.XHTML;
else if ("-epub".equals(sArg)) { sTargetMIME = MIMETypes.EPUB; } } else if ("-xhtml11".equals(sArg)) {
else if ("-epub3".equals(sArg)) { sTargetMIME = MIMETypes.EPUB3; } sTargetMIME = MIMETypes.XHTML11;
else if ("-rdf".equals(sArg)) { sTargetMIME = MIMETypes.RDF; } } else if ("-xhtml+mathml".equals(sArg)) {
else if ("-cleanxhtml".equals(sArg)) { configFileNames.add("*cleanxhtml.xml"); } sTargetMIME = MIMETypes.XHTML_MATHML;
else { // option with argument } else if ("-epub".equals(sArg)) {
int j=sArg.indexOf("="); sTargetMIME = MIMETypes.EPUB;
String sArg2; } else if ("-epub3".equals(sArg)) {
if (j>-1) { // argument is separated by = sTargetMIME = MIMETypes.EPUB3;
sArg2 = sArg.substring(j+1); } else if ("-rdf".equals(sArg)) {
sArg = sArg.substring(0,j); sTargetMIME = MIMETypes.RDF;
} } else if ("-cleanxhtml".equals(sArg)) {
else { // argument is separated by space configFileNames.add("*cleanxhtml.xml");
sArg2 = getArg(i++,sArgs); } else { // option with argument
} int j = sArg.indexOf("=");
if ("-config".equals(sArg)) { configFileNames.add(sArg2); } String sArg2;
else if ("-template".equals(sArg)) { sTemplateFileName = sArg2; } if (j > -1) { // argument is separated by =
else if ("-stylesheet".equals(sArg)) { sStyleSheetFileName = sArg2; } sArg2 = sArg.substring(j + 1);
else if ("-resource".equals(sArg)) { resources.add(sArg2); } sArg = sArg.substring(0, j);
else { // configuration option } else { // argument is separated by space
options.put(sArg.substring(1),sArg2); sArg2 = getArg(i++, sArgs);
} }
} if ("-config".equals(sArg)) {
} configFileNames.add(sArg2);
else { // not an option, so this must be the source } else if ("-template".equals(sArg)) {
sSource = sArg; sTemplateFileName = sArg2;
// Possibly followed by the target } else if ("-stylesheet".equals(sArg)) {
if (i<sArgs.length) { sStyleSheetFileName = sArg2;
String sArgument = getArg(i++,sArgs); } else if ("-resource".equals(sArg)) {
if (sArgument.length()>0) { sTarget = sArgument; } resources.add(sArg2);
} } else { // configuration option
// Skip any trailing empty arguments and signal an error if there's more options.put(sArg.substring(1), sArg2);
while (i<sArgs.length) { }
String sArgument = getArg(i++,sArgs); }
if (sArgument.length()>0) { } else { // not an option, so this must be the source
throw new IllegalArgumentException("I didn't expect "+sArgument+"?"); sSource = sArg;
} // Possibly followed by the target
} if (i < sArgs.length) {
} String sArgument = getArg(i++, sArgs);
} if (sArgument.length() > 0) {
if (sSource==null) { sTarget = sArgument;
throw new IllegalArgumentException("Please specify a source document/directory!"); }
} }
// Parsing of command line ended successfully! // Skip any trailing empty arguments and signal an error if there's more
} while (i < sArgs.length) {
String sArgument = getArg(i++, sArgs);
if (sArgument.length() > 0) {
throw new IllegalArgumentException("I didn't expect " + sArgument + "?");
}
}
}
}
if (sSource == null) {
throw new IllegalArgumentException("Please specify a source document/directory!");
}
// Parsing of command line ended successfully!
}
/**
* Extract the next argument from the array, while checking to see that the
* array size is not exceeded. Throw a friendly error message in case the arg
* is missing.
*
* @param i
* Argument index.
* @param args
* Array of command line arguments.
*
* @return The argument with the specified index.
*
* @throws IllegalArgumentException
* If an argument is invalid.
*/
private String getArg(int i, String args[]) throws IllegalArgumentException {
/** if (i < args.length) {
* Extract the next argument from the array, while checking to see return args[i];
* that the array size is not exceeded. Throw a friendly error } else
* message in case the arg is missing. throw new IllegalArgumentException("I'm sorry, the commandline ended abnormally");
* }
* @param i Argument index.
* @param args Array of command line arguments.
*
* @return The argument with the specified index.
*
* @throws IllegalArgumentException If an argument is invalid.
*/
private String getArg(int i, String args[])
throws IllegalArgumentException {
if (i < args.length) {
return args[i];
}
else throw new
IllegalArgumentException("I'm sorry, the commandline ended abnormally");
}
} }

View file

@ -1,3 +1,3 @@
#Sat Jul 25 13:13:39 CEST 2020 #Fri Aug 14 12:07:37 CEST 2020
releaseVersion=0.7.3 releaseVersion=0.7.4
releaseDate=13\:13\:39 25-07-2020 releaseDate=12\:07\:37 14-08-2020

View file

@ -3,12 +3,16 @@ package w2phtml.rdf;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import com.opencsv.CSVReader; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opencsv.CSVReaderHeaderAware; import com.opencsv.CSVReaderHeaderAware;
import com.opencsv.exceptions.CsvValidationException; import com.opencsv.exceptions.CsvValidationException;
@ -16,10 +20,13 @@ public class Metadata {
private static final String SUBTITLE = "subtitle"; private static final String SUBTITLE = "subtitle";
private static final String FILENAME = "Filename"; private static final String FILENAME = "Filename";
private static final String SECTION = "Section"; private static final String SECTION = "Section";
private static final Logger logger = LoggerFactory.getLogger(Metadata.class);
private HashMap<String, HashMap<String, Set<String>>> sectionsMetadata; private HashMap<String, HashMap<String, Set<String>>> sectionsMetadata;
public Metadata() { public Metadata() {
sectionsMetadata = new HashMap<String, HashMap<String,Set<String>>>(); sectionsMetadata = new HashMap<String, HashMap<String,Set<String>>>();
} }
public void read(String metadataFilePath) { public void read(String metadataFilePath) {
@ -51,18 +58,19 @@ public class Metadata {
} }
} catch (CsvValidationException e) { } catch (CsvValidationException e) {
System.out.println("CSV Validation failed. CSV file is broken"); logger.error("CSV Validation failed. File " + filePath);
e.printStackTrace(); logger.error(e.toString());
StringWriter sw = new StringWriter();
e.printStackTrace( new PrintWriter(sw));
logger.error(sw.toString());
} catch (IOException e) { } catch (IOException e) {
System.out.println("I/O Exception happened. Oops."); logger.error("Bad CSV file " + filePath);
System.out.println(i); logger.error(e.toString());
e.printStackTrace();
} finally { } finally {
try { try {
csvReader.close(); csvReader.close();
} catch (IOException e) { } catch (IOException e) {
System.out.println("I/O Exception happened. Sorry."); logger.error("On closing reader I/O Exception happened.");
e.printStackTrace();
} }
} }
} }

View file

@ -21,7 +21,6 @@ public class RDFDocumentResult implements OutputFile {
public RDFDocumentResult(Vector<XhtmlDocument> outFiles, String fileName, XhtmlConfig config) { public RDFDocumentResult(Vector<XhtmlDocument> outFiles, String fileName, XhtmlConfig config) {
System.out.println("FILENAME "+ fileName);
this.sFileName = Misc.removeExtension(fileName); this.sFileName = Misc.removeExtension(fileName);
this.config = config; this.config = config;
rdfStructure = new DocumentStructure(outFiles,sFileName,config); rdfStructure = new DocumentStructure(outFiles,sFileName,config);