OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 156 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.generationDoc;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
17
import org.openconcerto.erp.core.common.ui.PreviewFrame;
156 ilm 18
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
19
import org.openconcerto.erp.core.sales.quote.report.PaypalStamper;
21 ilm 20
import org.openconcerto.erp.generationDoc.element.TypeModeleSQLElement;
156 ilm 21
import org.openconcerto.erp.preferences.PayPalPreferencePanel;
61 ilm 22
import org.openconcerto.erp.storage.CloudStorageEngine;
25 ilm 23
import org.openconcerto.erp.storage.StorageEngine;
24
import org.openconcerto.erp.storage.StorageEngines;
19 ilm 25
import org.openconcerto.openoffice.OOUtils;
18 ilm 26
import org.jopendocument.link.Component;
27
import org.openconcerto.sql.Configuration;
28
import org.openconcerto.sql.element.SQLElement;
29
import org.openconcerto.sql.model.SQLBase;
30
import org.openconcerto.sql.model.SQLRow;
144 ilm 31
import org.openconcerto.sql.model.SQLRowAccessor;
156 ilm 32
import org.openconcerto.sql.preferences.SQLPreferences;
18 ilm 33
import org.openconcerto.utils.ExceptionHandler;
144 ilm 34
import org.openconcerto.utils.cc.ITransformer;
18 ilm 35
 
156 ilm 36
import java.awt.GraphicsEnvironment;
132 ilm 37
import java.awt.print.PrinterJob;
25 ilm 38
import java.io.BufferedInputStream;
18 ilm 39
import java.io.File;
25 ilm 40
import java.io.FileInputStream;
156 ilm 41
import java.io.FileNotFoundException;
19 ilm 42
import java.io.IOException;
156 ilm 43
import java.io.InputStream;
44
import java.io.InputStreamReader;
45
import java.io.OutputStream;
18 ilm 46
import java.lang.Thread.UncaughtExceptionHandler;
156 ilm 47
import java.net.HttpURLConnection;
48
import java.net.URL;
49
import java.net.URLConnection;
50
import java.net.URLEncoder;
51
import java.nio.charset.StandardCharsets;
132 ilm 52
import java.util.Arrays;
18 ilm 53
import java.util.HashMap;
25 ilm 54
import java.util.List;
18 ilm 55
import java.util.Map;
156 ilm 56
import java.util.StringJoiner;
25 ilm 57
import java.util.concurrent.Callable;
58
import java.util.concurrent.ExecutionException;
18 ilm 59
import java.util.concurrent.ExecutorService;
60
import java.util.concurrent.Future;
61
import java.util.concurrent.LinkedBlockingQueue;
132 ilm 62
import java.util.concurrent.ThreadFactory;
18 ilm 63
import java.util.concurrent.ThreadPoolExecutor;
64
import java.util.concurrent.TimeUnit;
65
 
132 ilm 66
import javax.swing.JOptionPane;
18 ilm 67
 
68
import org.jopendocument.model.OpenDocument;
69
 
70
public abstract class SheetXml {
71
 
144 ilm 72
    private ITransformer<List<SQLRowAccessor>, List<SQLRowAccessor>> postProcess = null;
73
 
74
    public ITransformer<List<SQLRowAccessor>, List<SQLRowAccessor>> getPostProcess() {
75
        return postProcess;
76
    }
77
 
93 ilm 78
    // INSTEAD USE THE PREF IN L.O. CALC --> Formules, toujours recalculer
79
    private boolean refreshFormulasRequired = false;
80
 
25 ilm 81
    // return null to keep default value
82
    public interface StorageDirs {
83
        public File getDocumentOutputDirectory(SheetXml sheet);
84
 
85
        public File getPDFOutputDirectory(SheetXml sheet);
86
 
87
        public String getStoragePath(SheetXml sheet);
88
    }
89
 
144 ilm 90
    /**
91
     * Post process line
92
     *
93
     * @param postProcess
94
     */
95
    public void setPostProcess(ITransformer<List<SQLRowAccessor>, List<SQLRowAccessor>> postProcess) {
96
        this.postProcess = postProcess;
97
    }
98
 
25 ilm 99
    private static StorageDirs STORAGE_DIRS;
100
 
101
    // allow to redirect all documents
102
    public static void setStorageDirs(StorageDirs d) {
103
        STORAGE_DIRS = d;
104
    }
105
 
106
    public static final String DEFAULT_PROPERTY_NAME = "Default";
18 ilm 107
    protected SQLElement elt;
108
 
109
    // nom de l'imprimante à utiliser
110
    protected String printer;
111
 
112
    // id
113
    protected SQLRow row;
114
 
19 ilm 115
    // Language du document
116
    protected SQLRow rowLanguage;
117
 
18 ilm 118
    protected static final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
119
 
120
    // single threaded and kill its thread after 3 seconds (to allow the program to exit)
132 ilm 121
    protected static final ExecutorService runnableQueue = new ThreadPoolExecutor(0, 1, 3L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
18 ilm 122
 
132 ilm 123
        @Override
124
        public Thread newThread(Runnable r) {
125
            final Thread res = new Thread(r);
126
            res.setUncaughtExceptionHandler(DEFAULT_HANDLER);
127
 
128
            return res;
129
        }
130
    });
