ref #10384: add Col DP Export to editor
[taxeditor.git] / eu.etaxonomy.taxeditor.store / src / main / java / eu / etaxonomy / taxeditor / model / AbstractUtility.java
index b6e9f288ad6ce58967ebe2619b72b8f435bd9891..a2717487a2b9b053b8a8f44c1137ec990cc8fc4f 100644 (file)
@@ -6,7 +6,6 @@
  * The contents of this file are subject to the Mozilla Public License Version 1.1
  * See LICENSE.TXT at the top of this package for the full license terms.
  */
-
 package eu.etaxonomy.taxeditor.model;
 
 import java.io.BufferedWriter;
@@ -29,7 +28,8 @@ import java.util.zip.ZipEntry;
 import java.util.zip.ZipOutputStream;
 
 import org.apache.commons.lang3.StringUtils;
-import org.apache.log4j.Logger;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
 import org.eclipse.core.commands.ExecutionException;
 import org.eclipse.core.commands.operations.AbstractOperation;
 import org.eclipse.core.commands.operations.IOperationHistory;
@@ -61,13 +61,15 @@ import org.eclipse.ui.progress.IProgressConstants;
 import eu.etaxonomy.cdm.api.application.CdmApplicationState;
 import eu.etaxonomy.cdm.api.service.IProgressMonitorService;
 import eu.etaxonomy.cdm.api.service.UpdateResult;
+import eu.etaxonomy.cdm.api.service.dto.CdmEntityIdentifier;
+import eu.etaxonomy.cdm.common.CdmUtils;
+import eu.etaxonomy.cdm.common.SetMap;
 import eu.etaxonomy.cdm.common.monitor.IRemotingProgressMonitor;
 import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
 import eu.etaxonomy.cdm.io.common.ExportDataWrapper;
 import eu.etaxonomy.cdm.io.common.ExportResult;
 import eu.etaxonomy.cdm.io.common.ExportResultType;
 import eu.etaxonomy.cdm.io.common.ExportType;
-import eu.etaxonomy.cdm.io.common.ImportResult;
 import eu.etaxonomy.cdm.model.common.CdmBase;
 import eu.etaxonomy.cdm.model.taxon.Synonym;
 import eu.etaxonomy.cdm.model.taxon.Taxon;
@@ -79,23 +81,21 @@ import eu.etaxonomy.taxeditor.operation.AbstractPostOperation;
 import eu.etaxonomy.taxeditor.operation.IFeedbackGenerator;
 import eu.etaxonomy.taxeditor.operation.IPostMoniteredOperationEnabled;
 import eu.etaxonomy.taxeditor.operation.IPostOperationEnabled;
-import eu.etaxonomy.taxeditor.operation.e4.RemotingCdmHandlerE4;
+import eu.etaxonomy.taxeditor.operation.e4.CdmHandlerE4;
 import eu.etaxonomy.taxeditor.store.CdmStore;
 import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
 import eu.etaxonomy.taxeditor.ui.dialog.ReportTextDialog;
-import eu.etaxonomy.taxeditor.view.e4.AbstractCdmDataViewerE4;
+import eu.etaxonomy.taxeditor.view.e4.AbstractCdmDataViewer;
 import eu.etaxonomy.taxeditor.view.e4.details.DetailsPartE4;
 import eu.etaxonomy.taxeditor.workbench.part.IE4SavablePart;
 
 /**
- *
  * @author n.hoffmann
  * @created 11.05.2009
- * @version 1.0
  */
 public abstract class AbstractUtility {
 
-    protected static final Logger logger = Logger.getLogger(AbstractUtility.class);
+    protected static final Logger logger = LogManager.getLogger(AbstractUtility.class);
 
     /** Constant <code>statusLineManager</code> */
     protected static IStatusLineManager statusLineManager;
@@ -118,6 +118,7 @@ public abstract class AbstractUtility {
         return TaxeditorStorePlugin.getDefault().getWorkbench();
     }
 
+    @SuppressWarnings("unchecked")
     public static Object getService(Class api) {
         return TaxeditorStorePlugin.getDefault().getWorkbench().getService(api);
     }
@@ -136,8 +137,7 @@ public abstract class AbstractUtility {
                     "There is no operation history for this context");
         }
 
