Merge branch 'release/4.7.0'
[taxeditor.git] / eu.etaxonomy.taxeditor.store / src / main / java / eu / etaxonomy / taxeditor / io / ExportManager.java
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.File;
13 import java.io.FileOutputStream;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Set;
17
18 import org.apache.log4j.Logger;
19 import org.eclipse.core.runtime.Assert;
20 import org.eclipse.core.runtime.IProgressMonitor;
21 import org.eclipse.core.runtime.IStatus;
22 import org.eclipse.core.runtime.Status;
23 import org.eclipse.core.runtime.jobs.Job;
24 import org.eclipse.swt.widgets.Display;
25 import org.eclipse.ui.IWorkbenchPart;
26 import org.eclipse.ui.PlatformUI;
27
28 import eu.etaxonomy.cdm.api.application.CdmApplicationState;
29 import eu.etaxonomy.cdm.api.application.ICdmRepository;
30 import eu.etaxonomy.cdm.api.conversation.IConversationEnabled;
31 import eu.etaxonomy.cdm.io.common.CdmDefaultExport;
32 import eu.etaxonomy.cdm.io.common.ExportDataWrapper;
33 import eu.etaxonomy.cdm.io.common.ExportResult;
34 import eu.etaxonomy.cdm.io.common.ExportResultType;
35 import eu.etaxonomy.cdm.io.common.IExportConfigurator;
36 import eu.etaxonomy.cdm.io.common.IIoConfigurator;
37 import eu.etaxonomy.cdm.io.common.IoResultBase;
38 import eu.etaxonomy.cdm.io.common.IoResultBase.IoInfo;
39 import eu.etaxonomy.cdm.io.jaxb.JaxbExportConfigurator;
40 import eu.etaxonomy.cdm.io.outputmodel.OutputModelConfigurator;
41 import eu.etaxonomy.cdm.io.sdd.out.SDDExportConfigurator;
42 import eu.etaxonomy.cdm.io.service.IIOService;
43 import eu.etaxonomy.taxeditor.model.CdmProgressMonitorAdapter;
44 import eu.etaxonomy.taxeditor.model.MessagingUtils;
45 import eu.etaxonomy.taxeditor.store.CdmStore;
46 import eu.etaxonomy.taxeditor.store.StoreUtil;
47 import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
48 import eu.etaxonomy.taxeditor.ui.dialog.ReportTextDialog;
49
50 /**
51 * <p>
52 * ExportHandler class.
53 * </p>
54 *
55 * @author n.hoffmann
56 * @created Sep 11, 2009
57 * @version 1.0
58 */
59 public class ExportManager extends AbstractIOManager<IExportConfigurator> {
60
61 private static final Logger logger = Logger.getLogger(ExportManager.class);
62
63 /**
64 *
65 * @param applicationConfiguration
66 */
67 private ExportManager(ICdmRepository applicationConfiguration) {
68 super(applicationConfiguration);
69 }
70
71 /**
72 * <p>
73 * NewInstance
74 * </p>
75 *
76 * @param applicationConfiguration
77 * a
78 * {@link eu.etaxonomy.cdm.api.application.CdmApplicationController}
79 * object.
80 * @return a {@link eu.etaxonomy.taxeditor.io.ExportManager} object.
81 */
82 public static ExportManager NewInstance(
83 ICdmRepository applicationConfiguration) {
84 return new ExportManager(applicationConfiguration);
85 }
86
87 /**
88 * <p>
89 * createIOJob
90 * </p>
91 *
92 * @param configurator
93 * a {@link eu.etaxonomy.cdm.io.common.IExportConfigurator}
94 * object.
95 * @return a {@link org.eclipse.core.runtime.jobs.Job} object.
96 */
97 @Override
98 protected Job createIOJob(final IExportConfigurator configurator) {
99
100 Assert.isNotNull(configurator, "Configuration may not be null");
101
102 final Display display = Display.getCurrent();
103
104 Job job = new Job("Export: " + configurator.getClass().getSimpleName()) {
105 @Override
106 protected IStatus run(IProgressMonitor monitor) {
107 monitor.beginTask(
108 "Exporting database. This will take some time.", 100);
109 monitor.worked(10);
110
111 /** see ticket # 4456 and */
112 // display.asyncExec(new Runnable() {
113 //
114 // @Override
115 // public void run() {
116 //
117 // // terminate any open transactions
118 // IConversationEnabled activePart = (IConversationEnabled) StoreUtil
119 // .getActivePage().getActivePart();
120 // activePart.getConversationHolder().commit(false);
121 // }
122 // });
123
124 // monitor.worked(10);
125
126 CdmDefaultExport<IExportConfigurator> exporter = new CdmDefaultExport<IExportConfigurator>();
127 configurator.setProgressMonitor(CdmProgressMonitorAdapter
128 .CreateSubMonitor(monitor, 80));
129 exporter.setCdmAppController(applicationConfiguration);
130 monitor.worked(10);
131
132 try {
133 exporter.invoke(configurator);
134 monitor.worked(60);
135 } catch (RuntimeException e) {
136 MessagingUtils.messageDialog("Error exporting data", this,
137 "An error occured while"
138 + "exporting to destination '"
139 + configurator.getDestinationNameString()
140 + "'.\n"
141 + "Please check error log for details.", e);
142 }
143
144 display.asyncExec(new Runnable() {
145
146 @Override
147 public void run() {
148 IWorkbenchPart activePart = StoreUtil.getActivePage()
149 .getActivePart();
150 if (activePart instanceof IConversationEnabled) {
151 // terminate any open transactions
152 IConversationEnabled conversationEnabled = (IConversationEnabled) activePart;
153 // restarting transaction and committing it to
154 // trigger
155 // change listener
156 // TODO verify correct behaviour
157
158 try{
159 conversationEnabled.getConversationHolder()
160 .startTransaction();
161
162 conversationEnabled.getConversationHolder()
163 .commit();
164 }catch(RuntimeException e){
165 MessagingUtils.messageDialog("Error starting conversation handling", this, "" +
166 "Conversation Error: "+ e);
167 }
168 }
169 }
170 });
171 monitor.worked(10);
172
173 return Status.OK_STATUS;
174 }
175 };
176
177 return job;
178 }
179
180 public Job createIOServiceJob(final IExportConfigurator configurator, final File exportFile) {
181 Assert.isNotNull(configurator, "Configuration may not be null");
182
183 // final Display display = Display.getCurrent();
184
185 Job job = new Job("Export: " + configurator.getClass().getSimpleName()) { //$NON-NLS-1$
186 @Override
187 protected IStatus run(IProgressMonitor monitor) {
188 monitor.beginTask("Exporting database. This will take some time.", IProgressMonitor.UNKNOWN);
189 try {
190 IIOService ioService = CdmApplicationState.getIOService();
191
192 ExportResult result = ioService.export(configurator);
193 ExportDataWrapper data = result.getExportData();
194 try{
195 if (result.getExportData().getType().equals(ExportResultType.BYTE_ARRAY)){
196 byte[] exportData = (byte[])data.getExportData();
197 if(exportData != null){
198 FileOutputStream stream = new FileOutputStream(exportFile);
199 stream.write(exportData);
200 stream.close();
201 }
202 // } else if (result.getExportData().getType().equals(ExportResultType.MAP_BYTE_ARRAY)){
203 // Map<String, byte[]> resultMap = (Map<String, byte[]>)data.getExportData();
204 // Set<String> keySet = resultMap.keySet();
205 // for (String key: keySet){
206 // byte[] fileData = resultMap.get(key);
207 // File file = new File(urlString)
208 // FileOutputStream stream = new FileOutputStream(key);
209 // stream.write(fileData);
210 // stream.close();
211 // }
212
213 }else{
214 logger.error("This kind of result data is not supported yet." + result.getExportData().getType().toString());
215 }
216 } catch(Exception e){
217 logger.error(e.getStackTrace());
218 }
219
220
221
222
223 } catch (Exception e) {
224 MessagingUtils.errorDialog("Error exporting data",
225 this,
226 e.getMessage(),
227 TaxeditorStorePlugin.PLUGIN_ID,
228 e,
229 true);
230 }
231 return Status.OK_STATUS;
232 }
233 };
234 return job;
235 }
236 /**
237 * @param jaxb
238 * @return
239 */
240 private IIoConfigurator getConfigurator(TYPE type) {
241 Assert.isNotNull(type, "Type should not be null");
242
243 switch (type) {
244 case Jaxb:
245 return JaxbExportConfigurator.NewInstance(null, null);
246 case Sdd:
247 return SDDExportConfigurator.NewInstance(null, null, null);
248 default:
249 MessagingUtils.notImplementedMessage(this);
250 throw new IllegalArgumentException("Export not supported yet");
251 }
252 }
253
254 /**
255 * <p>
256 * JaxbConfigurator
257 * </p>
258 *
259 * @return a {@link eu.etaxonomy.cdm.io.jaxb.JaxbExportConfigurator} object.
260 */
261 public final JaxbExportConfigurator JaxbConfigurator() {
262 return (JaxbExportConfigurator) getConfigurator(TYPE.Jaxb);
263 }
264
265 /**
266 * <p>
267 * SddConfigurator
268 * </p>
269 *
270 * @return a {@link eu.etaxonomy.cdm.io.sdd.out.SDDExportConfigurator}
271 * object.
272 */
273 public final SDDExportConfigurator SddConfigurator() {
274 return (SDDExportConfigurator) getConfigurator(TYPE.Sdd);
275 }
276
277 /**
278 * @param configurator
279 * @param urlString
280 * @return
281 */
282 public Job createIOServiceJob(OutputModelConfigurator configurator, String urlString) {
283 Assert.isNotNull(configurator, "Configuration may not be null");
284
285 // final Display display = Display.getCurrent();
286
287 Job job = new Job("Export: " + configurator.getClass().getSimpleName()) { //$NON-NLS-1$
288 @Override
289 protected IStatus run(IProgressMonitor monitor) {
290 monitor.beginTask("Exporting database. This will take some time.", IProgressMonitor.UNKNOWN);
291 try {
292 IIOService ioService = CdmApplicationState.getIOService();
293
294 ExportResult result = ioService.export(configurator);
295 ExportDataWrapper data = result.getExportData();
296 try{
297 if (result.getExportData().getType().equals(ExportResultType.BYTE_ARRAY)){
298 byte[] exportData = (byte[])data.getExportData();
299 if(exportData != null){
300 File file = new File(urlString);
301 FileOutputStream stream = new FileOutputStream(file);
302 stream.write(exportData);
303 stream.close();
304 }
305 } else if (result.getExportData().getType().equals(ExportResultType.MAP_BYTE_ARRAY)){
306 Map<String, byte[]> resultMap = (Map<String, byte[]>)data.getExportData();
307 Set<String> keySet = resultMap.keySet();
308 for (String key: keySet){
309 byte[] fileData = resultMap.get(key);
310 String fileEnding ="";
311 if (configurator instanceof OutputModelConfigurator){
312 fileEnding = ".csv";
313 }
314 File file = new File(urlString+File.separator + key + fileEnding);
315 FileOutputStream stream = new FileOutputStream(file);
316 stream.write(fileData);
317 stream.close();
318 }
319
320 }else{
321 logger.error("This kind of result data is not supported yet." + result.getExportData().getType().toString());
322 }
323 } catch(Exception e){
324 logger.error(e.getStackTrace());
325 }
326 final StringBuilder reportText = new StringBuilder();
327 if(result!=null){
328 List<IoInfo> reports = result.getErrors();
329 reportText.append("Errors:\\r");
330 for (IoInfo bs : reports) {
331 reportText.append(bs.getMessage() + " - " +bs.getException().getStackTrace());
332 }
333 List<IoResultBase.IoInfo> warnings = result.getWarnings();
334 reportText.append("Warnings:\\r");
335 for (IoResultBase.IoInfo bs : warnings) {
336 reportText.append(bs);
337 }
338 List<IoInfo> exceptions = result.getExceptions();
339 reportText.append("Exceptions:\\r");
340 for (IoInfo bs : exceptions) {
341 reportText.append(bs.getMessage() + " - " +bs.getException().getStackTrace());
342 }
343
344
345 }
346 final Display display = Display.getDefault();
347 display.asyncExec(new Runnable() {
348
349 @Override
350 public void run() {
351 // display reports with possibility to save
352 ReportTextDialog dialog = new ReportTextDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
353 dialog.setTitle(configurator.getClass().getSimpleName()+" Report");
354 dialog.setReportText(reportText.toString());
355 dialog.open();
356 CdmStore.getContextManager().notifyContextRefresh();
357 }
358 });
359
360
361
362 } catch (Exception e) {
363 MessagingUtils.errorDialog("Error exporting data",
364 this,
365 e.getMessage(),
366 TaxeditorStorePlugin.PLUGIN_ID,
367 e,
368 true);
369 }
370
371 return Status.OK_STATUS;
372 }
373 };
374 return job;
375 }
376
377
378
379 }