Project

General

Profile

Download (13.5 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2007 EDIT
3
 * European Distributed Institute of Taxonomy
4
 * http://www.e-taxonomy.eu
5
 *
6
 * The contents of this file are subject to the Mozilla Public License Version 1.1
7
 * See LICENSE.TXT at the top of this package for the full license terms.
8
 */
9

    
10
package eu.etaxonomy.taxeditor.io;
11

    
12
import java.io.BufferedWriter;
13
import java.io.ByteArrayOutputStream;
14
import java.io.File;
15
import java.io.FileOutputStream;
16
import java.io.IOException;
17
import java.io.OutputStreamWriter;
18
import java.io.Writer;
19
import java.text.SimpleDateFormat;
20
import java.util.Calendar;
21
import java.util.List;
22
import java.util.Map;
23
import java.util.Set;
24
import java.util.zip.ZipEntry;
25
import java.util.zip.ZipOutputStream;
26

    
27
import org.apache.log4j.Logger;
28
import org.eclipse.core.runtime.Assert;
29
import org.eclipse.core.runtime.IProgressMonitor;
30
import org.eclipse.core.runtime.IStatus;
31
import org.eclipse.core.runtime.Status;
32
import org.eclipse.core.runtime.jobs.Job;
33
import org.eclipse.swt.widgets.Display;
34
import org.eclipse.ui.IWorkbenchPart;
35
import org.eclipse.ui.PlatformUI;
36

    
37
import eu.etaxonomy.cdm.api.application.CdmApplicationState;
38
import eu.etaxonomy.cdm.api.application.ICdmRepository;
39
import eu.etaxonomy.cdm.api.conversation.IConversationEnabled;
40
import eu.etaxonomy.cdm.io.common.CdmDefaultExport;
41
import eu.etaxonomy.cdm.io.common.ExportDataWrapper;
42
import eu.etaxonomy.cdm.io.common.ExportResult;
43
import eu.etaxonomy.cdm.io.common.ExportResultType;
44
import eu.etaxonomy.cdm.io.common.IExportConfigurator;
45
import eu.etaxonomy.cdm.io.common.IIoConfigurator;
46

    
47
import eu.etaxonomy.cdm.io.jaxb.JaxbExportConfigurator;
48
import eu.etaxonomy.cdm.io.cdmLight.CdmLightExportConfigurator;
49
import eu.etaxonomy.cdm.io.sdd.out.SDDExportConfigurator;
50
import eu.etaxonomy.cdm.io.service.IIOService;
51
import eu.etaxonomy.taxeditor.model.CdmProgressMonitorAdapter;
52
import eu.etaxonomy.taxeditor.model.MessagingUtils;
53
import eu.etaxonomy.taxeditor.store.StoreUtil;
54
import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
55

    
56
/**
57
 * <p>
58
 * ExportHandler class.
59
 * </p>
60
 *
61
 * @author n.hoffmann
62
 * @created Sep 11, 2009
63
 * @version 1.0
64
 */
65
public class ExportManager extends AbstractIOManager<IExportConfigurator> {
66
	
67
	private final String successMessage = "The export was successfull";
68

    
69
    private static final Logger logger = Logger.getLogger(ExportManager.class);
70
    /** Constant <code>DATE_FORMAT_NOW="yyyyMMddHHmm"</code> */
71
	public static final String DATE_FORMAT_NOW = "yyyyMMddHHmm";
72
	/**
73
	 *
74
	 * @param applicationConfiguration
75
	 */
76
	private ExportManager(ICdmRepository applicationConfiguration) {
77
		super(applicationConfiguration);
78
	}
79

    
80
	/**
81
	 * <p>
82
	 * NewInstance
83
	 * </p>
84
	 *
85
	 * @param applicationConfiguration
86
	 *            a
87
	 *            {@link eu.etaxonomy.cdm.api.application.CdmApplicationController}
88
	 *            object.
89
	 * @return a {@link eu.etaxonomy.taxeditor.io.ExportManager} object.
90
	 */
91
	public static ExportManager NewInstance(
92
			ICdmRepository applicationConfiguration) {
93
		return new ExportManager(applicationConfiguration);
94
	}
95

    
96
	/**
97
	 * <p>
98
	 * createIOJob
99
	 * </p>
100
	 *
101
	 * @param configurator
102
	 *            a {@link eu.etaxonomy.cdm.io.common.IExportConfigurator}
103
	 *            object.
104
	 * @return a {@link org.eclipse.core.runtime.jobs.Job} object.
105
	 */
106
	@Override
107
	protected Job createIOJob(final IExportConfigurator configurator) {
108

    
109
		Assert.isNotNull(configurator, "Configuration may not be null");
110

    
111
		final Display display = Display.getCurrent();
112

    
113
		Job job = new Job("Export: " + configurator.getClass().getSimpleName()) {
114
			@Override
115
			protected IStatus run(IProgressMonitor monitor) {
116
				monitor.beginTask(
117
						"Exporting database. This will take some time.", 100);
118
				monitor.worked(10);
119

    
120
			    /** see ticket # 4456 and */
121
//				display.asyncExec(new Runnable() {
122
//
123
//					@Override
124
//					public void run() {
125
//
126
//					    // terminate any open transactions
127
//						IConversationEnabled activePart = (IConversationEnabled) StoreUtil
128
//								.getActivePage().getActivePart();
129
//						activePart.getConversationHolder().commit(false);
130
//					}
131
//				});
132

    
133
//				monitor.worked(10);
134

    
135
				CdmDefaultExport<IExportConfigurator> exporter = new CdmDefaultExport<IExportConfigurator>();
136
				configurator.setProgressMonitor(CdmProgressMonitorAdapter
137
						.CreateSubMonitor(monitor, 80));
138
				exporter.setCdmAppController(applicationConfiguration);
139
				monitor.worked(10);
140

    
141
				try {
142
					exporter.invoke(configurator);
143
					monitor.worked(60);
144
				} catch (RuntimeException e) {
145
					MessagingUtils.messageDialog("Error exporting data", this,
146
							"An error occured while"
147
									+ "exporting to destination '"
148
									+ configurator.getDestinationNameString()
149
									+ "'.\n"
150
									+ "Please check error log for details.", e);
151
				}
152

    
153
				display.asyncExec(new Runnable() {
154

    
155
					@Override
156
					public void run() {
157
						IWorkbenchPart activePart = StoreUtil.getActivePage()
158
								.getActivePart();
159
						if (activePart instanceof IConversationEnabled) {
160
							// terminate any open transactions
161
							IConversationEnabled conversationEnabled = (IConversationEnabled) activePart;
162
							// restarting transaction and committing it to
163
							// trigger
164
							// change listener
165
							// TODO verify correct behaviour
166

    
167
							try{
168
								conversationEnabled.getConversationHolder()
169
									.startTransaction();
170

    
171
								conversationEnabled.getConversationHolder()
172
									.commit();
173
							}catch(RuntimeException e){
174
								MessagingUtils.messageDialog("Error starting conversation handling", this, "" +
175
										"Conversation Error: "+ e);
176
							}
177
						}
178
					}
179
				});
180
				monitor.worked(10);
181

    
182
				return Status.OK_STATUS;
183
			}
184
		};
185

    
186
		return job;
187
	}
188

    
189
	public Job createIOServiceJob(final IExportConfigurator configurator, final File exportFile) {
190
	    Assert.isNotNull(configurator, "Configuration may not be null");
191

    
192
	    final Display display = Display.getCurrent();
193

    
194
	    Job job = new Job("Export: " + configurator.getClass().getSimpleName()) { //$NON-NLS-1$
195
	        @Override
196
	        protected IStatus run(IProgressMonitor monitor) {
197
	            monitor.beginTask("Exporting database. This will take some time.", IProgressMonitor.UNKNOWN);
198
	            try {
199
	                IIOService ioService = CdmApplicationState.getIOService();
200

    
201
	                ExportResult result = ioService.export(configurator);
202
	                ExportDataWrapper data = result.getExportData();
203
	                try{
204
    	                if (result.getExportData().getType().equals(ExportResultType.BYTE_ARRAY)){
205
    	                    byte[] exportData = (byte[])data.getExportData();
206
        	                if(exportData != null){
207
        	                    FileOutputStream stream = new FileOutputStream(exportFile);
208
                                stream.write(exportData);
209
                                stream.close();
210
                            }
211
//    	                } else if (result.getExportData().getType().equals(ExportResultType.MAP_BYTE_ARRAY)){
212
//    	                    Map<String, byte[]> resultMap = (Map<String, byte[]>)data.getExportData();
213
//    	                    Set<String> keySet = resultMap.keySet();
214
//    	                    for (String key: keySet){
215
//    	                        byte[] fileData = resultMap.get(key);
216
//    	                        File file = new File(urlString)
217
//    	                        FileOutputStream stream = new FileOutputStream(key);
218
//                                stream.write(fileData);
219
//                                stream.close();
220
//    	                    }
221

    
222
    	                }else{
223
    	                    logger.error("This kind of result data is not supported yet." + result.getExportData().getType().toString());
224
    	                }
225
	                } catch(Exception e){
226
	                    logger.error(e.getStackTrace());
227
	                }
228

    
229
	                showResult(configurator.getClass().getSimpleName(), display, result, successMessage); 
230

    
231

    
232
	            } catch (Exception e) {
233
	                MessagingUtils.errorDialog("Error exporting data",
234
	                        this,
235
	                        e.getMessage(),
236
	                        TaxeditorStorePlugin.PLUGIN_ID,
237
	                        e,
238
	                        true);
239
	            }
240
	            return Status.OK_STATUS;
241
	        }
242
	    };
243
	    return job;
244
	}
245
	/**
246
	 * @param jaxb
247
	 * @return
248
	 */
249
	private IIoConfigurator getConfigurator(TYPE type) {
250
		Assert.isNotNull(type, "Type should not be null");
251

    
252
		switch (type) {
253
		case Jaxb:
254
			return JaxbExportConfigurator.NewInstance(null, null);
255
		case Sdd:
256
			return SDDExportConfigurator.NewInstance(null, null, null);
257
		default:
258
			MessagingUtils.notImplementedMessage(this);
259
			throw new IllegalArgumentException("Export not supported yet");
260
		}
261
	}
262

    
263
	/**
264
	 * <p>
265
	 * JaxbConfigurator
266
	 * </p>
267
	 *
268
	 * @return a {@link eu.etaxonomy.cdm.io.jaxb.JaxbExportConfigurator} object.
269
	 */
270
	public final JaxbExportConfigurator JaxbConfigurator() {
271
		return (JaxbExportConfigurator) getConfigurator(TYPE.Jaxb);
272
	}
273

    
274
	/**
275
	 * <p>
276
	 * SddConfigurator
277
	 * </p>
278
	 *
279
	 * @return a {@link eu.etaxonomy.cdm.io.sdd.out.SDDExportConfigurator}
280
	 *         object.
281
	 */
282
	public final SDDExportConfigurator SddConfigurator() {
283
		return (SDDExportConfigurator) getConfigurator(TYPE.Sdd);
284
	}
285

    
286
    /**
287
     * @param configurator
288
     * @param urlString
289
     * @return
290
     */
291
    public Job createIOServiceJob(CdmLightExportConfigurator configurator, String urlString) {
292
        Assert.isNotNull(configurator, "Configuration may not be null");
293
        final Display display = Display.getDefault();
294
        
295
         Job job = new Job("Export: " + configurator.getClass().getSimpleName()) { //$NON-NLS-1$
296
             @Override
297
             protected IStatus run(IProgressMonitor monitor) {
298
                 monitor.beginTask("Exporting database. This will take some time.", IProgressMonitor.UNKNOWN);
299
                 try {
300
                     IIOService ioService = CdmApplicationState.getIOService();
301

    
302
                     ExportResult result = ioService.export(configurator);
303
                     ExportDataWrapper data = result.getExportData();
304
                     try{
305
                         if (result.getExportData().getType().equals(ExportResultType.BYTE_ARRAY)){
306
                             byte[] exportData = (byte[])data.getExportData();
307
                             if(exportData != null){
308
                                 File file = new File(urlString);
309
                                 FileOutputStream stream = new FileOutputStream(file);
310
                                 Writer out = new BufferedWriter(new OutputStreamWriter(
311
                             			stream, "UTF8"));
312

    
313
                             	stream.write(exportData);
314
                                out.flush();
315
                                stream.close();
316
                             }
317
                         } else if (result.getExportData().getType().equals(ExportResultType.MAP_BYTE_ARRAY)){
318
                             Map<String, byte[]> resultMap = (Map<String, byte[]>)data.getExportData();
319
                             Set<String> keySet = resultMap.keySet();
320
                             SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
321
                             Calendar cal = Calendar.getInstance();
322
                             String fileEnding = ".csv";
323
                             
324
                             if (configurator.isCreateZipFile()){      
325
                        		 File file = new File(urlString+File.separator + "csv_light_" + sdf.format(cal.getTime())+ ".zip");                              
326
                                 FileOutputStream stream = new FileOutputStream(file);
327
                                 ZipOutputStream zos = new ZipOutputStream(stream);
328
                                 for (String key: keySet){
329
                                	byte[] fileData = resultMap.get(key);
330
                                	ZipEntry entry = new ZipEntry( key + fileEnding); 
331
     								zos.putNextEntry(entry);
332
     								zos.write(fileData);
333
     								zos.closeEntry();
334
                                 }
335
                                 zos.close();
336
                        	 }else{
337
                        		 for (String key: keySet){
338
                        			 byte[] fileData = resultMap.get(key);
339
                        			 File file = new File(urlString+File.separator + key + fileEnding);
340
                                     FileOutputStream stream = new FileOutputStream(file);
341
                                     Writer out = new BufferedWriter(new OutputStreamWriter(
342
                                 			stream, "UTF8"));
343
                                     stream.write(fileData);
344
                                     stream.close();
345
                                 }
346
                        	 }
347
                        }else{
348
                             logger.error("This kind of result data is not supported yet." + result.getExportData().getType().toString());
349
                         }
350
                     } catch(Exception e){
351
                         logger.error(e.getStackTrace());
352
                     }
353
                     showResult(configurator.getClass().getSimpleName(), display, result, successMessage);
354

    
355

    
356
                 } catch (Exception e) {
357
                     MessagingUtils.errorDialog("Error exporting data",
358
                             this,
359
                             e.getMessage(),
360
                             TaxeditorStorePlugin.PLUGIN_ID,
361
                             e,
362
                             true);
363
                 }
364

    
365
                 return Status.OK_STATUS;
366
             }
367
         };
368
         return job;
369
    }
370

    
371

    
372

    
373
}
(2-2/3)