1. Project Clover database Tue Dec 20 2016 21:24:09 CET
  2. Package org.xwiki.rendering.wikimodel.tex

File TexSerializer.java

 

Coverage histogram

../../../../../img/srcFileCovDistChart4.png
78% of files have more coverage

Code metrics

70
206
41
3
707
532
83
0.4
5.02
13.67
2.02

Classes

Class Line # Actions
TexSerializer 50 162 0% 69 140
0.4573643545.7%
TexSerializer.DocumentContext 52 0 - 0 0
-1.0 -
TexSerializer.WGet 61 44 0% 14 59
0.00%
 

Contributing tests

This file is covered by 12 tests. .

Source view

1    /*
2    * See the NOTICE file distributed with this work for additional
3    * information regarding copyright ownership.
4    *
5    * This is free software; you can redistribute it and/or modify it
6    * under the terms of the GNU Lesser General Public License as
7    * published by the Free Software Foundation; either version 2.1 of
8    * the License, or (at your option) any later version.
9    *
10    * This software is distributed in the hope that it will be useful,
11    * but WITHOUT ANY WARRANTY; without even the implied warranty of
12    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13    * Lesser General Public License for more details.
14    *
15    * You should have received a copy of the GNU Lesser General Public
16    * License along with this software; if not, write to the Free
17    * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
18    * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
19    */
20    package org.xwiki.rendering.wikimodel.tex;
21   
22    import java.io.BufferedOutputStream;
23    import java.io.DataInputStream;
24    import java.io.EOFException;
25    import java.io.File;
26    import java.io.FileInputStream;
27    import java.io.FileOutputStream;
28    import java.io.IOException;
29    import java.io.InputStream;
30    import java.io.OutputStream;
31    import java.io.PrintStream;
32    import java.net.HttpURLConnection;
33    import java.net.URL;
34    import java.net.URLConnection;
35    import java.util.ArrayDeque;
36    import java.util.Deque;
37    import java.util.HashMap;
38    import java.util.Map;
39   
40    import org.xwiki.rendering.wikimodel.IWikiPrinter;
41    import org.xwiki.rendering.wikimodel.PrintTextListener;
42    import org.xwiki.rendering.wikimodel.ReferenceHandler;
43    import org.xwiki.rendering.wikimodel.WikiParameters;
44    import org.xwiki.rendering.wikimodel.images.ImageUtil;
45   
46    /**
47    * @version $Id: e7bca6a91b38ad627b5c7848ab0618a05ee65bfd $
48    * @since 4.0M1
49    */
 
