OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 149 | Go to most recent revision | Details | 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
 
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;
27
 
28
import java.io.BufferedInputStream;
29
import java.io.File;
30
import java.io.FileInputStream;
31
import java.io.IOException;
32
import java.sql.SQLException;
33
import java.util.Collection;
34
import java.util.List;
35
 
36
import javax.swing.JOptionPane;
37
 
38
import eu.medsea.mimeutil.MimeType;
39
import eu.medsea.mimeutil.MimeUtil;
40
 
41
public class AttachmentUtils {
42
 
43
    public void uploadFile(File inFile, SQLRowAccessor rowSource) {
44
        try {
45
 
46
            // Création de la row attachment
47
            SQLRowValues rowValsAttachment = new SQLRowValues(rowSource.getTable().getTable("ATTACHMENT"));
48
            rowValsAttachment.put("SOURCE_TABLE", rowSource.getTable().getName());
49
            rowValsAttachment.put("SOURCE_ID", rowSource.getID());
50
 
51
            SQLRow rowAttachment = rowValsAttachment.insert();
52
            int id = rowAttachment.getID();
53
 
54
            String subDir = "EDM" + File.separator + String.valueOf((id / 1000) * 1000);
55
            String fileNameID = String.valueOf(id);
56
            String ext = "";
57
 
58
            int i = inFile.getName().lastIndexOf('.');
59
            if (i > 0) {
60
                ext = inFile.getName().substring(i + 1);
61
            }
62
 
63
            final String fileWithIDNAme = fileNameID + "." + ext;
64
 
65
            final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
66
            boolean isOnCloud = config.isOnCloud();
67
 
68
            if (isOnCloud) {
69
 
70
                String remotePath = subDir;
71
                remotePath = remotePath.replace('\\', '/');
72
                List<StorageEngine> engines = StorageEngines.getInstance().getActiveEngines();
73
                for (StorageEngine storageEngine : engines) {
74
                    if (storageEngine.isConfigured() && storageEngine.allowAutoStorage()) {
75
                        final String path = remotePath;
76
                        try {
77
                            storageEngine.connect();
78
                            final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inFile));
79
                            storageEngine.store(inStream, path, fileWithIDNAme, true);
80
                            inStream.close();
81
                            storageEngine.disconnect();
82
                        } catch (IOException e) {
83
                            ExceptionHandler.handle("Impossible de sauvegarder le fichier " + inFile.getAbsolutePath() + " vers " + path + "(" + storageEngine + ")", e);
84
                        }
85
                        // if (storageEngine instanceof CloudStorageEngine) {
86
                        // try {
87
                        // storageEngine.connect();
88
                        // final BufferedInputStream inStream = new BufferedInputStream(new
89
                        // FileInputStream(generatedFile));
90
                        // storageEngine.store(inStream, path, generatedFile.getName(), true);
91
                        // inStream.close();
92
                        // storageEngine.disconnect();
93
                        // } catch (IOException e) {
94
                        // ExceptionHandler.handle("Impossible de sauvegarder le fichier généré " +
95
                        // generatedFile.getAbsolutePath() + " vers " + path + "(" + storageEngine +
96
                        // ")", e);
97
                        // }
98
                        // }
99
                    }
100
                }
101
            } else {
102
                // Upload File
103
 
104
                // Get file out
105
                File dirRoot = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(AttachmentSQLElement.DIRECTORY_PREFS);
106
                File storagePathFile = new File(dirRoot, subDir);
107
                storagePathFile.mkdirs();
108
                // TODO CHECK IF FILE EXISTS
109
                FileUtils.copyFile(inFile, new File(storagePathFile, fileWithIDNAme));
110
 
111
            }
112
 
113
            // Update rowAttachment
114
            rowValsAttachment = rowAttachment.createEmptyUpdateRow();
115
 
116
            // Default is without extension
117
            String fileName = inFile.getName();
118
            String name = fileName;
119
            int index = name.lastIndexOf('.');
120
            if (index > 0) {
121
                name = name.substring(0, index);
122
            }
123
            rowValsAttachment.put("NAME", name);
124
            rowValsAttachment.put("SOURCE_TABLE", rowSource.getTable().getName());
125
            rowValsAttachment.put("SOURCE_ID", rowSource.getID());
126
            Collection<MimeType> mimeTypes = MimeUtil.getMimeTypes(inFile);
127
            if (mimeTypes != null && !mimeTypes.isEmpty()) {
128
                final MimeType mimeType = (MimeType) mimeTypes.toArray()[0];
129
                rowValsAttachment.put("MIMETYPE", mimeType.getMediaType() + "/" + mimeType.getSubType());
130
            } else {
131
                rowValsAttachment.put("MIMETYPE", "application/octet-stream");
132
            }
133
            rowValsAttachment.put("FILENAME", fileName);
134
            rowValsAttachment.put("FILESIZE", inFile.length());
135
            rowValsAttachment.put("STORAGE_PATH", subDir);
136
            rowValsAttachment.put("STORAGE_FILENAME", fileWithIDNAme);
137
            // TODO THUMBNAIL
138
            // rowVals.put("THUMBNAIL", );
139
            // rowVals.put("THUMBNAIL_WIDTH", );
140
            // rowVals.put("THUMBNAIL_HEIGHT", );
141
 
142
            // needed for update count
143
 
144
            rowValsAttachment.commit();
145
 
146
            updateAttachmentsCountFromAttachment(rowValsAttachment);
147
        } catch (IOException e1) {
148
            e1.printStackTrace();
149
        } catch (SQLException e1) {
150
            e1.printStackTrace();
151
        }
