OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
142 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.core.edm;
15
 
149 ilm 16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
17
import org.openconcerto.erp.generationDoc.DocumentLocalStorageManager;
18
import org.openconcerto.erp.storage.StorageEngine;
19
import org.openconcerto.erp.storage.StorageEngines;
20
import org.openconcerto.sql.model.SQLRow;
21
import org.openconcerto.sql.model.SQLRowAccessor;
22
import org.openconcerto.sql.model.SQLRowValues;
23
import org.openconcerto.sql.model.SQLTable;
24
import org.openconcerto.utils.ExceptionHandler;
25
import org.openconcerto.utils.FileUtils;
26
import org.openconcerto.utils.sync.SyncClient;
142 ilm 27
 
156 ilm 28
import java.io.BufferedInputStream;
29
import java.io.File;
30
import java.io.FileInputStream;
31
import java.io.IOException;
32
import java.nio.file.Files;
33
import java.sql.SQLException;
34
import java.util.List;
35
 
36
import javax.swing.JOptionPane;
37
 
142 ilm 38
public class AttachmentUtils {
39
 
149 ilm 40
    public void uploadFile(File inFile, SQLRowAccessor rowSource, int idParent) {
142 ilm 41
        try {
42
 
43
            // Création de la row attachment
44
            SQLRowValues rowValsAttachment = new SQLRowValues(rowSource.getTable().getTable("ATTACHMENT"));
45
            rowValsAttachment.put("SOURCE_TABLE", rowSource.getTable().getName());
46
            rowValsAttachment.put("SOURCE_ID", rowSource.getID());
149 ilm 47
            rowValsAttachment.put("ID_PARENT", idParent);
142 ilm 48
            SQLRow rowAttachment = rowValsAttachment.insert();
49
            int id = rowAttachment.getID();
50
 
149 ilm 51
            final String folderId = String.valueOf((id / 1000) * 1000);
156 ilm 52
            String subDir = "EDM/" + folderId;
142 ilm 53
            String fileNameID = String.valueOf(id);
54
            String ext = "";
55
 
56
            int i = inFile.getName().lastIndexOf('.');
57
            if (i > 0) {
58
                ext = inFile.getName().substring(i + 1);
59
            }
60
 
61
            final String fileWithIDNAme = fileNameID + "." + ext;
62
 
63
            final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
64
            boolean isOnCloud = config.isOnCloud();
65
 
66
            if (isOnCloud) {
67
 
68
                String remotePath = subDir;
69
                List<StorageEngine> engines = StorageEngines.getInstance().getActiveEngines();
70
                for (StorageEngine storageEngine : engines) {
71
                    if (storageEngine.isConfigured() && storageEngine.allowAutoStorage()) {
72
                        final String path = remotePath;
149 ilm 73
 
74
                        try (FileInputStream in = new FileInputStream(inFile)) {
142 ilm 75
                            storageEngine.connect();
149 ilm 76
                            final BufferedInputStream inStream = new BufferedInputStream(in);
142 ilm 77
                            storageEngine.store(inStream, path, fileWithIDNAme, true);
78
                            inStream.close();
79
                            storageEngine.disconnect();
80
                        } catch (IOException e) {
81
                            ExceptionHandler.handle("Impossible de sauvegarder le fichier " + inFile.getAbsolutePath() + " vers " + path + "(" + storageEngine + ")", e);
82
                        }
83
                        // if (storageEngine instanceof CloudStorageEngine) {
84
                        // try {
85
                        // storageEngine.connect();
86
                        // final BufferedInputStream inStream = new BufferedInputStream(new
87
                        // FileInputStream(generatedFile));
88
                        // storageEngine.store(inStream, path, generatedFile.getName(), true);
89
                        // inStream.close();
90
                        // storageEngine.disconnect();
91
                        // } catch (IOException e) {
92
                        // ExceptionHandler.handle("Impossible de sauvegarder le fichier généré " +
93
                        // generatedFile.getAbsolutePath() + " vers " + path + "(" + storageEngine +
94
                        // ")", e);
95
                        // }
96
                        // }
97
                    }
98
                }
99
            } else {
100
                // Upload File
101
 
102
                // Get file out
103
                File dirRoot = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(AttachmentSQLElement.DIRECTORY_PREFS);
104
                File storagePathFile = new File(dirRoot, subDir);
105
                storagePathFile.mkdirs();
106
                // TODO CHECK IF FILE EXISTS
107
                FileUtils.copyFile(inFile, new File(storagePathFile, fileWithIDNAme));
108
 
109
            }
110
 
111
            // Update rowAttachment
112
            rowValsAttachment = rowAttachment.createEmptyUpdateRow();
113
 
114
            // Default is without extension
115
            String fileName = inFile.getName();
116
            String name = fileName;
117
            int index = name.lastIndexOf('.');
118
            if (index > 0) {
119
                name = name.substring(0, index);
120
            }
121
            rowValsAttachment.put("NAME", name);
122
            rowValsAttachment.put("SOURCE_TABLE", rowSource.getTable().getName());
123
            rowValsAttachment.put("SOURCE_ID", rowSource.getID());
156 ilm 124
            final String mimeType = Files.probeContentType(inFile.toPath());
125
            rowValsAttachment.put("MIMETYPE", mimeType != null ? mimeType : "application/octet-stream");
142 ilm 126
            rowValsAttachment.put("FILENAME", fileName);
127
            rowValsAttachment.put("FILESIZE", inFile.length());
128
            rowValsAttachment.put("STORAGE_PATH", subDir);
129
            rowValsAttachment.put("STORAGE_FILENAME", fileWithIDNAme);
130
            // TODO THUMBNAIL
131
            // rowVals.put("THUMBNAIL", );
132
            // rowVals.put("THUMBNAIL_WIDTH", );
133
            // rowVals.put("THUMBNAIL_HEIGHT", );
134
 
135
            // needed for update count
136
 
137
            rowValsAttachment.commit();
149 ilm 138
            final Attachment a = new Attachment(rowValsAttachment);
139
            updateAttachmentsCountFromAttachment(a);
140
        } catch (Exception e) {
141
            e.printStackTrace();
142 ilm 142
        }
143
    }
144
 
149 ilm 145
    public File getFile(Attachment attachment) {
142 ilm 146
 
147
        final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
148
        boolean isOnCloud = config.isOnCloud();
149
 
149 ilm 150
        String subDir = attachment.getStoragePath();
151
        String fileName = attachment.getStorageFileName();
142 ilm 152
 
153
        String remotePath = config.getSocieteID() + File.separator + subDir;
154
 
155
        File fTemp;
156
        try {
157
            fTemp = File.createTempFile("edm_", "oc");
158
        } catch (IOException e) {
159
            ExceptionHandler.handle("Impossible de créer le fichier temporaire de réception", e);
160
            return null;
161
        }
162
        File f = new File(fTemp.getParent(), fTemp.getName() + "-dir");
163
        f.mkdirs();
164
        fTemp.delete();
165
 
166
        if (isOnCloud) {
167
            remotePath = remotePath.replace('\\', '/');
168
            final SyncClient client = new SyncClient("https://" + config.getStorageServer());
169
 
170
            client.setVerifyHost(false);
171
 
172
            try {
173
                client.retrieveFile(f, remotePath, fileName, config.getToken());
174
            } catch (Exception e) {
175
                ExceptionHandler.handle("Impossible de récupérer le fichier depuis le cloud", e);
176
                return null;
177
            }
178
 
179
        } else {
180
 
181
            // Get file out
182
            File dirRoot = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(AttachmentSQLElement.DIRECTORY_PREFS);
183
            File storagePathFile = new File(dirRoot, subDir);
156 ilm 184
            File fileIn;
185
            try {
186
                fileIn = new File(storagePathFile, fileName).getCanonicalFile();
187
                if (fileIn.exists()) {
188
                    final File outFile = new File(f, fileName);
189
                    try {
190
                        FileUtils.copyFile(fileIn, outFile);
191
                    } catch (IOException e) {
192
                        ExceptionHandler.handle("Impossible de copier le fichier vers le fichier temporaire de réception", e);
193
                        return null;
194
                    }
195
                } else {
196
                    JOptionPane.showMessageDialog(null, "Le fichier n'existe pas sur le serveur!\n" + fileIn.getAbsolutePath(), "Erreur fichier", JOptionPane.ERROR_MESSAGE);
142 ilm 197
                    return null;
198
                }
156 ilm 199
            } catch (IOException e1) {
200
                ExceptionHandler.handle("Impossible de trouver le fichier\n" + storagePathFile + File.pathSeparator + fileName, e1);
201
                return null;
142 ilm 202
            }
203
        }
204
        final File outFile = new File(f, fileName);
205
        outFile.setReadOnly();
206
        return outFile;
207
 
208
    }
209
 
149 ilm 210
    public void deleteFile(Attachment rowAttachment) throws SQLException, IllegalStateException {
142 ilm 211
 
212
        final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
149 ilm 213
        if (!rowAttachment.isFolder()) {
214
            boolean isOnCloud = config.isOnCloud();
215
            // Delete File
216
            String subDir = rowAttachment.getStoragePath();
217
            String fileName = rowAttachment.getStorageFileName();
142 ilm 218
 
149 ilm 219
            String remotePath = config.getSocieteID() + File.separator + subDir;
220
            if (isOnCloud) {
221
                remotePath = remotePath.replace('\\', '/');
222
                // final SyncClient client = new SyncClient("https://" + config.getStorageServer());
223
                //
224
                // client.setVerifyHost(false);
142 ilm 225
 
149 ilm 226
                // TODO DELETE FILE ON CLOUD OR RENAME?
227
                // client.retrieveFile(f, remotePath, fileName, config.getToken());
228
            } else {
142 ilm 229
 
149 ilm 230
                File dirRoot = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(AttachmentSQLElement.DIRECTORY_PREFS);
231
                File storagePathFile = new File(dirRoot, subDir);
232
                File f = new File(storagePathFile, fileName);
233
                if (f.exists()) {
234
                    if (!f.delete()) {
235
                        throw new IllegalStateException("Une erreur est survenue lors de la suppression du fichier");
236
                    }
142 ilm 237
                }
238
            }
239
        }
240
        // Delete Row
149 ilm 241
        config.getDirectory().getElement(AttachmentSQLElement.class).archive(rowAttachment.getId());
142 ilm 242
        updateAttachmentsCountFromAttachment(rowAttachment);
243
    }
244
 
149 ilm 245
    private void updateAttachmentsCountFromAttachment(Attachment rowAttachment) {
246
        final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
247
        final SQLTable attachmentTable = config.getDirectory().getElement(AttachmentSQLElement.class).getTable();
248
        final SQLTable table = attachmentTable.getTable(rowAttachment.getSourceTable());
249
        final SQLRow source = table.getRow(rowAttachment.getSourceId());
142 ilm 250
        updateAttachmentsCountFromSource(source);
251
    }
252
 
149 ilm 253
    private void updateAttachmentsCountFromSource(SQLRow rowSource) {
254
        final SQLTable tableSource = rowSource.getTable();
255
        final SQLTable tableAtt = rowSource.getTable().getTable("ATTACHMENT");
142 ilm 256
 
257
        String req = "UPDATE " + tableSource.getSQLName().quote() + " SET " + tableSource.getField("ATTACHMENTS").getQuotedName() + "=(SELECT COUNT(*) FROM " + tableAtt.getSQLName().quote();
258
        req += " WHERE " + tableAtt.getArchiveField().getQuotedName() + "=0 AND " + tableAtt.getField("SOURCE_TABLE").getQuotedName() + "='" + tableSource.getName() + "'";
259
        req += " AND " + tableAtt.getField("SOURCE_ID").getQuotedName() + "=" + rowSource.getID() + ") WHERE " + tableSource.getKey().getQuotedName() + "=" + rowSource.getID();
260
 
261
        tableSource.getDBSystemRoot().getDataSource().execute(req);
262
    }
263
 
149 ilm 264
    public static void rename(Attachment rowAttachment, String newName) {
265
        rowAttachment.setName(newName);
266
        final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
267
        final SQLTable attachmentTable = config.getDirectory().getElement(AttachmentSQLElement.class).getTable();
268
        final String req = "UPDATE " + attachmentTable.getSQLName().quote() + " SET " + attachmentTable.getField("NAME").getQuotedName() + "=" + attachmentTable.getBase().quoteString(newName)
269
                + " WHERE " + attachmentTable.getKey().getQuotedName() + "=" + rowAttachment.getId();
270
        attachmentTable.getDBSystemRoot().getDataSource().execute(req);
271
    }
272
 
273
    public void createFolder(String folderName, SQLRowAccessor rowSource, int idParent) throws SQLException {
274
        final SQLRowValues rowValsAttachment = new SQLRowValues(rowSource.getTable().getTable("ATTACHMENT"));
275
        rowValsAttachment.put("SOURCE_TABLE", rowSource.getTable().getName());
276
        rowValsAttachment.put("SOURCE_ID", rowSource.getID());
277
        rowValsAttachment.put("ID_PARENT", idParent);
278
        rowValsAttachment.put("NAME", folderName);
279
        rowValsAttachment.put("SOURCE_TABLE", rowSource.getTable().getName());
280
        rowValsAttachment.put("SOURCE_ID", rowSource.getID());
281
        rowValsAttachment.put("MIMETYPE", Attachment.MIMETYPE_FOLDER);
282
        rowValsAttachment.put("FILENAME", "");
283
        rowValsAttachment.put("FILESIZE", 0);
284
        rowValsAttachment.put("STORAGE_PATH", "");
285
        rowValsAttachment.put("STORAGE_FILENAME", "");
286
        rowValsAttachment.commit();
287
    }
288
 
289
    public void move(Attachment a, Attachment folder) {
290
        if (!folder.isFolder()) {
291
            throw new IllegalArgumentException(folder + " is not a folder");
292
        }
293
        move(a, folder.getId());
294
    }
295
 
296
    public void move(Attachment a, int folderId) {
297
        final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
298
        final SQLTable attachmentTable = config.getDirectory().getElement(AttachmentSQLElement.class).getTable();
299
        final String req = "UPDATE " + attachmentTable.getSQLName().quote() + " SET " + attachmentTable.getField("ID_PARENT").getQuotedName() + "=" + folderId + " WHERE "
300
                + attachmentTable.getKey().getQuotedName() + "=" + a.getId();
301
        attachmentTable.getDBSystemRoot().getDataSource().execute(req);
302
    }
303
 
142 ilm 304
}