8ab96efcc6507a319bffa9263b0ce4381a472f71
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / export / pdf / WikiPDFExporter.java
1 package net.sourceforge.phpeclipse.wiki.export.pdf;
2
3 import java.io.FileNotFoundException;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.StringReader;
7 import java.lang.reflect.InvocationTargetException;
8 import java.util.ArrayList;
9 import java.util.Collections;
10 import java.util.List;
11
12 import net.sourceforge.phpeclipse.wiki.builder.CreatePageAction;
13 import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin;
14
15 import org.eclipse.core.resources.IFile;
16 import org.eclipse.core.resources.IResource;
17 import org.eclipse.core.runtime.CoreException;
18 import org.eclipse.core.runtime.IPath;
19 import org.eclipse.core.runtime.IProgressMonitor;
20 import org.eclipse.core.runtime.IStatus;
21 import org.eclipse.core.runtime.MultiStatus;
22 import org.eclipse.core.runtime.Path;
23 import org.eclipse.core.runtime.Status;
24 import org.eclipse.jface.operation.IRunnableWithProgress;
25 import org.eclipse.ui.PlatformUI;
26 import org.eclipse.ui.dialogs.IOverwriteQuery;
27
28 import com.lowagie.text.Document;
29 import com.lowagie.text.DocumentException;
30 import com.lowagie.text.html.HtmlParser;
31 import com.lowagie.text.pdf.PdfWriter;
32
33 //import de.java2html.converter.JavaSource2HTMLConverter;
34 //import de.java2html.javasource.JavaSource;
35 //import de.java2html.javasource.JavaSourceParser;
36 //import de.java2html.options.Java2HtmlConversionOptions;
37
38 public final class WikiPDFExporter implements IRunnableWithProgress {
39   //The constants for the overwrite 3 state
40   private static final int OVERWRITE_NOT_SET = 0;
41
42   private static final int OVERWRITE_NONE = 1;
43
44   private static final int OVERWRITE_ALL = 2;
45
46   private int overwriteState = OVERWRITE_NOT_SET;
47
48   private List errorTable = new ArrayList(1);
49
50   private List fResourcesToExport;
51
52   private IPath fPath;
53
54   private IOverwriteQuery fOverwriteCallback;
55
56   public WikiPDFExporter(List resources, String destinationPath, IOverwriteQuery overwriteImplementor) {
57     super();
58     fResourcesToExport = resources;
59     fPath = new Path(destinationPath);
60     fOverwriteCallback = overwriteImplementor;
61   }
62
63   //  public void export(IContainer folder, String exportDirectoryName, String srcBasePath, IProgressMonitor monitor) throws
64   // IOException, CoreException,
65   //      InstantiationException, IllegalAccessException, ClassNotFoundException {
66   //    // exportDirectory = new File(exportDirectoryName);
67   //    IResource[] resources = folder.members(IResource.FILE);
68   //    String templateFileName = Util.getExportTemplate(folder);
69   //// monitor.beginTask(WikiEditorPlugin.getResourceString("Export.wikiPages"), resources.length + 1);
70   //    for (int i = 0; i < resources.length; i++) {
71   //      if (resources[i] instanceof IFile) {
72   //        monitor.subTask(WikiEditorPlugin.getResourceString("Export.exportFile")+resources[i].getLocation());
73   //        CreatePageAction.createPage(templateFileName, (IFile) resources[i], exportDirectoryName, srcBasePath);
74   //        monitor.worked(1);
75   //      } else if (resources[i] instanceof IFolder) {
76   //        monitor.subTask(WikiEditorPlugin.getResourceString("Export.exportFolder")+resources[i].getLocation());
77   //        export((IFolder) resources[i], exportDirectoryName, srcBasePath, monitor);
78   //        monitor.worked(1);
79   //      }
80   //    }
81   //    // monitor.subTask(WikiEditorPlugin.getResourceString("Export.linkedResources"));
82   //    // exportLinkedResources();
83   //    // createIndex();
84   //// monitor.worked(1);
85   //  }
86
87   /**
88    * TODO: This is a horrible hack for a quick solution.
89    */
90   //  private void createIndex() throws IOException {
91   //    File indexFile = createHtmlFile("index");
92   //
93   //    PrintWriter writer = new PrintWriter(new FileWriter(indexFile));
94   //    writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
95   //    writer.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">");
96   //    writer.println("<html>");
97   //    writer.println(" <head>");
98   //    writer.print(" <title>Index</title>");
99   //    writer.println(" </head>");
100   //    writer.println(" <body>");
101   //
102   //    Iterator iterator = index.iterator();
103   //    while (iterator.hasNext()) {
104   //      String name = (String) iterator.next();
105   //      writer.print(" <br/>");
106   //      writer.println("<a href=\"" + name + ".html\">" + name + "</a>");
107   //    }
108   //
109   //    writer.println(" </body>");
110   //    writer.println(" </html>");
111   //    writer.flush();
112   //    writer.close();
113   //  }
114   //    private void exportLinkedResources() throws IOException {
115   //        if (!exportLinkMaker.hasLinkedDocuments()) {
116   //            return;
117   //        }
118   //        File workspaceExport = new File(exportDirectory, WikiPDFExporter.WORKSPACE);
119   //        if (!workspaceExport.exists()) {
120   //            workspaceExport.mkdir();
121   //        }
122   //        HashMap map = exportLinkMaker.getLinkedResources();
123   //        Iterator iterator = map.keySet().iterator();
124   //        while (iterator.hasNext()) {
125   //            IResource resource = (IResource) iterator.next();
126   //            String location = (String) map.get(resource);
127   //            export(resource, location);
128   //        }
129   //    }
130   //  private void export(IResource resource, String location) throws IOException {
131   //    File destination = new File(exportDirectory, location);
132   //
133   //    if (destination.isDirectory()) {
134   //      return;
135   //    }
136   //    if (!destination.exists()) {
137   //      destination.getParentFile().mkdirs();
138   //    }
139   //    File source = new File(resource.getLocation().toString());
140   //    if (isJavaResource(resource)) {
141   //      javaToHtml(source, new File(destination.getParentFile(), destination.getName()));
142   //    } else {
143   //      copy(source, destination);
144   //    }
145   //  }
146   //  private boolean isJavaResource(IResource resource) {
147   //    return "java".equals(resource.getFileExtension());
148   //  }
149   //  private void javaToHtml(File source, File destination) throws IOException {
150   //    JavaSource java = new JavaSourceParser().parse(new FileReader(source));
151   //    JavaSource2HTMLConverter converter = new JavaSource2HTMLConverter(java);
152   //    Java2HtmlConversionOptions options = Java2HtmlConversionOptions.getDefault();
153   //    options.setShowLineNumbers(true);
154   //    options.setShowFileName(true);
155   //    options.setShowJava2HtmlLink(true);
156   //    converter.setConversionOptions(options);
157   //    FileWriter writer = new FileWriter(destination);
158   //    converter.convert(writer);
159   //    writer.flush();
160   //    writer.close();
161   //  }
162   //  private void copy(File source, File dest) throws IOException {
163   //    FileChannel in = null;
164   //    FileChannel out = null;
165   //    try {
166   //      in = new FileInputStream(source).getChannel();
167   //      out = new FileOutputStream(dest).getChannel();
168   //      long size = in.size();
169   //      MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);
170   //      out.write(buf);
171   //    } finally {
172   //      if (in != null) {
173   //        in.close();
174   //      }
175   //      if (out != null) {
176   //        out.close();
177   //      }
178   //    }
179   //  }
180   /*
181    * (non-Javadoc)
182    * 
183    * @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
184    */
185 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
186
187     WikiFilesVisitor visitor = new WikiFilesVisitor();
188     for (int i = 0; i < fResourcesToExport.size(); i++) {
189       try {
190         ((IResource) fResourcesToExport.get(i)).accept(visitor);
191       } catch (CoreException e) {
192         e.printStackTrace();
193       }
194     }
195
196     List list = visitor.getList();
197     Collections.sort(list, new IFileComparator());
198     IFile file;
199     StringBuffer htmlBuffer = new StringBuffer();
200     htmlBuffer.append("<html><head></head><body>");
201     for (int i = 0; i < list.size(); i++) {
202       try {
203         file = (IFile) list.get(i);
204         monitor.subTask(WikiEditorPlugin.getResourceString("Export.exportFile") + file.getLocation());
205         System.out.println(file.getLocation().toString());
206         // TODO add the real title here:
207         htmlBuffer.append("<h2>"+file.getName()+"</h2><br/>");
208         CreatePageAction.createFragmentPage(file, htmlBuffer);
209         if (i < list.size()-1) {
210 //        TODO create a boolean flag to determine, if we would like a new page or only horizontal ruler
211           htmlBuffer.append("<hr/>");
212         }
213         System.out.println(htmlBuffer.toString());
214         //        CreatePageAction.createPage(templateFileName, (IFile) resources[i], exportDirectoryName, srcBasePath);
215         monitor.worked(1);
216       } catch (Exception e) {
217         addError("PDF export exception", e);
218       }
219     }
220     htmlBuffer.append("</body></html>");
221     
222     StringReader stream = null;
223     String pdffilename = fPath.toString();
224     FileOutputStream os = null;
225     try {
226       
227       HtmlParser parser = new HtmlParser();
228       Document document = new Document();
229       document.open();
230       os = new FileOutputStream(pdffilename);
231       monitor.subTask("Generating PDF file: "+pdffilename);
232       stream = new StringReader(htmlBuffer.toString());
233       PdfWriter pdfWriter = PdfWriter.getInstance(document, os);
234 //      pdfWriter.s
235       parser.go(document, stream);
236     } catch (FileNotFoundException e) {
237       e.printStackTrace();
238     } catch (Exception e) {
239       e.printStackTrace();
240     } finally {
241       if (stream!=null) {
242         stream.close();
243       }
244       if (os!=null) {
245         try {
246           os.close();
247         } catch (IOException e1) {
248         }
249       }
250     }
251
252     System.out.println(fPath.toString());
253   }
254   /**
255    * Add a new entry to the error table with the passed information
256    */
257   protected void addError(String message, Throwable e) {
258     errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, message, e));
259   }
260
261   /**
262    * Set this boolean indicating whether exported resources should automatically overwrite existing files when a conflict occurs. If
263    * not query the user.
264    * 
265    * @param value
266    *          boolean
267    */
268   public void setOverwriteFiles(boolean value) {
269     if (value)
270       overwriteState = OVERWRITE_ALL;
271   }
272
273   /**
274    * Returns the status of the export operation. If there were any errors, the result is a status object containing individual
275    * status objects for each error. If there were no errors, the result is a status object with error code <code>OK</code>.
276    * 
277    * @return the status
278    */
279   public IStatus getStatus() {
280     IStatus[] errors = new IStatus[errorTable.size()];
281     errorTable.toArray(errors);
282     return new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, errors, "PDF export problems occured", //$NON-NLS-1$
283         null);
284   }
285   
286   // test
287 //  public static void main(String[] args) {
288 //    try {
289 //      HtmlParser parser = new HtmlParser();
290 //      Document document = new Document();
291 //      String htmlfilename = "C:/eclipse/wikibooks/wpbin/Synästhesie.html";
292 //      String pdffilename = "C:/eclipse/wikibooks/wpbin/code_java1.pdf";
293 //
294 //      PdfWriter.getInstance(document, new FileOutputStream(pdffilename));
295 //      parser.go(document, htmlfilename);
296 //    } catch (FileNotFoundException e) {
297 //      e.printStackTrace();
298 //    } catch (DocumentException e) {
299 //      e.printStackTrace();
300 //    }
301 //  }
302 }