152
    }
153
 
154
    public File getFile(SQLRowAccessor rowAttachment) {
155
 
156
        final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
157
        boolean isOnCloud = config.isOnCloud();
158
 
159
        String subDir = rowAttachment.getString("STORAGE_PATH");
160
        String fileName = rowAttachment.getString("STORAGE_FILENAME");
161
 
162
        String remotePath = config.getSocieteID() + File.separator + subDir;
163
 
164
        File fTemp;
165
        try {
166
            fTemp = File.createTempFile("edm_", "oc");
167
        } catch (IOException e) {
168
            ExceptionHandler.handle("Impossible de créer le fichier temporaire de réception", e);
169
            return null;
170
        }
171
        File f = new File(fTemp.getParent(), fTemp.getName() + "-dir");
172
        f.mkdirs();
173
        fTemp.delete();
174
 
175
        if (isOnCloud) {
176
            remotePath = remotePath.replace('\\', '/');
177
            final SyncClient client = new SyncClient("https://" + config.getStorageServer());
178
 
179
            client.setVerifyHost(false);
180
 
181
            try {
182
                client.retrieveFile(f, remotePath, fileName, config.getToken());
183
            } catch (Exception e) {
184
                ExceptionHandler.handle("Impossible de récupérer le fichier depuis le cloud", e);
185
                return null;
186
            }
187
 
188
        } else {
189
 
190
            // Get file out
191
            File dirRoot = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(AttachmentSQLElement.DIRECTORY_PREFS);
192
            File storagePathFile = new File(dirRoot, subDir);
193
            File fileIn = new File(storagePathFile, fileName);
194
            if (fileIn.exists()) {
195
                final File outFile = new File(f, fileName);
196
                try {
197
                    FileUtils.copyFile(fileIn, outFile);
198
                } catch (IOException e) {
199
                    ExceptionHandler.handle("Impossible de copier le fichier vers le fichier temporaire de réception", e);
200
                    return null;
201
                }
202
            } else {
203
                JOptionPane.showMessageDialog(null, "Le fichier n'existe pas sur le serveur!", "Erreur fichier", JOptionPane.ERROR_MESSAGE);
204
            }
205
        }
206
        final File outFile = new File(f, fileName);
207
        outFile.setReadOnly();
208
        return outFile;
209
 
210
    }
211
 
212
    public void deleteFile(SQLRowAccessor rowAttachment) throws SQLException, IllegalStateException {
213
 
214
        final ComptaPropsConfiguration config = ComptaPropsConfiguration.getInstanceCompta();
215
        boolean isOnCloud = config.isOnCloud();
216
 
217
        // Delete File
218
        String subDir = rowAttachment.getString("STORAGE_PATH");
219
        String fileName = rowAttachment.getString("STORAGE_FILENAME");
220
 
221
        String remotePath = config.getSocieteID() + File.separator + subDir;
222
        if (isOnCloud) {
223
            remotePath = remotePath.replace('\\', '/');
224
            // final SyncClient client = new SyncClient("https://" + config.getStorageServer());
225
            //
226
            // client.setVerifyHost(false);
227
 
228
            // TODO DELETE FILE ON CLOUD OR RENAME?
229
            // client.retrieveFile(f, remotePath, fileName, config.getToken());
230
        } else {
231
 
232
            File dirRoot = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(AttachmentSQLElement.DIRECTORY_PREFS);
233
            File storagePathFile = new File(dirRoot, subDir);
234
            File f = new File(storagePathFile, fileName);
235
            if (f.exists()) {
236
                if (!f.delete()) {
237
                    throw new IllegalStateException("Une erreur est survenue lors de la suppression du fichier");
238
                }
239
            }
240
        }
241
 
242
        // Delete Row
243
        config.getDirectory().getElement(rowAttachment.getTable()).archive(rowAttachment.getID());
244
        updateAttachmentsCountFromAttachment(rowAttachment);
245
    }
246
 
247
    public void updateAttachmentsCountFromAttachment(SQLRowAccessor rowAttachment) {
248
        SQLTable table = rowAttachment.getTable().getTable(rowAttachment.getString("SOURCE_TABLE"));
249
        SQLRow source = table.getRow(rowAttachment.getInt("SOURCE_ID"));
250
        updateAttachmentsCountFromSource(source);
251
    }
252
 
253
    public void updateAttachmentsCountFromSource(SQLRow rowSource) {
254
        SQLTable tableSource = rowSource.getTable();
255
        SQLTable tableAtt = rowSource.getTable().getTable("ATTACHMENT");
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
 
264
}