Java tutorial
/** * MicroUnits - Pauses Analysis of XML files generated by Translog II software. * For Translog II details See <http://bridge.cbs.dk/platform/?q=Translog-II> * * Copyright (C) 2014 Gabriel Ed. da Silva * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Model; import static Model.StringTreatment.getFontString; import static Model.StringTreatment.removeExtensionsPdf; import static Model.StringTreatment.removeExtensionsXml; import static Model.StringTreatment.replace; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.FontSelector; import com.itextpdf.text.pdf.PdfWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; /** * @author Gabriel Ed. da Silva */ public class MyPdfDocument { private static final int BOTH = 0; private static final int LINEARPROTOCOL = 1; private static final int MICROUNITSWITHFIXATIONS = 2; private MyPdfDocument() { } /** * Gets a object instance for MyPdfDocument * Recupera uma instncia de objeto do MyPdfDocument * @return Instance */ public static MyPdfDocument getInstance() { return MyPdfDocumentHolder.INSTANCE; } private static class MyPdfDocumentHolder { private static final MyPdfDocument INSTANCE = new MyPdfDocument(); } /** * Create a pdf file * Cria um arquivo pdf * * @param path Directory to Parse * @param file PDF File name * @param pause Time between pauses * @param type 0 - Both, 1 - Linear Protocol, 2 - fixation * @throws java.lang.Exception Exception */ public void create(String path, String file, Integer pause, Integer type) throws Exception { try { File dir = new File(path); String[] filename = dir.list(); if (filename == null) { return; } switch (type) { case BOTH: create(filename, path, file, pause); break; case LINEARPROTOCOL: createLinearProtocol(filename, path, file, pause); break; case MICROUNITSWITHFIXATIONS: createfixation(filename, path, file, pause); break; default: throw new Exception("Invalid type"); } } catch (Exception ex) { throw new Exception(ex.getMessage()); } } private void create(String[] filename, String path, String file, Integer pause) throws Exception { ArrayList<ArrayList<String>> stList1 = new ArrayList<>(); // MicroUnits with Fixation ArrayList<ArrayList<String>> stList2 = new ArrayList<>(); // Linear Protocol String docName; /** * Gets all xml files in a directory and parses them * each file is writing in a different pdf file * * Recupera todos os arquivos xml de um diretrio e os processa, em * seguida cada arquivo escrito em arquivo pdf diferente */ for (String st : filename) { if (st.endsWith(".xml")) { MyDoc myDoc = getMyDoc(path, st); /** * Clears the list to always have the title in first position * Limpa a lista para sempre ter o ttulo na primeira posio */ stList1.clear(); stList1.add(myDoc.pausefixationAnalysis(pause)); /** * Removes the file extensions and Concatenates the pdf title * with xml file name, the final name will be a concatenation * of them plus ".pdf". * * Remove a exteno do arquivo e concatena o ttulo do arquivo * pdf ao ttulo do arquivo xml, o nome final ser a concatenao * deles acrescido de ".pdf" * * Example / Exemplo : * * file = "mypdf.pdf" * st = "Example12345.xml" * final = "mypdfExample12345.pdf" */ docName = removeExtensionsPdf(file) + removeExtensionsXml(st).toUpperCase() + ".pdf"; /** * Writes a pdf file - MicroUnits with PDF type. * Escreve um arquivo PDF - Tipo PDF com MicroUnits. */ stList1.get(0).set(0, removeExtensionsXml(st)); write(stList1, docName); /** * Temp is used to change file title * A tempo utilizada para modificar o ttulo do documento */ ArrayList<String> temp = myDoc.pauseAnalysis(pause); temp.set(0, removeExtensionsXml(st)); stList2.add(temp); } } /** * Write the PDF - Linear Protocol Type * Escreve o arquivo PDF - tipo protocolo linear */ if (!stList2.isEmpty()) { write(stList2, file + ".pdf"); } } /** * Create a basic pdf file with Linear Protocol only * Cria um arquivo pdf bsico com apenas o protocolo linear */ private void createLinearProtocol(String[] filename, String path, String file, Integer pause) throws Exception { ArrayList<ArrayList<String>> stList = new ArrayList<>(); /** * Gets all xml files in a directory and parses them * Recupera todos os arquivos xml em um diretrio e os processa */ for (String st : filename) { if (st.endsWith(".xml")) { MyDoc myDoc = getMyDoc(path, st); /** * Temp is used to change file title * A tempo utilizada para modificar o ttulo do documento */ ArrayList<String> temp = myDoc.pauseAnalysis(pause); temp.set(0, removeExtensionsXml(st)); stList.add(temp); } } /** * Write the PDF * Escreve o arquivo PDF */ if (!stList.isEmpty()) { write(stList, file + ".pdf"); } } /** * Create a pdf file with fixation parsing * Cria um arquivo pdf com processamento de fixaes */ private void createfixation(String[] filename, String path, String file, Integer pause) throws Exception { ArrayList<ArrayList<String>> stList = new ArrayList<>(); String docName; /** * Gets all xml files in a directory and parses them * each file is writing in a different pdf file * * Recupera todos os arquivos xml de um diretrio e os processa, em * seguida cada arquivo escrito em arquivo pdf diferente */ for (String st : filename) { if (st.endsWith(".xml")) { MyDoc myDoc = getMyDoc(path, st); /** * Clears the list to always have the title in first position * Limpa a lista para sempre ter o ttula na primeira posio */ stList.clear(); stList.add(myDoc.pausefixationAnalysis(pause)); /** * Removes the file extensions and Concatenates the pdf title * with xml file name, the final name will be a concatenation * of them plus ".pdf". * * Remove a exteno do arquivo e concatena o ttulo do arquivo * pdf ao ttulo do arquivo xml, o nome final ser a concatenao * deles acrescido de ".pdf" * * Example / Exemplo : * * file = "mypdf.pdf" * st = "Example12345.xml" * final = "mypdfExample12345.pdf" */ docName = removeExtensionsPdf(file) + removeExtensionsXml(st).toUpperCase() + ".pdf"; /** * Writes a pdf file * Escreve o arquivo pdf. */ stList.get(0).set(0, removeExtensionsXml(st)); write(stList, docName); } } } /** * Write the pdf file * Escreve o arquivo pdf */ private void write(ArrayList<ArrayList<String>> stList, String filename) throws DocumentException, FileNotFoundException, UnsupportedEncodingException { Document document = null; try { document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); MyFontSelector myFontSelector = MyFontSelector.getInstance(); FontSelector fontSelector; Phrase phrase; for (ArrayList<String> stL : stList) { fontSelector = myFontSelector.getFontSelector("TITLE"); phrase = fontSelector.process(stL.remove(0)); document.add(new Paragraph(phrase)); Paragraph paragraph = new Paragraph(); addEmptyLine(paragraph, 1); for (String st : stL) { fontSelector = myFontSelector.getFontSelector(getFontString(st)); /** * In Windows we have some problems with Latin characters * and we need to forces the encoding to UFT8 * * No Windows tivemos alguns problemas com caracteres latinos * e foi necessrio forar a codificao para UTF8 */ if (isWindows()) { st = new String(st.getBytes(), "UTF8"); } st = replace(st); phrase = fontSelector.process(st); paragraph.add(phrase); } document.add(paragraph); document.newPage(); } } catch (DocumentException ex) { throw new DocumentException("Read error"); } catch (FileNotFoundException ex) { throw new FileNotFoundException("File [" + filename + "] not found"); } finally { if (document != null) { document.close(); } } } /** * Add a empty line * Adiciona uma linha em branco * Method addEmptyLine as seen in: http://www.vogella.com/tutorials/JavaPDF/article.html */ private void addEmptyLine(Paragraph paragraph, int number) { for (int i = 0; i < number; i++) { paragraph.add(new Paragraph(" ")); } } /** * Checks if the OS is Windows * Verifica se o sistema operacional Windows * @return True if is running in Windows */ private boolean isWindows() { return System.getProperty("os.name").startsWith("Windows"); } /** * Imprime o nome do arquivo a ser processado e realiza o processamento * Prints the file name to be parsed and do the parse * * @param path File path * @param st File name * @return MyDoc Object * @throws Exception Error */ private MyDoc getMyDoc(String path, String st) throws Exception { System.out.println("Parsing File: " + path + StringTreatment.getSlash() + st); return AnotherParse.parseDocument(path + StringTreatment.getSlash() + st); } }