-        final IAdaptable uiInfoAdapter = WorkspaceUndoUtil
-                .getUIInfoAdapter(getShell());
+        final IAdaptable uiInfoAdapter = WorkspaceUndoUtil.getUIInfoAdapter(getShell());
 
         Job job = Job.create(operation.getLabel(), (ICoreRunnable) monitor -> {
             sync.syncExec(() -> {
@@ -176,11 +176,11 @@ public abstract class AbstractUtility {
         return Status.OK_STATUS;
     }
 
-    public static IStatus executeOperation(final AbstractOperation operation, final RemotingCdmHandlerE4 handler, UISynchronize sync) {
+    public static IStatus executeOperation(final AbstractOperation operation, final CdmHandlerE4 handler, UISynchronize sync) {
         return executeOperation_internal(operation, handler, sync);
     }
 
-    private static IStatus executeOperation_internal(final AbstractOperation operation, final RemotingCdmHandlerE4 handler,
+    private static IStatus executeOperation_internal(final AbstractOperation operation, final CdmHandlerE4 handler,
             UISynchronize sync) {
         if (getOperationHistory() == null) {
             throw new IllegalArgumentException(
@@ -271,7 +271,7 @@ public abstract class AbstractUtility {
                                 feedbackGenerator,
                                 subMonitor);
                     } catch (Exception ex) {
-                        return new Status(Status.ERROR, TaxeditorStorePlugin.PLUGIN_ID, "Operation Interrupted", ex);
+                        return new Status(IStatus.ERROR, TaxeditorStorePlugin.PLUGIN_ID, "Operation Interrupted", ex);
                     }
 
                     createExportResult(label, urlString, createZip, remotingMonitor);
@@ -417,13 +417,13 @@ public abstract class AbstractUtility {
 
     public static void refreshDetailsViewer(EPartService partService) {
         if (getDetailsView(partService) != null) {
-            ((AbstractCdmDataViewerE4) getDetailsView(partService).getViewer()).refresh();
+            ((AbstractCdmDataViewer) getDetailsView(partService).getViewer()).refresh();
         }
     }
 
     public static void reflowDetailsViewer(EPartService partService) {
         if (getDetailsView(partService) != null) {
-            ((AbstractCdmDataViewerE4) getDetailsView(partService).getViewer()).reflow();
+            ((AbstractCdmDataViewer) getDetailsView(partService).getViewer()).reflow();
         }
     }
 
@@ -460,7 +460,7 @@ public abstract class AbstractUtility {
             if(depth>0){
                 indentString += "- ";
             }
-            result.put(node.term, indentString + node.term.getMessage());
+            result.put(node.term, indentString + node.term.getLabel());
             parseTermTree(node.children, result, depth);
         }
     }
@@ -559,7 +559,7 @@ public abstract class AbstractUtility {
             if (getClass() != obj.getClass()) {
                 return false;
             }
-            TermNode other = (TermNode) obj;
+            TermNode<?> other = (TermNode<?>) obj;
             if (term == null) {
                 if (other.term != null) {
                     return false;
@@ -572,7 +572,7 @@ public abstract class AbstractUtility {
 
         @Override
         public int compareTo(TermNode<T> that) {
-            return this.term.getMessage().compareTo(that.term.getMessage());
+            return this.term.getLabel().compareTo(that.term.getLabel());
         }
     }
 
@@ -604,7 +604,8 @@ public abstract class AbstractUtility {
             final boolean cancelable,
             final IPostMoniteredOperationEnabled postOp,
             final IFeedbackGenerator feedbackGenerator,
-            final boolean showResult) {
+            final boolean showResult,
+            final boolean updateNavigator) {
 
        try{
                // get the remoting monitor the first time to make sure that the
@@ -622,8 +623,6 @@ public abstract class AbstractUtility {
             }
 
             Job job = new Job(label) {
-
-
                 @Override
                 public IStatus run(IProgressMonitor monitor) {
                     // run the monitor until the operation is finished
@@ -639,34 +638,25 @@ public abstract class AbstractUtility {
                                 feedbackGenerator,
                                 subMonitor);
                     } catch (Exception ex) {
-                        return new Status(Status.ERROR, TaxeditorStorePlugin.PLUGIN_ID, "Operation Interrupted", ex);
+                        return new Status(IStatus.ERROR, TaxeditorStorePlugin.PLUGIN_ID, "Operation Interrupted", ex);
                     }
 
-
                     // collect reports
 //                         for(String report : remotingMonitor.getResult()) {
                     createResult(label, showResult, remotingMonitor);
                     Set<Taxon> taxaToUpdate = getTaxaToUpdate(remotingMonitor);
                     updateNameEditors(taxaToUpdate);
-                    if (!taxaToUpdate.isEmpty()){
+                    if (!taxaToUpdate.isEmpty() && updateNavigator){
                         refreshNavigator();
                     }
+                    subMonitor.subTask("");
                     return Status.OK_STATUS;
                 }
 
-
-
-
-
-
-
                 private void refreshNavigator() {
                     EventUtility.postEvent(WorkbenchEventConstants.REFRESH_NAVIGATOR, true);
-
                 }
 
-
-
                 @Override
                 protected void canceling() {
                     CdmStore.getCurrentApplicationConfiguration().getProgressMonitorService().cancel(uuid);
@@ -690,18 +680,16 @@ public abstract class AbstractUtility {
         }
 
         return Status.OK_STATUS;
-        }
+    }
 
     private static Set<Taxon> getTaxaToUpdate(IRemotingProgressMonitor remotingMonitor) {
         Set<Taxon> taxaToUpdate = new HashSet<>();
-        if (remotingMonitor.getResult() instanceof UpdateResult){
+        if (remotingMonitor != null && remotingMonitor.getResult() instanceof UpdateResult){
             for (CdmBase object: ((UpdateResult)remotingMonitor.getResult()).getUpdatedObjects()){
                 Taxon taxon = null;
 
                 if (object instanceof Taxon){
                     taxon = HibernateProxyHelper.deproxy(object, Taxon.class);
-
-
                 }else if (object instanceof Synonym){
                     Synonym syn = HibernateProxyHelper.deproxy(object, Synonym.class);
                     taxon = syn.getAcceptedTaxon();
@@ -712,59 +700,67 @@ public abstract class AbstractUtility {
                     taxaToUpdate.add(taxon);
                 }
             }
-        }else if (remotingMonitor.getResult() instanceof ImportResult){
-            Map<String, Integer> result = ((ImportResult)remotingMonitor.getResult()).getUpdatedRecords();
-            for (Map.Entry<String, Integer> object: result.entrySet()){
-                Taxon taxon = null;
-                if (object instanceof Taxon){
-                    taxon = HibernateProxyHelper.deproxy(object, Taxon.class);
-                }else if (object instanceof Synonym){
-                    Synonym syn = HibernateProxyHelper.deproxy(object, Synonym.class);
-                    taxon = syn.getAcceptedTaxon();
-                }
-                taxaToUpdate.add(taxon);
-           }
-
         }
         return taxaToUpdate;
     }
+
     public static void createResult(String label, boolean showResult,
             IRemotingProgressMonitor remotingMonitor) {
         final StringBuilder reportSb = new StringBuilder();
-        if (remotingMonitor.getResult() instanceof ExportResult) {
+        if (remotingMonitor == null){
+            reportSb.append("Something went wrong. No result returned from server.");
+        }else if (remotingMonitor.getResult() instanceof ExportResult) {
             reportSb.append(((ExportResult)remotingMonitor.getResult()).createReport());
         }else if (remotingMonitor.getResult() instanceof UpdateResult){
-            if (((UpdateResult)remotingMonitor.getResult()).isOk()){
-                int count = ((UpdateResult)remotingMonitor.getResult()).getUpdatedObjects().size();
-                if (count == 0){
-                    count = ((UpdateResult)remotingMonitor.getResult()).getUpdatedCdmIds().size();
-                }
-
-                reportSb.append("Update successful. \n"+"Updated Objects: " +count);
-            }
-            if (!((UpdateResult)remotingMonitor.getResult()).getExceptions().isEmpty()){
-                reportSb.append(((UpdateResult)remotingMonitor.getResult()).getExceptions().toString());
-            }
+            UpdateResult result = (UpdateResult)remotingMonitor.getResult();
+            createUpdateResultReport(reportSb, result);
         }else if (remotingMonitor.getReports()!= null){
             for (String o:remotingMonitor.getReports()){
                 reportSb.append(o);
             }
         }
-//          }
-        if(showResult && !StringUtils.isBlank(reportSb.toString()) && reportSb.length() != 0) {
+        String report = reportSb.toString();
+        if(showResult && !StringUtils.isBlank(report)) {
             Display.getDefault().asyncExec(new Runnable() {
                 @Override
                 public void run() {
                     // display reports with possibility to save
                     ReportTextDialog dialog = new ReportTextDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
                     dialog.setTitle(label + " Report");
-                    dialog.setReportText(reportSb.toString());
+                    dialog.setReportText(report);
                     dialog.open();
                 }
             });
         }
     }
 
+    public static void createUpdateResultReport(final StringBuilder reportSb, UpdateResult result) {
+        if (result.isOk() || result.isAbort()){
+            SetMap<Class<? extends CdmBase>, Integer> map = getUpdateResultStatistics(result);
+            reportSb.append("Update successful. \n"
+              + "Updated Objects: " + map.sizeAll() + "\n================\n");
+            for (Class<? extends CdmBase> clazz : map.keySet()){
+                reportSb.append( CdmUtils.userFriendlyClassName(clazz)+": " + map.get(clazz).size() + "\n");
+            }
+        }
+        if (!result.getExceptions().isEmpty()){
+            reportSb.append(result.getExceptions().toString());
+        }
+    }
+
+    //TODO move to cdmlib
+    public static SetMap<Class<? extends CdmBase>, Integer> getUpdateResultStatistics(UpdateResult result) {
+        SetMap<Class<? extends CdmBase>, Integer> map = new SetMap<>();
+        for (CdmBase cdmBase : result.getUpdatedObjects()){
+            map.putItem(cdmBase.getClass(), cdmBase.getId());
+        }
+        for (CdmEntityIdentifier entity : result.getUpdatedCdmIds()){
+            map.putItem(entity.getCdmClass(), entity.getId());
+        }
+
+        return map;
+    }
+
     private static void createExportResult(final String label, String urlString, boolean createZip,
             IRemotingProgressMonitor remotingMonitor) {
 
@@ -788,7 +784,7 @@ public abstract class AbstractUtility {
             }
 
             if (urlString != null){
-                 ExportDataWrapper data = result.getExportData();
+                 ExportDataWrapper<?> data = result.getExportData();
                  try{
                      if (result.getExportData().getType().equals(ExportResultType.BYTE_ARRAY)){
                          byte[] exportData = (byte[])data.getExportData();
@@ -810,7 +806,8 @@ public abstract class AbstractUtility {
                          String fileEnding = ".csv";
 
                          if (createZip){
-                             File file = new File(urlString+File.separator +  sdf.format(cal.getTime())+ ".zip");
+//                             File file = new File(urlString+File.separator +  sdf.format(cal.getTime())+ ".zip");
+                             File file = new File(urlString+ ".zip");
                              FileOutputStream stream = new FileOutputStream(file);
                              ZipOutputStream zos = new ZipOutputStream(stream);
                              for (String key: keySet){
@@ -852,10 +849,12 @@ public abstract class AbstractUtility {
                      }
                  } catch(Exception e){
                      logger.error(e.getStackTrace());
+                     e.printStackTrace();
                  }
             }
         }
     }
+
     public static void updateNameEditors(Set<Taxon> taxaToUpdate){
         for (Taxon tax: taxaToUpdate){
             if (tax != null){
@@ -863,6 +862,4 @@ public abstract class AbstractUtility {
             }
         }
     }
-
-
-}
+}
\ No newline at end of file