View Javadoc

1   /**
2    * 
3    */
4   package sk.stuba.fiit.foo07.genex.export;
5   
6   import java.io.File;
7   import java.io.FileOutputStream;
8   import java.io.IOException;
9   import java.io.OutputStreamWriter;
10  import java.io.StringWriter;
11  import java.nio.charset.Charset;
12  import java.sql.Connection;
13  import java.sql.SQLException;
14  import java.text.DecimalFormat;
15  import java.util.ArrayList;
16  import java.util.Collections;
17  import java.util.Hashtable;
18  import java.util.Iterator;
19  
20  import org.apache.velocity.Template;
21  import org.apache.velocity.VelocityContext;
22  import org.apache.velocity.app.VelocityEngine;
23  import org.apache.velocity.exception.ParseErrorException;
24  import org.apache.velocity.exception.ResourceNotFoundException;
25  
26  import sk.stuba.fiit.foo07.genex.beans.Answer;
27  import sk.stuba.fiit.foo07.genex.beans.ExportAnswer;
28  import sk.stuba.fiit.foo07.genex.beans.ExportPicture;
29  import sk.stuba.fiit.foo07.genex.beans.ExportQuestion;
30  import sk.stuba.fiit.foo07.genex.beans.Picture;
31  import sk.stuba.fiit.foo07.genex.beans.QuestionPoints;
32  import sk.stuba.fiit.foo07.genex.beans.QuestionType;
33  import sk.stuba.fiit.foo07.genex.beans.Test;
34  import sk.stuba.fiit.foo07.genex.dao.AnswerDaoDerby;
35  import sk.stuba.fiit.foo07.genex.dao.PictureDaoDerby;
36  import sk.stuba.fiit.foo07.genex.dao.QuestionDaoDerby;
37  import sk.stuba.fiit.foo07.genex.dao.QuestionTypeDaoDerby;
38  import sk.stuba.fiit.foo07.genex.dao.TestDaoDerby;
39  import sk.stuba.fiit.foo07.genex.dao.UserDaoDerby;
40  
41  /**
42   * @author Radu
43   */
44  /**
45   * For tag description see User Guide.
46   */
47  
48  public class ExportLatex extends Export {
49      public ArrayList<QuestionPoints> questPointsList;
50      public ArrayList<ExportQuestion> exQuestList;
51      public ArrayList<ExportAnswer> exAnsList;
52      public ArrayList<ExportPicture> exPictureList;
53      private PictureDaoDerby PDD;
54      private QuestionDaoDerby QDD;
55      private AnswerDaoDerby ADD;
56      private UserDaoDerby UDD;
57      private QuestionTypeDaoDerby QTDD;
58      private TestDaoDerby QTD;
59      public ArrayList<Answer> ansList;
60      private String instructions = null;
61      private Test toExport;
62      private boolean permutateAnswers = true;
63      private ExportQuestion eq;
64      private QuestionPoints qp;
65      private String text;
66      private String points;
67      private String template;
68      private String answer;
69      private String date;
70      private ExportAnswer ea;
71      private Picture picture;
72      private String pointsFloat;
73      private Integer sumaInt = 0;
74      private Float sumaFloat = (float) 0.0;
75      private String group = null;
76      private DecimalFormat df;
77      private Iterator<Picture> it3;
78  
79      @Override
80      public void exportTest(Integer testId, Connection con) throws IOException {
81  
82          QDD = new QuestionDaoDerby(con);
83          ADD = new AnswerDaoDerby(con);
84          QTDD = new QuestionTypeDaoDerby(con);
85          PDD = new PictureDaoDerby(con);
86          QTD = new TestDaoDerby(con);
87          UDD = new UserDaoDerby(con);
88          // First prepare all data for velocity template
89  
90          try {
91              toExport = QTD.getTestByID(testId);
92          } catch (Exception e) {
93          }
94          questPointsList = toExport.getQuestionPoints();
95          exQuestList = new ArrayList<ExportQuestion>(questPointsList.size());
96  
97          sumaInt = 0;
98          sumaFloat = (float) 0.0;
99          Iterator<QuestionPoints> it = questPointsList.iterator();
100         while (it.hasNext()) {
101             qp = it.next();
102 
103             try {
104                 text = QDD.getQuestionByID(qp.getQuestionId()).getText();
105             } catch (SQLException e) {
106 
107                 e.printStackTrace();
108             }
109             points = new String(new Integer(qp.getPoints().intValue())
110                     .toString());
111             sumaInt += qp.getPoints().intValue();
112 
113             df = new DecimalFormat("0.#");
114 
115             pointsFloat = df.format(qp.getPoints());
116             sumaFloat += qp.getPoints();
117 
118             //TODO 
119             //pridane odchytavanie vynimky (palo)
120             try {
121                 ansList = ADD.getAnswersByQuestionID(qp.getQuestionId());
122             } catch (Exception e) {
123             }
124             if (permutateAnswers)
125                 Collections.shuffle(ansList);
126             exAnsList = new ArrayList<ExportAnswer>(5);
127             Iterator<Answer> it2 = ansList.iterator();
128             while (it2.hasNext()) {
129                 Answer a = it2.next();
130                 answer = a.getText();
131                 boolean isCorrect = a.getIsCorrect();
132 
133                 ea = new ExportAnswer(answer, isCorrect);
134                 exAnsList.add(ea);
135             }
136             ArrayList<Picture> pictureList = null; //pozor mozna chyba
137             //TODO 
138             //pridane odchytavanie vynimky (palo)
139             try {
140                 pictureList = PDD.getPicturesByQuestionID(qp.getQuestionId());
141                 exPictureList = new ArrayList<ExportPicture>(pictureList.size());
142             } catch (Exception e) {
143                 e.printStackTrace();
144             }
145             if (!pictureList.isEmpty()) {
146 
147                 Iterator<Picture> it4 = pictureList.iterator();
148                 while (it4.hasNext()) {
149                     ExportPicture ep = new ExportPicture(it4.next());
150                     if (ep.getMIMETYPE().startsWith("tex")
151                             || ep.getMIMETYPE().startsWith("ltx"))
152                         ep.setTextPicture(true);
153                     exPictureList.add(ep);
154                 }
155             }
156             eq = new ExportQuestion(qp.getQuestionId(), text, points,
157                     pointsFloat, exAnsList, exPictureList);
158             exQuestList.add(eq);
159 
160         }
161         // Now write all images of test from database to files
162         try {
163             ArrayList<Picture> pictureList = PDD.getPicturesByTestID(toExport
164                     .getTestID());
165             it3 = pictureList.iterator();
166 
167             while (it3.hasNext()) {
168 
169                 picture = it3.next();
170 
171                 FileOutputStream fos = new FileOutputStream(new File(picture
172                         .getName()));
173 
174                 fos.write(picture.getContent());
175                 fos.close();
176                 // pridat bufferovanie..
177             }
178         } catch (SQLException e1) {
179             // TODO Auto-generated catch block
180             e1.printStackTrace();
181         }
182         VelocityEngine ve = new VelocityEngine();
183         /*  next, get the Template  */
184         Template t;
185         try {
186 
187             ve.init();
188             t = ve.getTemplate("templates"
189                     + System.getProperty("file.separator") + template, "UTF8");
190 
191             /*  create a context and add data */
192             VelocityContext context = new VelocityContext();
193 
194             context.put("FILEHEADER", this.getFileHeader());
195             context.put("TESTHEADER", this.getTestHeader());
196             context.put("NAMETABLE", this.getNameTable());
197             context.put("ANSWERTABLE", this.getAnswerTable(false));
198             context.put("TESTNAME", this.getTestName());
199             context.put("TESTSUBJECT", this.getSubject());
200             context.put("TESTGROUP", this.getGroupLatex());
201             context.put("TESTCREATOR", this.getUser());
202             context.put("TESTDATE", this.getTestDate());
203             context.put("TESTINSTRUCTIONS", this.getHelloMsg());
204             context.put("CORRECTANSWERS", this.getAnswerTable(true));
205             context.put("TOTALPOINTS", this.sumaInt.toString());
206             context.put("TOTALPOINTSFLOAT", df.format(sumaFloat));
207 
208             context.put("QUESTIONLIST", exQuestList);
209 
210             /* now render the template into a StringWriter */
211             StringWriter writer = new StringWriter();
212             t.merge(context, writer);
213             /* show the World */
214             //pw = new PrintWriter(new FileOutputStream(new File("test.tex")));
215             //pw.println(writer.toString());
216             FileOutputStream f = new FileOutputStream(super.getOutputFilename());
217 
218             OutputStreamWriter osw = new OutputStreamWriter(f, Charset
219                     .forName("UTF8"));
220 
221             osw.write(writer.toString());
222             osw.flush();
223             osw.close();
224 
225             // Now get rid of text picture files
226             ArrayList<Picture> pictureList = PDD.getPicturesByTestID(toExport
227                     .getTestID());
228 
229             Iterator<ExportQuestion> exQIT = exQuestList.iterator();
230             while (exQIT.hasNext()) {
231                 Iterator<ExportPicture> it3a = exQIT.next().getPICTURELIST()
232                         .iterator();
233                 while (it3a.hasNext()) {
234 
235                     ExportPicture picture1 = it3a.next();
236                     if (picture1.getMIMETYPE().startsWith("tex")
237                             || picture1.getMIMETYPE().startsWith("ltx")) {
238 
239                         File textPicture = new File(picture1.getNAME());
240                         textPicture.delete();
241                     }
242 
243                 }
244             } // pw.flush();
245         } catch (ResourceNotFoundException e) {
246             // TODO Auto-generated catch block
247             e.printStackTrace();
248         } catch (ParseErrorException e) {
249             // TODO Auto-generated catch block
250             e.printStackTrace();
251         } catch (Exception e) {
252             // TODO Auto-generated catch block
253             e.printStackTrace();
254         }
255 
256     }
257 
258     public String getTestDate() {
259         if (date.length() == 0)
260             return new String("");
261         else
262             return new String("Dátum: " + date + "\\\\ \n");
263     }
264 
265     public String getTestName() {
266         StringBuilder testName = new StringBuilder();
267         testName.append("\\textbf{");
268         testName.append(toExport.getName());
269         testName.append("}\\\\ \n");
270         return (testName.toString());
271     }
272 
273     public String getSubject() {
274         return (new String("Predmet: " + toExport.getSubject() + "\\\\ \n"));
275 
276     }
277 
278     public String getGroupLatex() {
279         if (group.length() == 0) {
280             return (new String(""));
281         } else {
282             return (new String("Skupina: " + group + "\\\\ \n"));
283         }
284 
285     }
286 
287     //TODO pridany catch blok, pozret logiku metody
288     public String getUser() {
289 
290         try {
291             return new String("Vyucujuci: "
292                     + UDD.getTUserByID(toExport.getUserID()) + "\\\\ \n");
293         } catch (Exception e) {
294             return null;
295         }
296     }
297 
298     public String getTestHeader() {
299         StringBuilder testHeader = new StringBuilder();
300 
301         testHeader.append(getTestName());
302         testHeader.append(getSubject());
303         testHeader.append(getGroupLatex());
304         testHeader.append(getUser());
305         testHeader.append(getHelloMsg());
306 
307         return testHeader.toString();
308     }
309 
310     public String getNameTable() {
311         StringBuilder testNameTable = new StringBuilder();
312         testNameTable.append("\\begin{tabular}{|l|l|l|l|} \\hline \n");
313         testNameTable
314                 .append("\\textbf{Priezvisko:} & \\mbox{\\hspace{3cm}}& \\textbf{Os. číslo} & \\textbf{Body}\\\\[2mm] \\hline \n");
315         testNameTable.append("\\textbf{Meno:} &  &  &  \\\\[2mm] \\hline \n");
316         testNameTable.append("\\end{tabular} \n");
317         testNameTable.append("\\vspace{2mm} \\ \n");
318         return testNameTable.toString();
319     }
320 
321     public String getHelloMsg() {
322         if (instructions.length() == 0)
323             return new String("");
324         else
325             return new String(instructions + "\\ \n \\vspace{2mm} \n");
326     }
327 
328     public String getFileHeader() {
329         return new String("% " + toExport.getName()
330                 + "\n% Vygenerovane systemom Genex");
331     }
332 
333     private String writeAnswerTableToFile(int[] QuestionOrder,
334             Hashtable<Integer, ArrayList<Integer>> ChoiceAnswers,
335             int maxPossibleAnswers, boolean answers) {
336 
337         int i, j;
338         int tableStep = 5; //after each 'tableStep' rows there's a tiny jump in the table
339         StringBuilder table = new StringBuilder();
340 
341         //we have no 'choice' question
342         if (ChoiceAnswers.size() == 0) {
343             return new String(
344                     "%No AnswerTable: none single choice, multi choice or True-false question");
345 
346         }
347 
348         //Answertable beginning
349         table.append("\\begin{tabular}{|c||");
350 
351         //create column separators
352         for (i = 0; i < maxPossibleAnswers + 1; i++)
353             table.append("c|");
354 
355         table.append("} \\hline \n ");
356 
357         //answers 'a' 'b' 'c' ...
358         for (i = 97; i < maxPossibleAnswers + 97; i++)
359             table.append(" & " + (char) i);
360 
361         //formating stuff
362         table.append(" \\\\ \\hline\\hline \n");
363 
364         //write answers or just empty space into table fields
365         for (i = 0; i < ChoiceAnswers.size(); i++) {
366             table.append((QuestionOrder[i]) + " ");
367             for (j = 0; j < maxPossibleAnswers; j++) {
368                 if (answers && ChoiceAnswers.get(i).contains(j))
369                     table.append("&  X"); //write correct answers
370                 else
371                     table.append("&   "); //write empty AnswerTable
372             }
373 
374             //after each tableStep-rows make a double hline and
375             //don't make a double hline after the last line
376             if ((i + 1) % tableStep == 0 && (i + 1) != ChoiceAnswers.size())
377                 table.append("\\\\ \\hline \\hline");
378             else
379                 table.append("\\\\ \\hline");
380 
381             table.append('\n');
382         }
383 
384         //end the table
385         table.append("\\end{tabular}");
386 
387         return new String(table.toString());
388 
389     }
390 
391     public String getAnswerTable(boolean withCorrectAnswers) {
392 
393         QuestionType qt;
394         ExportQuestion question;
395         int i = 0;
396         int j = 0;
397         int numberOfChoiceQuestions = 0;
398         int maxPossibleAnswers = 0;
399         int PossibleAnswers = 0;
400         Hashtable<Integer, ArrayList<Integer>> ChoiceAnswers = new Hashtable<Integer, ArrayList<Integer>>();
401         ArrayList<Integer> correctAnswers;
402         ArrayList<ExportAnswer> a_list;
403         int[] QuestionOrder;
404 
405         QuestionOrder = new int[exQuestList.size()];
406 
407         for (i = 0; i < exQuestList.size(); i++) {
408             question = exQuestList.get(i);
409             //TODO
410             //vynimky
411             qt = null;
412             try {
413                 qt = QTDD.getQuestionTypeByQuestionID(question.getQuestionID());
414             } catch (Exception e) {
415             }
416 
417             if ("Single choice".equals(qt.getName())
418                     || "Multi choice".equals(qt.getName())
419                     || "True/False".equals(qt.getName())) {
420 
421                 a_list = question.getANSWERLIST();
422 
423                 //get maximum possible answers in test 
424                 PossibleAnswers = a_list.size();
425 
426                 if (PossibleAnswers > maxPossibleAnswers)
427                     maxPossibleAnswers = PossibleAnswers;
428 
429                 //remember order of question
430                 //questions start from 1 not 0
431                 QuestionOrder[numberOfChoiceQuestions] = i + 1;
432 
433                 correctAnswers = new ArrayList<Integer>();
434 
435                 //remember correct answers order
436                 for (j = 0; j < a_list.size(); j++)
437                     if (a_list.get(j).isCorrect()) {
438                         correctAnswers.add(j);
439                     }
440 
441                 //map question order to correct answer order 
442                 ChoiceAnswers.put(numberOfChoiceQuestions, correctAnswers);
443                 numberOfChoiceQuestions++;
444 
445             }
446 
447         }
448 
449         //write table to output
450         return new String(writeAnswerTableToFile(QuestionOrder, ChoiceAnswers,
451                 maxPossibleAnswers, withCorrectAnswers));
452 
453     }
454 
455     public String getInstructions() {
456         return instructions;
457     }
458 
459     public void setInstructions(String helloMesage) {
460         this.instructions = helloMesage;
461     }
462 
463     public boolean isPermutateAnswers() {
464         return permutateAnswers;
465     }
466 
467     public void setPermutateAnswers(boolean permutateAnswers) {
468         this.permutateAnswers = permutateAnswers;
469     }
470 
471     public String getTemplate() {
472         return template;
473     }
474 
475     public void setTemplate(String template) {
476         this.template = template;
477     }
478 
479     public void setGroup(String group) {
480         this.group = group;
481     }
482 
483     public String getGroup() {
484         return group;
485     }
486 
487     public String getDate() {
488         return date;
489     }
490 
491     public void setDate(String date) {
492         this.date = date;
493     }
494 
495 }