131
 
18 ilm 132
    protected static UncaughtExceptionHandler DEFAULT_HANDLER = new UncaughtExceptionHandler() {
133
        @Override
134
        public void uncaughtException(Thread t, Throwable e) {
19 ilm 135
            ExceptionHandler.handle("Erreur de generation", e);
18 ilm 136
        }
137
    };
138
 
25 ilm 139
    public final SQLElement getElement() {
140
        return this.elt;
18 ilm 141
    }
142
 
25 ilm 143
    /**
144
     * Show, print and export the document to PDF. This method is asynchronous, but is executed in a
145
     * single threaded queue shared with createDocument
132 ilm 146
     */
25 ilm 147
    public Future<SheetXml> showPrintAndExportAsynchronous(final boolean showDocument, final boolean printDocument, final boolean exportToPDF) {
148
        final Callable<SheetXml> c = new Callable<SheetXml>() {
149
            @Override
150
            public SheetXml call() throws Exception {
151
                showPrintAndExport(showDocument, printDocument, exportToPDF);
152
                return SheetXml.this;
153
            }
154
        };
155
        return runnableQueue.submit(c);
18 ilm 156
 
25 ilm 157
    }
158
 
132 ilm 159
    public static Future<?> submitInQueue(final Runnable r) {
160
 
161
        return runnableQueue.submit(r);
94 ilm 162
    }
163
 
61 ilm 164
    public void showPrintAndExport(final boolean showDocument, final boolean printDocument, boolean exportToPDF) {
65 ilm 165
        showPrintAndExport(showDocument, printDocument, exportToPDF, Boolean.getBoolean("org.openconcerto.oo.useODSViewer"), false);
61 ilm 166
    }
167
 
25 ilm 168
    /**
169
     * Show, print and export the document to PDF. This method is synchronous
132 ilm 170
     */
65 ilm 171
    public void showPrintAndExport(final boolean showDocument, final boolean printDocument, boolean exportToPDF, boolean useODSViewer, boolean exportPDFSynch) {
25 ilm 172
 
173
        final File generatedFile = getGeneratedFile();
174
        final File pdfFile = getGeneratedPDFFile();
175
        if (generatedFile == null || !generatedFile.exists()) {
132 ilm 176
            JOptionPane.showMessageDialog(null, "Fichier généré manquant : " + generatedFile);
18 ilm 177
            return;
178
        }
179
 
180
        try {
61 ilm 181
            if (!useODSViewer) {
174 ilm 182
                if (exportToPDF || printDocument) {
183
                    final Component doc = ComptaPropsConfiguration.getOOConnexion().loadDocument(generatedFile, !showDocument);
18 ilm 184
 
174 ilm 185
                    if (printDocument) {
186
                        Map<String, Object> map = new HashMap<String, Object>();
187
                        map.put("Name", this.printer);
188
                        doc.printDocument(map);
189
                    }
190
                    if (exportToPDF) {
191
                        doc.saveToPDF(pdfFile).get();
192
                    }
193
                    if (!showDocument) {
194
                        doc.close();
195
                    }
196
                } else {
197
                    openDocument(false);
18 ilm 198
                }
199
            } else {
25 ilm 200
                final OpenDocument doc = new OpenDocument(generatedFile);
18 ilm 201
 
25 ilm 202
                if (showDocument) {
18 ilm 203
                    showPreviewDocument();
204
                }
25 ilm 205
                if (printDocument) {
18 ilm 206
                    // Print !
28 ilm 207
                    DefaultNXDocumentPrinter printer = new DefaultNXDocumentPrinter();
132 ilm 208
                    printer.print(Arrays.asList(doc));
18 ilm 209
                }
61 ilm 210
 
211
                // FIXME Profiler pour utiliser moins de ram --> ex : demande trop de mémoire pour
212
                // faire
213
                // un grand livre KD
25 ilm 214
                if (exportToPDF) {
18 ilm 215
 
25 ilm 216
                    Thread t = new Thread(new Runnable() {
217
 
218
                        @Override
219
                        public void run() {
67 ilm 220
                            createPDF(generatedFile, pdfFile, doc, getStoragePath());
65 ilm 221
 
67 ilm 222
                        }
25 ilm 223
 
65 ilm 224
                    }, "convert and upload to pdf");
225
 
226
                    t.setDaemon(true);
25 ilm 227
                    t.start();
65 ilm 228
                    if (exportPDFSynch) {
229
                        t.join();
230
                    }
25 ilm 231
                }
18 ilm 232
            }
233
 
234
        } catch (Exception e) {
156 ilm 235
            ExceptionHandler.handle("Impossible de charger le document OpenOffice " + pdfFile.getAbsolutePath() + "(viewer : " + useODSViewer + ")", e);
18 ilm 236
        }
237
    }