50    public class TexSerializer extends PrintTextListener
51    {
 
52    private static class DocumentContext
53    {
54    boolean fFirstRowCell = false;
55   
56    boolean fTableHead = false;
57   
58    boolean fTableHeadCell = false;
59    }
60   
 
61    class WGet
62    {
63    final String commandName = WGet.class.getName();
64   
65    int count;
66   
67    final PrintStream out = System.out;
68   
69    boolean output = true;
70   
71    boolean verb;
72   
73    // https://my.mandriva.com/rest/export/club.php?auth=a68184fa4d3acec7ac63542a70fa09d8-fee6f44d0dced0229543d9201b074377
74   
 
75  0 toggle public final void fetchURL(String url, OutputStream output)
76    throws IOException
77    {
78  0 URL url1 = new URL(url);
79  0 URLConnection urlConnection = url1.openConnection();
80  0 BufferedOutputStream bos = new BufferedOutputStream(output);
81  0 if (urlConnection instanceof HttpURLConnection) {
82  0 readHttpURL((HttpURLConnection) urlConnection, bos);
83    } else {
84  0 readURL(urlConnection);
85    }
86    }
87   
 
88  0 toggle public final void printHeader(URLConnection url)
89    {
90  0 verbose(WGet.class.getName()
91    + ": Content-Length : "
92    + url.getContentLength());
93  0 verbose(WGet.class.getName()
94    + ": Content-Type : "
95    + url.getContentType());
96  0 if (url.getContentEncoding() != null) {
97  0 verbose(WGet.class.getName()
98    + ": Content-Encoding : "
99    + url.getContentEncoding());
100    }
101    }
102   
 
103  0 toggle public final void readHttpURL(HttpURLConnection url, OutputStream output)
104    throws IOException
105    {
106   
107  0 long before, after;
108   
109  0 url.setAllowUserInteraction(true);
110  0 url.connect();
111  0 before = System.currentTimeMillis();
112  0 DataInputStream in = new DataInputStream(url.getInputStream());
113  0 after = System.currentTimeMillis();
114   
115  0 before = System.currentTimeMillis();
116   
117  0 try {
118  0 if (url.getResponseCode() != HttpURLConnection.HTTP_OK) {
119  0 out.println(commandName + ": " + url.getResponseMessage());
120    } else {
121  0 printHeader(url);
122  0 while (true) {
123    // writeChar((char) in.readUnsignedByte());
124  0 output.write(in.readByte());
125    }
126    }
127    } catch (EOFException e) {
128  0 after = System.currentTimeMillis();
129  0 int milliSeconds = (int) (after - before);
130  0 verbose(commandName
131    + ": Read "
132    + count
133    + " bytes from "
134    + url.getURL());
135  0 verbose(commandName
136    + ": HTTP/1.0 "
137    + url.getResponseCode()
138    + " "
139    + url.getResponseMessage());
140  0 url.disconnect();
141   
142  0 if (url.usingProxy()) {
143  0 verbose(commandName + ": This URL uses a proxy");
144    }
145    } catch (IOException e) {
146  0 out.println(e + ": " + e.getMessage());
147  0 verbose(commandName
148    + ": I/O Error : Read "
149    + count
150    + " bytes from "
151    + url.getURL());
152  0 out.println(commandName
153    + ": I/O Error "
154    + url.getResponseMessage());
155    }
156  0 output.flush();
157  0 output.close();
158    }
159   
 
160  0 toggle public final void readURL(URLConnection url) throws IOException
161    {
162  0 DataInputStream in = new DataInputStream(url.getInputStream());
163  0 printHeader(url);
164   
165  0 try {
166  0 while (true) {
167  0 System.out.println((char) in.readUnsignedByte());
168    }
169    } catch (EOFException e) {
170  0 e.printStackTrace();
171    } catch (IOException e) {
172  0 e.printStackTrace();
173    }
174    }
175   
 
176  0 toggle public final void verbose(String s)
177    {
178  0 if (verb) {
179  0 out.println(s);
180    }
181    }
182    }
183   
184    private static int tableCount = 0;
185   
 
186  0 toggle public static String processString(String g, boolean flag)
187    {
188  0 String[] array1 = new String[]{"\\s", "é", "è", "ê", "à", "ô", "ù"};
189  0 String[] array2 = new String[]{
190    "_",
191    "eacute;",
192    "eagrave;",
193    "ecicr;",
194    "aacute;",
195    "ocirc;",
196    "ugrave;"};
197   
198  0 if (flag) {
199  0 for (int i = 0; i < array1.length; i++) {
200  0 g = g.replaceAll(array1[i], array2[i]);
201    }
202  0 return g;
203    } else {
204  0 for (int i = 1; i < array1.length; i++) {
205  0 g = g.replaceAll(array2[i], array1[i]);
206    }
207  0 return g;
208    }
209    }
210   
211    int[] cols = new int[]{
212    3,
213    4,
214    4,
215    4,
216    3,
217    3,
218    3,
219    5,
220    5,
221    3,
222    5,
223    3,
224    4,
225    3,
226    3,
227    3,
228    0,
229    0,
230    0,
231    0,
232    0};
233   
234    private String documentName;
235   
236    private DocumentContext fContext;
237   
238    private Deque<DocumentContext> fContextStack = new ArrayDeque<DocumentContext>();
239   
240    private String imageTargetFolder;
241   
242    private String wikiFileDownloadBaseUrl;
243   
244    private boolean isFirstElementRendered = false;
245   
246    private int listDepth = 0;
247   
248    /**
249    * @param printer
250    */
 
251  12 toggle public TexSerializer(
252    IWikiPrinter printer,
253    String documentName,
254    String wikiFileDownloadBaseUrl,
255    String imageTargetFolderPath)
256    {
257  12 super(printer);
258  12 this.documentName = documentName;
259  12 this.imageTargetFolder = imageTargetFolderPath;
260  12 this.wikiFileDownloadBaseUrl = wikiFileDownloadBaseUrl;
261    }
262   
 
263  12 toggle @Override
264    public void beginDocument(WikiParameters params)
265    {
266    // TODO: For nested documents, call printEmptyLine()
267    // if (fContext == null) {
268    // println("\\documentclass{article}");
269    // println("\\usepackage{graphics} % for pdf, bitmapped graphics files");
270    // println("\\usepackage{graphicx} % for pdf, bitmapped graphics files");
271    // println("\\usepackage{epsfig} % for postscript graphics files");
272    // println("\\begin{document}");
273    // println();
274    // }
275  12 fContext = new DocumentContext();
276  12 fContextStack.push(fContext);
277    }
278   
 
279  0 toggle @Override
280    public void beginHeader(int headerLevel, WikiParameters params)
281    {
282  0 printEmptyLine();
283  0 print("\\");
284  0 if (headerLevel == 1) {
285  0 print("chapter{");
286  0 } else if (headerLevel < 4) {
287  0 for (int i = 1; i < headerLevel - 1; i++) {
288  0 print("sub");
289    }
290  0 print("section{");
291    } else {
292  0 print("paragraph{");
293    }
294    }
295   
 
296  17 toggle @Override
297    public void beginList(WikiParameters parameters, boolean ordered)
298    {
299  17 if (listDepth == 0) {
300  4 printEmptyLine();
301    } else {
302  13 print("\n");
303    }
304  17 if (ordered) {
305  8 print("\\begin{enumerate}");
306    } else {
307  9 print("\\begin{itemize}");
308    }
309  17 listDepth++;
310    }
311   
 
312  30 toggle @Override
313    public void beginListItem()
314    {
315  30 if (listDepth > 0) {
316  30 print("\n");
317    }
318  30 print(" \\item ");
319    }
320   
 
321  9 toggle @Override
322    public void beginParagraph(WikiParameters params)
323    {
324  9 printEmptyLine();
325    }
326   
 
327  1 toggle @Override
328    public void beginTable(WikiParameters params)
329    {
330  1 printEmptyLine();
331  1 println("\\begin{center}");
332  1 println("\\begin{footnotesize}");
333    // System.out.println("Table count: "+tableCount);
334  1 String colwidth = "3";
335  1 if (cols[tableCount] > 3) {
336  0 colwidth = "2";
337    }
338  1 print("\\begin{tabular}{");
339  5 for (int i = 0; i < cols[tableCount] + 1; i++) {
340  4 print("|p{" + colwidth + "cm}");
341    }
342  1 println("|}\\hline");
343  1 fContext.fTableHead = true;
344  1 tableCount++;
345    }
346   
 
347  6 toggle @Override
348    public void beginTableCell(boolean tableHead, WikiParameters params)
349    {
350    // String str = tableHead ? "\\textcolor{white}" : "";
351  6 String str = tableHead ? "" : "";
352   
353  6 print(str + params);
354  6 if (tableHead) {
355  2 fContext.fTableHeadCell = true;
356    }
357  6 if (!fContext.fFirstRowCell) {
358  3 print("&");
359    }
360  6 fContext.fFirstRowCell = false;
361    }
362   
 
363  3 toggle @Override
364    public void beginTableRow(WikiParameters params)
365    {
366  3 if (fContext.fTableHead)
367    // print("\\rowcolor{style@lightblue}");
368    {
369  1 print("");
370    } else {
371  2 print("");
372    }
373  3 fContext.fFirstRowCell = true;
374    }
375   
 
376  12 toggle @Override
377    public void endDocument(WikiParameters params)
378    {
379  12 fContextStack.pop();
380  12 fContext = fContextStack.peek();
381    // if (fContext == null) {
382    // println("\\end{document}");
383    // }
384    }
385   
 
386  0 toggle @Override
387    public void endHeader(int headerLevel, WikiParameters params)
388    {
389  0 println("}");
390    }
391   
 
392  17 toggle @Override
393    public void endList(WikiParameters parameters, boolean ordered)
394    {
395  17 listDepth--;
396  17 print("\n");
397  17 if (ordered) {
398  8 print("\\end{enumerate}");
399    } else {
400  9 print("\\end{itemize}");
401    }
402    }
403   
 
404  30 toggle @Override
405    public void endListItem()
406    {
407    }
408   
 
409  9 toggle @Override
410    public void endParagraph(WikiParameters params)
411    {
412    }
413   
 
414  0 toggle @Override
415    public void endQuotationLine()
416    {
417  0 println("");
418    }
419   
 
420  1 toggle @Override
421    public void endTable(WikiParameters params)
422    {
423  1 println("\\end{tabular}");
424  1 println("\\end{footnotesize}");
425  1 print("\\end{center}");
426    }
427   
 
428  6 toggle @Override
429    public void endTableCell(boolean tableHead, WikiParameters params)
430    {
431  6 if (tableHead) {
432  2 print("}");
433    }
434    }
435   
 
436  3 toggle @Override
437    public void endTableRow(WikiParameters params)
438    {
439  3 println("\\\\\\hline");
440  3 fContext.fTableHead = false;
441    }
442   
443    /**
444    * Returns an input stream with an image corresponding to the specified
445    * reference. If there is no image was found then this method should return
446    * null. This method is used to define dimensions of images used in the
447    * output. Sould be overloaded in sublcasses.
448    *
449    * @param ref the image reference
450    * @return the input stream with an image
451    */
 
452  0 toggle protected InputStream getImageInput(String ref) throws IOException
453    {
454  0 File f = new File(imageTargetFolder + ref);
455  0 if (!f.exists()) {
456   
457  0 FileOutputStream fos = new FileOutputStream(f);
458  0 String url = wikiFileDownloadBaseUrl + documentName + "/" + ref;
459  0 System.out.println("Downloading image "
460    + url
461    + " to "
462    + f.getAbsolutePath()
463    + "...");
464  0 try {
465  0 WGet wget = new WGet();
466  0 wget.fetchURL(url, fos);
467    } catch (Exception e) {
468  0 e.printStackTrace();
469    }
470  0 fos.flush();
471  0 fos.close();
472    }
473  0 FileInputStream fis = new FileInputStream(f);
474  0 return fis;
475    }
476   
477    /**
478    * Returns a two-value array with the size of the image defined by the given
479    * url
480    *
481    * @param ref the reference to the image
482    * @return a size of an image with the specified url;
483    */
 
484  0 toggle protected int[] getImageSize(String ref)
485    {
486  0 int[] result = null;
487  0 try {
488  0 InputStream input = getImageInput(ref);
489  0 if (input != null) {
490  0 int maxWidth = getMaxImageWidth();
491  0 int maxHeight = getMaxImageHeight();
492  0 return ImageUtil.getImageSize(input, maxWidth, maxHeight);
493    }
494    } catch (Exception e) {
495    }
496  0 return result;
497    }
498   
499    /**
500    * Returns maximal possible image height. This method can be overloaded in
501    * subclasses.
502    *
503    * @return the maximal possible image height
504    */
 
505  0 toggle protected int getMaxImageHeight()
506    {
507  0 return 2000;
508    }
509   
510    /**
511    * Returns maximal possible image width. This method can be overloaded in
512    * subclasses.
513    *
514    * @return the maximal possible image width
515    */
 
516  0 toggle protected int getMaxImageWidth()
517    {
518  0 return 2000;
519    }
520   
 
521  12 toggle @Override
522    protected ReferenceHandler newReferenceHandler()
523    {
524  12 return new ReferenceHandler(true, true)
525    {
526    Map<String, int[]> fImageSizes = new HashMap<String, int[]>();
527   
 
528  0 toggle @Override
529    protected void handleImage(
530    String ref,
531    String label,
532    WikiParameters params)
533    {
534   
535  0 String caption = "";
536  0 int idx = ref.indexOf("===caption===");
537  0 if (idx > 0) {
538  0 caption = ref.substring(idx + 13, ref.length() - 13);
539  0 caption = caption.replaceAll("_", " ");
540  0 caption = processString(caption, false);
541  0 ref = ref.substring(0, idx);
542    // removing extension
543  0 label = ref.substring(0, ref.length() - 4);
544    }
545   
546  0 int[] size = getImageSize(ref);
547   
548  0 println();
549  0 println("\\begin{figure}");
550  0 println("\\centering");
551   
552  0 if (size[0] > 400) {
553  0 println("\\includegraphics[width=0.95\\textwidth]{images/"
554    + ref
555    + "}");
556    } else {
557  0 println("\\includegraphics{images/" + ref + "}");
558    }
559  0 println("\\caption{" + caption + "}");
560  0 println("\\label{" + label + "}");
561  0 println("\\end{figure}");
562  0 println();
563   
564  0 if (fImageSizes.containsKey(ref)) {
565  0 size = fImageSizes.get(ref);
566    } else {
567  0 size = getImageSize(ref);
568  0 fImageSizes.put(ref, size);
569    }
570   
571    // if (size != null) {
572    // // print("\\begin{figure}[htpb]\n");
573    // String dim = "[bb=0 0 " + size[0] + " " + size[1] + "]";
574    // println("\\includegraphics" + dim + "{"
575    // + WikiPageUtil.escapeXmlString(ref) + "}");
576    // ref = ref.replaceAll("_", "-");
577    // // if (!"".equals(label)) {
578    // // println("\\caption{" + label + "}");
579    // // println("\\label{fig:" + label + "}");
580    // // }
581    // // print("\\end{figure}");
582    // }
583    }
584   
 
585  0 toggle @Override
586    protected void handleReference(
587    String ref,
588    String label,
589    WikiParameters params)
590    {
591    // String s = ref + " " + label;
592  0 int idx1 = ref.indexOf('>');
593   
594  0 if (idx1 > 0) {
595  0 label = ref.substring(0, idx1);
596  0 ref = ref.substring(idx1 + 1);
597    }
598   
599  0 ref = ref.substring(ref.indexOf('.') + 1);
600  0 print(texClean(label) + "~(\\ref{" + ref + "})");
601    // print(texClean(ref)+ texClean(label));
602    // print(" (");
603    // print(texClean(ref));
604    // print(")");
605    // print("~\ref{"+ref+"}");
606    }
607    };
608    }
609   
 
610  0 toggle @Override
611    public void onEscape(String str)
612    {
613  0 print(str);
614    }
615   
 
616  0 toggle @Override
617    public void onLineBreak()
618    {
619  0 println("\\newline");
620    }
621   
 
622  0 toggle @Override
623    public void onNewLine()
624    {
625  0 println("");
626    }
627   
 
628  46 toggle @Override
629    public void onSpace(String str)
630    {
631  46 print(str);
632    }
633   
 
634  0 toggle @Override
635    public void onSpecialSymbol(String str)
636    {
637   
638  0 if (str.equals("#")) {
639  0 print("\\_\\_");
640  0 return;
641    }
642   
643  0 if (str.equals("&")) {
644  0 print("\\&");
645  0 return;
646    }
647   
648  0 if (str.equals("$")) {
649  0 print("\\$");
650  0 return;
651    }
652   
653  0 if (str.equals("%")) {
654  0 print("\\%");
655  0 return;
656    }
657   
658  0 if (!str.equals("}") && !str.equals("{")) {
659  0 print(str);
660    }
661    }
662   
 
663  88 toggle @Override
664    public void onWord(String str)
665    {
666  88 str = texClean(str);
667  88 if (fContext.fTableHeadCell) {
668  2 print("{\\bf ");
669  2 fContext.fTableHeadCell = false;
670    }
671  88 print(str);
672    }
673   
 
674  2 toggle @Override
675    public void onVerbatimInline(String str, WikiParameters params)
676    {
677  2 print("\\begin{verbatim}");
678  2 print(str);
679  2 print("\\end{verbatim}");
680    }
681   
 
682  1 toggle @Override
683    public void onVerbatimBlock(String str, WikiParameters params)
684    {
685  1 printEmptyLine();
686  1 onVerbatimInline(str, params);
687    }
688   
 
689  88 toggle public String texClean(String str)
690    {
691   
692  88 str = str.replace("_", "\\_");
693  88 str = str.replace("#", "\\#");
694  88 str = str.replace("$", "\\$");
695   
696  88 return str;
697    }
698   
 
699  15 toggle private void printEmptyLine()
700    {
701  15 if (this.isFirstElementRendered) {
702  3 print("\n\n");
703    } else {
704  12 this.isFirstElementRendered = true;
705    }
706    }
707    }