Merge branch 'release/5.1.0'
[taxeditor.git] / eu.etaxonomy.taxeditor.store / src / main / java / eu / etaxonomy / taxeditor / model / AbstractUtility.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.model;
11
12 import java.io.BufferedWriter;
13 import java.io.File;
14 import java.io.FileOutputStream;
15 import java.io.OutputStreamWriter;
16 import java.io.Writer;
17 import java.text.SimpleDateFormat;
18 import java.util.ArrayList;
19 import java.util.Calendar;
20 import java.util.Collection;
21 import java.util.LinkedHashMap;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Set;
25 import java.util.TreeSet;
26 import java.util.UUID;
27 import java.util.zip.ZipEntry;
28 import java.util.zip.ZipOutputStream;
29
30 import org.apache.commons.lang.StringUtils;
31 import org.apache.log4j.Logger;
32 import org.eclipse.core.commands.ExecutionException;
33 import org.eclipse.core.commands.operations.AbstractOperation;
34 import org.eclipse.core.commands.operations.IOperationHistory;
35 import org.eclipse.core.runtime.IAdaptable;
36 import org.eclipse.core.runtime.ICoreRunnable;
37 import org.eclipse.core.runtime.IProgressMonitor;
38 import org.eclipse.core.runtime.IStatus;
39 import org.eclipse.core.runtime.NullProgressMonitor;
40 import org.eclipse.core.runtime.OperationCanceledException;
41 import org.eclipse.core.runtime.Status;
42 import org.eclipse.core.runtime.SubMonitor;
43 import org.eclipse.core.runtime.SubProgressMonitor;
44 import org.eclipse.core.runtime.jobs.Job;
45 import org.eclipse.e4.ui.di.UISynchronize;
46 import org.eclipse.e4.ui.model.application.ui.basic.MPart;
47 import org.eclipse.e4.ui.workbench.modeling.EPartService;
48 import org.eclipse.jface.action.IStatusLineManager;
49 import org.eclipse.jface.viewers.IStructuredSelection;
50 import org.eclipse.jface.viewers.SelectionChangedEvent;
51 import org.eclipse.swt.graphics.Color;
52 import org.eclipse.swt.graphics.Font;
53 import org.eclipse.swt.widgets.Display;
54 import org.eclipse.swt.widgets.Shell;
55 import org.eclipse.ui.IWorkbench;
56 import org.eclipse.ui.PlatformUI;
57 import org.eclipse.ui.ide.undo.WorkspaceUndoUtil;
58 import org.eclipse.ui.progress.IProgressConstants;
59
60 import eu.etaxonomy.cdm.api.application.CdmApplicationState;
61 import eu.etaxonomy.cdm.api.service.IProgressMonitorService;
62 import eu.etaxonomy.cdm.api.service.UpdateResult;
63 import eu.etaxonomy.cdm.common.monitor.IRemotingProgressMonitor;
64 import eu.etaxonomy.cdm.io.common.ExportDataWrapper;
65 import eu.etaxonomy.cdm.io.common.ExportResult;
66 import eu.etaxonomy.cdm.io.common.ExportResultType;
67 import eu.etaxonomy.cdm.io.common.ExportType;
68 import eu.etaxonomy.cdm.model.common.IEnumTerm;
69 import eu.etaxonomy.taxeditor.event.EventUtility;
70 import eu.etaxonomy.taxeditor.operation.AbstractPostOperation;
71 import eu.etaxonomy.taxeditor.operation.IFeedbackGenerator;
72 import eu.etaxonomy.taxeditor.operation.IPostMoniteredOperationEnabled;
73 import eu.etaxonomy.taxeditor.operation.IPostOperationEnabled;
74 import eu.etaxonomy.taxeditor.operation.e4.RemotingCdmHandlerE4;
75 import eu.etaxonomy.taxeditor.store.CdmStore;
76 import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
77 import eu.etaxonomy.taxeditor.ui.dialog.ReportTextDialog;
78 import eu.etaxonomy.taxeditor.view.e4.AbstractCdmDataViewerE4;
79 import eu.etaxonomy.taxeditor.view.e4.details.DetailsPartE4;
80 import eu.etaxonomy.taxeditor.workbench.part.IE4SavablePart;
81
82 /**
83 *
84 * @author n.hoffmann
85 * @created 11.05.2009
86 * @version 1.0
87 */
88 public abstract class AbstractUtility {
89
90 protected static final Logger logger = Logger.getLogger(AbstractUtility.class);
91
92 /** Constant <code>statusLineManager</code> */
93 protected static IStatusLineManager statusLineManager;
94 /** Constant <code>DATE_FORMAT_NOW="yyyyMMddHHmm"</code> */
95 public static final String DATE_FORMAT_NOW = "yyyyMMddHHmm";
96
97 public static Object getActivePart() {
98 MPart activePart = EventUtility.getActivePart();
99 if(activePart!=null){
100 return activePart.getObject();
101 }
102 return null;
103 }
104
105 public static Shell getShell() {
106 return EventUtility.getShell();
107 }
108
109 public static IWorkbench getWorkbench() {
110 return TaxeditorStorePlugin.getDefault().getWorkbench();
111 }
112
113 public static Object getService(Class api) {
114 return TaxeditorStorePlugin.getDefault().getWorkbench().getService(api);
115 }
116
117 public static Font getFont(String symbolicName) {
118 return FontResources.getFont(symbolicName);
119 }
120
121 public static Color getColor(String symbolicName) {
122 return ColorResources.getColor(symbolicName);
123 }
124
125 public static IStatus executeOperation(final AbstractPostOperation operation, UISynchronize sync) {
126 if (getOperationHistory() == null) {
127 throw new IllegalArgumentException(
128 "There is no operation history for this context");
129 }
130
131 final IAdaptable uiInfoAdapter = WorkspaceUndoUtil
132 .getUIInfoAdapter(getShell());
133
134 Job job = Job.create(operation.getLabel(), (ICoreRunnable) monitor -> {
135 sync.syncExec(() -> {
136 String operationlabel = operation.getLabel();
137 monitor.beginTask(operationlabel, 100);
138 IStatus status = Status.CANCEL_STATUS;
139 try {
140 operation.addContext(IOperationHistory.GLOBAL_UNDO_CONTEXT);
141 status = operation.execute(monitor, uiInfoAdapter);
142 } catch (ExecutionException e) {
143
144 MessagingUtils.operationDialog(AbstractUtility.class, e, TaxeditorStorePlugin.PLUGIN_ID, operationlabel, null);
145
146 } finally {
147 monitor.done();
148 }
149
150 String statusString = status.equals(Status.OK_STATUS) ? "completed"
151 : "cancelled";
152 setStatusLine(operationlabel + " " + statusString + ".");
153 IPostOperationEnabled postOperationEnabled = operation
154 .getPostOperationEnabled();
155 if (postOperationEnabled != null) {
156 postOperationEnabled.onComplete();
157 }
158 });
159 });
160
161 try {
162 job.setUser(true);
163 job.schedule();
164 } catch (Exception e) {
165 MessagingUtils.messageDialog("Error executing operation", AbstractUtility.class, "An error occurred while executing " + operation.getLabel(), e);
166 }
167
168 return Status.OK_STATUS;
169 }
170
171 public static IStatus executeOperation(final AbstractOperation operation, final RemotingCdmHandlerE4 handler, UISynchronize sync) {
172 return executeOperation_internal(operation, handler, sync);
173 }
174
175 private static IStatus executeOperation_internal(final AbstractOperation operation, final RemotingCdmHandlerE4 handler,
176 UISynchronize sync) {
177 if (getOperationHistory() == null) {
178 throw new IllegalArgumentException(
179 "There is no operation history for this context");
180 }
181
182 final IAdaptable uiInfoAdapter = WorkspaceUndoUtil
183 .getUIInfoAdapter(getShell());
184
185
186 Job job = Job.create(operation.getLabel(), (ICoreRunnable) monitor -> {
187 sync.syncExec(() -> {
188 String operationlabel = operation.getLabel();
189 monitor.beginTask(operationlabel, 100);
190 IStatus status = Status.CANCEL_STATUS;
191 try {
192 operation.addContext(IOperationHistory.GLOBAL_UNDO_CONTEXT);
193 status = operation.execute(monitor,
194 uiInfoAdapter);
195 handler.postOperation(status);
196 } catch (ExecutionException e) {
197 MessagingUtils.operationDialog(AbstractUtility.class, e, TaxeditorStorePlugin.PLUGIN_ID, operationlabel, null);
198 } finally {
199 monitor.done();
200 }
201
202 String statusString = status.equals(Status.OK_STATUS) ? "completed"
203 : "cancelled";
204 setStatusLine(operationlabel + " " + statusString + ".");
205 });
206 });
207
208 try {
209 job.setUser(true);
210 sync.syncExec(()->job.schedule());
211 } catch (Exception e) {
212 MessagingUtils.messageDialog("Error executing operation", AbstractUtility.class, "An error occurred while executing " + operation.getLabel(), e);
213 }
214
215 return Status.OK_STATUS;
216 }
217
218 /**
219 * Executes a remoting monitored operation
220 *
221 * @param label for the operation
222 * @param uuid of the remoting monitor already started on the server
223 * @param pollInterval in milliseconds
224 * @param cancelable flag which determines whether the operation can be cancelled
225 * @param postOp callback for running post operation logic
226 * @return
227 */
228 public static IStatus executeMoniteredExport(final String label,
229 final UUID uuid,
230 final int pollInterval,
231 final boolean cancelable,
232 final IPostMoniteredOperationEnabled postOp,
233 final IFeedbackGenerator feedbackGenerator,
234 String urlString,
235 boolean createZip) {
236
237 try {
238 // get the remoting monitor the first time to make sure that the
239 // operation is valid
240 final IProgressMonitorService progressMonitorService = CdmApplicationState.getCurrentAppConfig().getProgressMonitorService();
241 final IRemotingProgressMonitor firstRemotingMonitor = progressMonitorService.getRemotingMonitor(uuid);
242 if(firstRemotingMonitor == null) {
243 throw new IllegalStateException("Remoting progress monitor is null");
244 }
245 if (firstRemotingMonitor.isDone()){
246 createExportResult(label, urlString, createZip, firstRemotingMonitor);
247 }
248
249 Job job = new Job(label) {
250
251
252 @Override
253 public IStatus run(IProgressMonitor monitor) {
254 // run the monitor until the operation is finished
255 SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
256 //subMonitor.beginTask("Start", 100);
257 IRemotingProgressMonitor remotingMonitor;
258 try {
259 remotingMonitor = CdmStore.getProgressMonitorClientManager().pollMonitor(label,
260 uuid,
261 pollInterval,
262 postOp,
263 feedbackGenerator,
264 subMonitor);
265 } catch (Exception ex) {
266 return new Status(Status.ERROR, TaxeditorStorePlugin.PLUGIN_ID, "Operation Interrupted", ex);
267 }
268
269 createExportResult(label, urlString, createZip, remotingMonitor);
270 return Status.OK_STATUS;
271 }
272
273
274
275 @Override
276 protected void canceling() {
277 CdmStore.getCurrentApplicationConfiguration().getProgressMonitorService().cancel(uuid);
278 }
279 };
280
281 // configure the job
282 job.setProperty(IProgressConstants.KEEP_PROPERTY, true);
283 job.setUser(true);
284 // schedule job
285 job.schedule();
286
287 } catch (Exception e) {
288 MessagingUtils.errorDialog("Error executing operation",
289 AbstractUtility.class,
290 "An error occurred while executing " + label,
291 TaxeditorStorePlugin.PLUGIN_ID,
292 e,
293 true);
294 }
295
296 return Status.OK_STATUS;
297 }
298
299 public static IOperationHistory getOperationHistory() {
300 return getWorkbench().getOperationSupport().getOperationHistory();
301 }
302
303 public static void setStatusLine(final String message) {
304 Display.getDefault().asyncExec(new Runnable() {
305
306 @Override
307 public void run() {
308 statusLineManager.setMessage(message);
309 }
310
311 });
312
313 }
314
315 public static IProgressMonitor getMonitor() {
316 statusLineManager.setCancelEnabled(false);
317 return statusLineManager.getProgressMonitor();
318 }
319
320 /**
321 * Starts either the given {@link IProgressMonitor} if it's not
322 * <code>null</code> or a new {@link NullProgressMonitor}.
323 *
324 * @param progressMonitor
325 * The {@link IProgressMonitor} or <code>null</code> if no
326 * progress should be reported.
327 * @param taskName
328 * The name of the main task.
329 * @param steps
330 * The number of steps this task is subdivided into.
331 * @return The {@link IProgressMonitor}.
332 */
333 public static IProgressMonitor startMainMonitor(
334 IProgressMonitor progressMonitor, String taskName, int steps) {
335 IProgressMonitor newMonitor = progressMonitor;
336 if (newMonitor == null) {
337 newMonitor = new NullProgressMonitor();
338 }
339 newMonitor.beginTask(taskName == null ? "" : taskName, steps);
340 newMonitor.subTask(" ");
341 return newMonitor;
342 }
343
344 /**
345 * Creates a {@link SubProgressMonitor} if the given
346 * {@link IProgressMonitor} is not <code>null</code> and not a
347 * {@link NullProgressMonitor}.
348 *
349 * @param progressMonitor
350 * The parent {@link IProgressMonitor} of the
351 * {@link SubProgressMonitor} to be created.
352 * @param ticks
353 * The number of steps this subtask is subdivided into. Must be a
354 * positive number and must not be
355 * {@link IProgressMonitor#UNKNOWN}.
356 * @return The {@link IProgressMonitor}.
357 */
358 public static IProgressMonitor getSubProgressMonitor(
359 IProgressMonitor progressMonitor, int ticks) {
360 if (progressMonitor == null) {
361 return new NullProgressMonitor();
362 }
363 if (progressMonitor instanceof NullProgressMonitor) {
364 return progressMonitor;
365 }
366
367 return new SubProgressMonitor(progressMonitor, ticks);
368 }
369
370 /**
371 * Checks whether the user canceled this operation. If not canceled, the
372 * given number of steps are declared as done.
373 *
374 * @param newMonitor
375 * a {@link org.eclipse.core.runtime.IProgressMonitor} object.
376 * @param steps
377 * a int.
378 */
379 public static void workedChecked(IProgressMonitor newMonitor, int steps) {
380 // In case the progress monitor was canceled throw an exception.
381 if (newMonitor.isCanceled()) {
382 throw new OperationCanceledException();
383 }
384 // Otherwise declare this step as done.
385 newMonitor.worked(steps);
386 }
387
388 public static String getPluginId() {
389 return "eu.taxeditor";
390 }
391
392 public static Object getActiveEditor() {
393 MPart activePart = EventUtility.getActivePart();
394 if(activePart!=null && activePart.getObject()!=null
395 && activePart.getObject() instanceof IE4SavablePart){
396 return activePart.getObject();
397 }
398 return null;
399 }
400
401 public static DetailsPartE4 getDetailsView(EPartService partService) {
402 MPart part = partService.findPart("eu.etaxonomy.taxeditor.view.e4.details.DetailsPartE4");
403 if(part!=null){
404 return (DetailsPartE4) part.getObject();
405 }
406 return null;
407 }
408
409 public static void refreshDetailsViewer(EPartService partService) {
410 if (getDetailsView(partService) != null) {
411 ((AbstractCdmDataViewerE4) getDetailsView(partService).getViewer()).refresh();
412 }
413 }
414
415 public static void reflowDetailsViewer(EPartService partService) {
416 if (getDetailsView(partService) != null) {
417 ((AbstractCdmDataViewerE4) getDetailsView(partService).getViewer()).reflow();
418 }
419 }
420
421
422 /**
423 * Orders a Collection of {@link IEnumTerm}s according to the term
424 * hierarchy. <br>
425 * <br>
426 * The returned map will be be ordered primarily by root elements,
427 * secondarily by the child elements and their children resp., both ascending alphabetically. <br>
428 * @param terms
429 * A {@link Collection} of {@link IEnumTerm}s for which the term
430 * hierarchy should be created
431 * @return a map which holds the terms as keys and their string
432 * representation via {@link IEnumTerm#getMessage()} as values
433 */
434 public static <T extends IEnumTerm<T>> LinkedHashMap<T, String> orderTerms(Collection<T> terms) {
435 TreeSet<TermNode<T>> parentElements = new TreeSet<TermNode<T>>();
436 parentElements.addAll(getTermHierarchy(terms));
437
438 // create list according to the type hierarchy (root elements alphabetically with recursive children also alphabetically)
439 LinkedHashMap<T, String> result = new LinkedHashMap<T, String>();
440 parseTermTree(parentElements, result, -1);
441 return result;
442 }
443
444 private static<T extends IEnumTerm<T>> void parseTermTree(Collection<TermNode<T>> children, LinkedHashMap<T, String> result, int depth){
445 depth++;
446 for(TermNode<T> node:children){
447 String indentString = "";
448 for(int i=0;i<depth;i++){
449 indentString += " ";
450 }
451 if(depth>0){
452 indentString += "- ";
453 }
454 result.put(node.term, indentString + node.term.getMessage());
455 parseTermTree(node.children, result, depth);
456 }
457 }
458
459 private static<T extends IEnumTerm<T>> void addToParents(List<TermNode<T>> parents, Collection<T> terms){
460 List<TermNode<T>> hasChildrenList = new ArrayList<TermNode<T>>();
461 for(T term:terms){
462 // only terms with parents
463 if(term.getKindOf()!=null){
464 TermNode<T> parentNode = new TermNode<T>(term.getKindOf());
465 TermNode<T> childNode = new TermNode<T>(term);
466 if(parents.contains(parentNode)){
467 // parent found in parent list -> add this term to parent's child list
468 parents.get(parents.indexOf(parentNode)).addChild(childNode);
469 if(!term.getGeneralizationOf().isEmpty()){
470 // has more children -> add to list which will be the parent for the next recursion
471 hasChildrenList.add(childNode);
472 }
473 }
474 }
475 }
476 if(!hasChildrenList.isEmpty()){
477 addToParents(hasChildrenList, terms);
478 }
479 }
480
481 private static<T extends IEnumTerm<T>> List<TermNode<T>> getTermHierarchy(Collection<T> terms){
482 List<TermNode<T>> parents = new ArrayList<TermNode<T>>();
483 // get root elements
484 for(T term:terms){
485 T parentTerm = term.getKindOf();
486 if(parentTerm==null){
487 // root element
488 parents.add(new TermNode<T>(term));
489 }
490 }
491 addToParents(parents, terms);
492 return parents;
493 }
494
495 @SuppressWarnings("unchecked")
496 /**
497 * Recursively iterates over all term parents until no more parent is found i.e. the root node
498 * @param term The term for which the parent should be found
499 * @return the root terms of the term hierarchy
500 */
501 private static<T extends IEnumTerm<T>> T getParentFor(T term){
502 // PP: cast should be safe. Why is Eclipse complaining??
503 T parent = term.getKindOf();
504 if(parent==null){
505 return term;
506 }
507 else{
508 return getParentFor(term.getKindOf());
509 }
510 }
511
512 private static class TermNode<T extends IEnumTerm<T>> implements Comparable<TermNode<T>>{
513 private final T term;
514 private final TreeSet<TermNode<T>> children;
515
516 public TermNode(T term) {
517 super();
518 this.term = term;
519 this.children = new TreeSet<TermNode<T>>();
520 }
521
522 public void addChild(TermNode<T> child){
523 this.children.add(child);
524 }
525
526 public TreeSet<TermNode<T>> getChildren() {
527 return children;
528 }
529
530 public T getTerm() {
531 return term;
532 }
533
534 @Override
535 public int hashCode() {
536 final int prime = 31;
537 int result = 1;
538 result = prime * result + ((term == null) ? 0 : term.hashCode());
539 return result;
540 }
541
542 @Override
543 public boolean equals(Object obj) {
544 if (this == obj) {
545 return true;
546 }
547 if (obj == null) {
548 return false;
549 }
550 if (getClass() != obj.getClass()) {
551 return false;
552 }
553 TermNode other = (TermNode) obj;
554 if (term == null) {
555 if (other.term != null) {
556 return false;
557 }
558 } else if (!term.equals(other.term)) {
559 return false;
560 }
561 return true;
562 }
563
564 @Override
565 public int compareTo(TermNode<T> that) {
566 return this.term.getMessage().compareTo(that.term.getMessage());
567 }
568 }
569
570 public static Object getElementsFromSelectionChangedEvent(SelectionChangedEvent event) {
571 IStructuredSelection selection = (IStructuredSelection) event.getSelection();
572 Object selectionToSet = selection;
573 if(selection.size() == 1){
574 selectionToSet = selection.getFirstElement();
575 }
576 else if(!selection.isEmpty()){
577 selectionToSet = selection.toArray();
578 }
579 return selectionToSet;
580 }
581
582 /**
583 * Executes a remoting monitored import
584 *
585 * @param label for the import
586 * @param uuid of the remoting monitor already started on the server
587 * @param pollInterval in milliseconds
588 * @param cancelable flag which determines whether the operation can be cancelled
589 * @param postOp callback for running post operation logic
590 * @return
591 */
592 public static IStatus executeMoniteredOperation(final String label,
593 final UUID uuid,
594 final int pollInterval,
595 final boolean cancelable,
596 final IPostMoniteredOperationEnabled postOp,
597 final IFeedbackGenerator feedbackGenerator,
598 final boolean showResult) {
599
600 try{
601 // get the remoting monitor the first time to make sure that the
602 // operation is valid
603 final IProgressMonitorService progressMonitorService = CdmApplicationState.getCurrentAppConfig().getProgressMonitorService();
604 final IRemotingProgressMonitor firstRemotingMonitor = progressMonitorService.getRemotingMonitor(uuid);
605 if(firstRemotingMonitor == null) {
606 throw new IllegalStateException("Remoting progress monitor is null");
607 }
608 if (firstRemotingMonitor.isDone()){
609 createResult(label, showResult, firstRemotingMonitor);
610 return Status.OK_STATUS;
611 }
612
613 Job job = new Job(label) {
614
615
616 @Override
617 public IStatus run(IProgressMonitor monitor) {
618 // run the monitor until the operation is finished
619 SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
620 // subMonitor.beginTask("Start", 100);
621
622 IRemotingProgressMonitor remotingMonitor;
623 try {
624 remotingMonitor = CdmStore.getProgressMonitorClientManager().pollMonitor(label,
625 uuid,
626 pollInterval,
627 postOp,
628 feedbackGenerator,
629 subMonitor);
630 } catch (Exception ex) {
631 return new Status(Status.ERROR, TaxeditorStorePlugin.PLUGIN_ID, "Operation Interrupted", ex);
632 }
633
634
635 // collect reports
636 // for(String report : remotingMonitor.getResult()) {
637 createResult(label, showResult, remotingMonitor);
638
639 return Status.OK_STATUS;
640 }
641
642
643
644 @Override
645 protected void canceling() {
646 CdmStore.getCurrentApplicationConfiguration().getProgressMonitorService().cancel(uuid);
647 }
648 };
649
650 // configure the job
651 job.setUser(true);
652 // schedule job
653 job.schedule();
654
655 } catch (Exception e) {
656 MessagingUtils.errorDialog("Error executing operation",
657 AbstractUtility.class,
658 "An error occurred while executing " + label,
659 TaxeditorStorePlugin.PLUGIN_ID,
660 e,
661 true);
662 }
663
664 return Status.OK_STATUS;
665 }
666
667
668 private static void createResult(final String label, final boolean showResult,
669 IRemotingProgressMonitor remotingMonitor) {
670 final StringBuilder reportSb = new StringBuilder();
671 if (remotingMonitor.getResult() instanceof ExportResult) {
672 reportSb.append(((ExportResult)remotingMonitor.getResult()).createReport());
673 }else if (remotingMonitor.getResult() instanceof UpdateResult){
674 if (((UpdateResult)remotingMonitor.getResult()).isOk()){
675 reportSb.append("Update successfull. \n"+"Updated Objects: " + ((UpdateResult)remotingMonitor.getResult()).getUpdatedObjects().size());
676 }
677 if (!((UpdateResult)remotingMonitor.getResult()).getExceptions().isEmpty()){
678 reportSb.append(((UpdateResult)remotingMonitor.getResult()).getExceptions().toString());
679 }
680 }
681 // }
682 if(showResult && !StringUtils.isBlank(reportSb.toString()) && reportSb.length() != 0) {
683 Display.getDefault().asyncExec(new Runnable() {
684 @Override
685 public void run() {
686 // display reports with possibility to save
687 ReportTextDialog dialog = new ReportTextDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
688 dialog.setTitle(label + " Report");
689 dialog.setReportText(reportSb.toString());
690 dialog.open();
691 }
692 });
693 }
694 }
695
696 private static void createExportResult(final String label, String urlString, boolean createZip,
697 IRemotingProgressMonitor remotingMonitor) {
698
699 final StringBuilder reportSb = new StringBuilder();
700 if (remotingMonitor.getResult() instanceof ExportResult){
701 ExportResult result = (ExportResult)remotingMonitor.getResult();
702
703 reportSb.append(result.createReport());
704
705 if(!StringUtils.isBlank(reportSb.toString())) {
706 Display.getDefault().asyncExec(new Runnable() {
707 @Override
708 public void run() {
709 // display reports with possibility to save
710 ReportTextDialog dialog = new ReportTextDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
711 dialog.setTitle(label + " Report");
712 dialog.setReportText(reportSb.toString());
713 dialog.open();
714 }
715 });
716 }
717
718 if (urlString != null){
719 ExportDataWrapper data = result.getExportData();
720 try{
721 if (result.getExportData().getType().equals(ExportResultType.BYTE_ARRAY)){
722 byte[] exportData = (byte[])data.getExportData();
723 if(exportData != null){
724 File file = new File(urlString);
725 FileOutputStream stream = new FileOutputStream(file);
726 Writer out = new BufferedWriter(new OutputStreamWriter(
727 stream, "UTF8"));
728
729 stream.write(exportData);
730 out.flush();
731 stream.close();
732 }
733 } else if (result.getExportData().getType().equals(ExportResultType.MAP_BYTE_ARRAY)){
734 Map<String, byte[]> resultMap = (Map<String, byte[]>)data.getExportData();
735 Set<String> keySet = resultMap.keySet();
736 SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
737 Calendar cal = Calendar.getInstance();
738 String fileEnding = ".csv";
739
740 if (createZip){
741 File file = new File(urlString+File.separator + sdf.format(cal.getTime())+ ".zip");
742 FileOutputStream stream = new FileOutputStream(file);
743 ZipOutputStream zos = new ZipOutputStream(stream);
744 for (String key: keySet){
745 byte[] fileData = resultMap.get(key);
746 ZipEntry entry = new ZipEntry( key + fileEnding);
747 zos.putNextEntry(entry);
748 zos.write(fileData);
749 zos.closeEntry();
750 }
751 zos.close();
752 }else{
753 if(result.getExportType().equals(ExportType.DWCA)){
754
755 File file = new File(urlString);
756 FileOutputStream stream = new FileOutputStream(file);
757 ZipOutputStream zos = new ZipOutputStream(stream);
758 for (String key: keySet){
759 byte[] fileData = resultMap.get(key);
760 ZipEntry entry = new ZipEntry( key);
761 zos.putNextEntry(entry);
762 zos.write(fileData);
763 zos.closeEntry();
764 }
765 zos.close();
766 }else{
767 for (String key: keySet){
768 byte[] fileData = resultMap.get(key);
769 File file = new File(urlString+File.separator + key + fileEnding);
770 FileOutputStream stream = new FileOutputStream(file);
771 Writer out = new BufferedWriter(new OutputStreamWriter(
772 stream, "UTF8"));
773 stream.write(fileData);
774 stream.close();
775 }
776 }
777 }
778 }else{
779 logger.error("This kind of result data is not supported yet." + result.getExportData().getType().toString());
780 }
781 } catch(Exception e){
782 logger.error(e.getStackTrace());
783 }
784 }
785 }
786 }
787 }