238
 
73 ilm 239
    MetaDataSheet meta;
240
 
241
    /**
242
     * MetaData à inclure lors de la génération
243
     *
244
     * @param meta
245
     */
246
    public void setMetaGeneration(MetaDataSheet meta) {
247
        this.meta = meta;
248
    }
249
 
250
    /**
251
     * MetaData à inclure lors de la génération
252
     *
253
     * @param meta
254
     */
255
 
256
    public MetaDataSheet getMetaGeneration() {
257
        return this.meta;
258
    }
259
 
156 ilm 260
    public void createPDF(final File generatedFile, final File pdfFile, final OpenDocument doc, String storagePath) {
80 ilm 261
        if (pdfFile == null) {
262
            throw new IllegalArgumentException("null PDF file");
263
        }
67 ilm 264
        try {
156 ilm 265
            if (VenteFactureXmlSheet.TEMPLATE_ID.equals(getDefaultTemplateId())) {
266
                final SQLPreferences prefs = SQLPreferences.getMemCached(getElement().getTable().getDBRoot());
267
                if (prefs.getBoolean(PayPalPreferencePanel.PAYPAL_INVOICE, false)) {
268
                    try {
269
                        final File inFile = File.createTempFile("oc_", pdfFile.getName());
270
                        SheetUtils.convert2PDF(doc, inFile);
271
                        PaypalStamper s = new PaypalStamper();
272
                        int x = prefs.getInt(PayPalPreferencePanel.PAYPAL_INVOICE_X, 0);
273
                        int y = prefs.getInt(PayPalPreferencePanel.PAYPAL_INVOICE_Y, 0);
274
 
275
                        // Reference
276
                        String ref = getSQLRow().getString("NUMERO");
277
                        // Montant : ex : 10.55
278
                        long cents = getSQLRow().getLong("NET_A_PAYER");
279
                        String amount = cents / 100 + "." + cents % 100;
280
                        // Devise
281
                        // TODO : autres devises
282
                        String currency = "EUR";
283
                        // POST
284
                        final URL url = new URL("https://cloud.openconcerto.org/payment");
285
                        final URLConnection con = url.openConnection();
286
                        final HttpURLConnection http = (HttpURLConnection) con;
287
                        http.setRequestMethod("POST");
288
                        http.setDoOutput(true);
289
                        http.setDefaultUseCaches(false);
290
 
291
                        String hyperlink = null;
292
                        // x-www-form-urlencoded
293
                        final Map<String, String> arguments = new HashMap<>();
294
                        arguments.put("pI", prefs.get(PayPalPreferencePanel.PAYPAL_CLIENTID, ""));
295
                        arguments.put("pS", prefs.get(PayPalPreferencePanel.PAYPAL_SECRET, ""));
296
                        arguments.put("ref", ref);
297
                        arguments.put("amount", amount);
298
                        arguments.put("currency", currency);
299
                        arguments.put("type", "paypal");
300
                        final StringJoiner sj = new StringJoiner("&");
301
                        for (Map.Entry<String, String> entry : arguments.entrySet()) {
302
                            sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8"));
303
                        }
304
                        final String postData = sj.toString();
305
                        System.err.println("SheetXml.createPDF() " + postData);
306
                        byte[] out = postData.getBytes(StandardCharsets.UTF_8);
307
                        int length = out.length;
308
                        http.setFixedLengthStreamingMode(length);
309
                        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
310
                        http.connect();
311
                        try (OutputStream os = http.getOutputStream()) {
312
                            os.write(out);
313
                        }
314
                        if (http.getResponseCode() != 401) {
315
 
316
                            InputStream is = http.getInputStream();
317
                            InputStreamReader isr = new InputStreamReader(is);
318
 
319
                            int numCharsRead;
320
                            char[] charArray = new char[1024];
321
                            StringBuilder sb = new StringBuilder();
322
                            while ((numCharsRead = isr.read(charArray)) > 0) {
323
                                sb.append(charArray, 0, numCharsRead);
324
                            }
325
                            //
326
                            hyperlink = sb.toString();
327
                        }
328
                        s.addLink(inFile, pdfFile, x, y, hyperlink);
329
                    } catch (Exception e) {
330
                        e.printStackTrace();
331
                        SheetUtils.convert2PDF(doc, pdfFile);
332
                    }
333
 
334
                } else {
335
                    SheetUtils.convert2PDF(doc, pdfFile);
336
                }
337
            } else {
338
                SheetUtils.convert2PDF(doc, pdfFile);
339
            }
340
 
67 ilm 341
        } catch (Throwable e) {
80 ilm 342
            ExceptionHandler.handle("Impossible de créer le PDF " + pdfFile.getAbsolutePath(), e);
67 ilm 343
        }
80 ilm 344
        if (!pdfFile.canRead()) {
345
            ExceptionHandler.handle("Le fichier PDF " + pdfFile.getAbsolutePath() + " ne peut être lu.");
346
        }
67 ilm 347
        List<StorageEngine> engines = StorageEngines.getInstance().getActiveEngines();
348
        for (StorageEngine storageEngine : engines) {
349
            if (storageEngine.isConfigured() && storageEngine.allowAutoStorage()) {
80 ilm 350
                final String path = storagePath;
67 ilm 351
                try {
352
                    storageEngine.connect();
353
                    final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(pdfFile));
354
                    storageEngine.store(inStream, path, pdfFile.getName(), true);
355
                    inStream.close();
356
                    storageEngine.disconnect();
357
                } catch (IOException e) {
80 ilm 358
                    ExceptionHandler.handle("Impossible de sauvegarder le PDF " + pdfFile.getAbsolutePath() + " vers " + path + "(" + storageEngine + ")", e);
67 ilm 359
                }
360
                if (storageEngine instanceof CloudStorageEngine) {
361
                    try {
362
                        storageEngine.connect();
363
                        final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(generatedFile));
364
                        storageEngine.store(inStream, path, generatedFile.getName(), true);
365
                        inStream.close();
366
                        storageEngine.disconnect();
367
                    } catch (IOException e) {
80 ilm 368
                        ExceptionHandler.handle("Impossible de sauvegarder le fichier généré " + generatedFile.getAbsolutePath() + " vers " + path + "(" + storageEngine + ")", e);
67 ilm 369
                    }
370
                }
371
            }
372
        }
373
    }
374
 
25 ilm 375
    public abstract String getDefaultTemplateId();
21 ilm 376
 
25 ilm 377
    /**
378
     * Path of the directory used for storage. Ex: Devis/2010
132 ilm 379
     */
25 ilm 380
    public final String getStoragePath() {
381
        final String res = STORAGE_DIRS == null ? null : STORAGE_DIRS.getStoragePath(this);
382
        if (res != null)
383
            return res;
384
        else
385
            return this.getStoragePathP();
386
    }
387
 
388
    public final File getDocumentOutputDirectory() {
389
        final File res = STORAGE_DIRS == null ? null : STORAGE_DIRS.getDocumentOutputDirectory(this);
390
        if (res != null)
391
            return res;
392
        else
393
            return this.getDocumentOutputDirectoryP();
394
    }
395
 
396
    public final File getPDFOutputDirectory() {
397
        final File res = STORAGE_DIRS == null ? null : STORAGE_DIRS.getPDFOutputDirectory(this);
398
        if (res != null)
399
            return res;
400
        else
401
            return this.getPDFOutputDirectoryP();
402
    }
403
 
404
    protected abstract String getStoragePathP();
405
 
406
    protected abstract File getDocumentOutputDirectoryP();
407
 
408
    protected abstract File getPDFOutputDirectoryP();
409
 
410
    /**
411
     * Name of the generated document (without extension), do not rely on this name.
412
     *
413
     * Use getGeneratedFile().getName() to get the generated file name.
132 ilm 414
     */
25 ilm 415
    public abstract String getName();
416
 
417
    /**
418
     * @return the template id for this template (ex: "sales.quote")
132 ilm 419
     */
25 ilm 420
    public String getTemplateId() {
421
        if (this.row != null && this.row.getTable().getFieldsName().contains("ID_MODELE")) {
151 ilm 422
            if (row.getObject("ID_MODELE") == null || row.isForeignEmpty("ID_MODELE")) {
21 ilm 423
                TypeModeleSQLElement typeModele = Configuration.getInstance().getDirectory().getElement(TypeModeleSQLElement.class);
25 ilm 424
                String modele = typeModele.getTemplateMapping().get(this.row.getTable().getName());
21 ilm 425
                if (modele == null) {
426
                    System.err.println("No default modele in table TYPE_MODELE for table " + this.row.getTable().getName());
427
                    Thread.dumpStack();
25 ilm 428
                    return getDefaultTemplateId();
21 ilm 429
                } else {
430
                    return modele;
431
                }
432
            } else {
90 ilm 433
                SQLRow rowModele = this.row.getForeignRow("ID_MODELE");
21 ilm 434
                return rowModele.getString("NOM");
435
            }
436
        }
25 ilm 437
        return getDefaultTemplateId();
21 ilm 438
    }
439
 
25 ilm 440
    public abstract Future<SheetXml> createDocumentAsynchronous();
18 ilm 441
 
25 ilm 442
    public void createDocument() throws InterruptedException, ExecutionException {
443
        createDocumentAsynchronous().get();
18 ilm 444
    }
445
 
25 ilm 446
    /**
447
     * get the File that is, or must be generated.
448
     *
449
     * @return a file (not null)
132 ilm 450
     */
25 ilm 451
    public abstract File getGeneratedFile();
18 ilm 452
 
25 ilm 453
    public File getGeneratedPDFFile() {
454
        return SheetUtils.getFileWithExtension(getGeneratedFile(), ".pdf");
18 ilm 455
    }
456
 
19 ilm 457
    public SQLRow getRowLanguage() {
458
        return this.rowLanguage;
459
    }
460
 
461
    public String getReference() {
462
        return "";
463
    }
464
 
18 ilm 465
    /**
25 ilm 466
     * Creates the document if needed and returns the generated file (OpenDocument)
132 ilm 467
     */
25 ilm 468
    public File getOrCreateDocumentFile() throws Exception {
469
        File f = getGeneratedFile();
470
        if (!f.exists()) {
471
            return createDocumentAsynchronous().get().getGeneratedFile();
18 ilm 472
        } else {
25 ilm 473
            return f;
18 ilm 474
        }
475
    }
476
 
25 ilm 477
    /**
41 ilm 478
     * Creates the document if needed and returns the generated file (OpenDocument)
479
     *
480
     * @param createRecent true for recreate the pdf document if older than ods
481
     * @return
482
     * @throws Exception
483
     *
132 ilm 484
     */
41 ilm 485
    public File getOrCreatePDFDocumentFile(boolean createRecent) throws Exception {
61 ilm 486
        return getOrCreatePDFDocumentFile(createRecent, Boolean.getBoolean("org.openconcerto.oo.useODSViewer"));
487
    }
488
 
489
    public File getOrCreatePDFDocumentFile(boolean createRecent, boolean useODSViewer) throws Exception {
41 ilm 490
        File f = getGeneratedPDFFile();
491
        if (!f.exists()) {
492
            getOrCreateDocumentFile();
65 ilm 493
            showPrintAndExport(false, false, true, useODSViewer, true);
41 ilm 494
            return f;
495
        } else {
496
            File fODS = getOrCreateDocumentFile();
497
            if (fODS.lastModified() > f.lastModified()) {
65 ilm 498
                showPrintAndExport(false, false, true, useODSViewer, true);
41 ilm 499
            }
500
            return f;
501
        }
502
    }
503
 
504
    /**
25 ilm 505
     * Open the document with the native application
506
     *
507
     * @param synchronous
132 ilm 508
     */
25 ilm 509
    public void openDocument(boolean synchronous) {
510
        Runnable r = new Runnable() {
511
 
512
            @Override
513
            public void run() {
514
                File f;
515
                try {
516
                    f = getOrCreateDocumentFile();
156 ilm 517
                    if (f != null && f.exists()) {
518
                        OOUtils.open(f);
519
                    } else {
520
                        if (!GraphicsEnvironment.isHeadless()) {
521
                            if (f != null) {
522
                                JOptionPane.showMessageDialog(null, "Le fichier " + f.getAbsolutePath() + " est manquant");
523
                            } else {
524
                                JOptionPane.showMessageDialog(null, "Fichier manquant");
525
                            }
526
                        } else {
527
                            if (f != null) {
528
                                throw new FileNotFoundException(f.getAbsolutePath() + " missing");
529
                            } else {
530
                                throw new NullPointerException("null document");
531
                            }
532
                        }
533
                    }
25 ilm 534
                } catch (Exception e) {
535
                    ExceptionHandler.handle("Impossible d'ouvrir le document.", e);
536
                }
18 ilm 537
            }
25 ilm 538
        };
539
        if (synchronous) {
540
            r.run();
18 ilm 541
        } else {
25 ilm 542
            Thread thread = new Thread(r, "openDocument: " + getGeneratedFile().getAbsolutePath());
543
            thread.setDaemon(true);
544
            thread.start();
18 ilm 545
        }
546
 
547
    }
548
 
25 ilm 549
    public void showPreviewDocument() throws Exception {
174 ilm 550
        showPreviewDocument(null, null);
551
    }
552
 
553
    public void showPreviewDocument(String actionName, Runnable r) throws Exception {
25 ilm 554
        File f = null;
555
        f = getOrCreateDocumentFile();
174 ilm 556
        PreviewFrame.show(f, actionName, r);
18 ilm 557
    }
558
 
132 ilm 559
    public void printDocument() {
560
        printDocument(null);
18 ilm 561
    }
562
 
132 ilm 563
    public void printDocument(PrinterJob job) {
18 ilm 564
 
565
        try {
25 ilm 566
            final File f = getOrCreateDocumentFile();
567
 
18 ilm 568
            if (!Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
569
                final Component doc = ComptaPropsConfiguration.getOOConnexion().loadDocument(f, true);
149 ilm 570
                doc.printDocument(job);
18 ilm 571
                doc.close();
572
            } else {
573
                // Load the spreadsheet.
574
                final OpenDocument doc = new OpenDocument(f);
575
                // Print !
576
                DefaultNXDocumentPrinter printer = new DefaultNXDocumentPrinter();
132 ilm 577
                printer.print(Arrays.asList(doc), job);
18 ilm 578
            }
579
 
580
        } catch (Exception e) {
132 ilm 581
            ExceptionHandler.handle("Impossible d'imprimer le document OpenOffice", e);
18 ilm 582
            e.printStackTrace();
583
        }
584
    }
585
 
586
    public SQLRow getSQLRow() {
587
        return this.row;
588
    }
589
 
590
    /**
591
     * Remplace tous les caracteres non alphanumeriques (seul le _ est autorisé) par un -. Cela
592
     * permet d'avoir toujours un nom de fichier valide.
593
     *
594
     * @param fileName nom du fichier à créer ex:FACTURE_2007/03/001
595
     * @return un nom fichier valide ex:FACTURE_2007-03-001
596
     */
83 ilm 597
    public static String getValidFileName(String fileName) {
25 ilm 598
        final StringBuffer result = new StringBuffer(fileName.length());
18 ilm 599
        for (int i = 0; i < fileName.length(); i++) {
25 ilm 600
            char ch = fileName.charAt(i);
18 ilm 601
 
602
            // Si c'est un caractere alphanumerique
25 ilm 603
            if (Character.isLetterOrDigit(ch) || (ch == '_') || (ch == ' ')) {
604
                result.append(ch);
18 ilm 605
            } else {
606
                result.append('-');
607
            }
608
        }
609
        return result.toString();
610
    }
611
 
612
    public String getPrinter() {
613
        return this.printer;
614
    }
615
 
93 ilm 616
    public void setRefreshFormulasRequired(boolean refreshFormulasRequired) {
617
        this.refreshFormulasRequired = refreshFormulasRequired;
618
    }
619
 
620
    public boolean isRefreshFormulasRequired() {
621
            return refreshFormulasRequired;
622
    }
623
 
18 ilm 624
}