eu.etaxonomy.taxeditor.store/hibernate.log
eu.etaxonomy.taxeditor.store/target
eu.etaxonomy.taxeditor.test/screenshots/*.jpeg
+eu.etaxonomy.taxeditor.test/src/test/resources/.cdm-server-ehcache
+eu.etaxonomy.taxeditor.test/src/test/resources/.cdmLibrary/remote-webapp
eu.etaxonomy.taxeditor.test/target
+eu.etaxonomy.taxeditor.webapp/lib/cdmlib-remote-webapp.war
eu.etaxonomy.taxeditor/.settings
eu.etaxonomy.taxeditor/target
/runtime-taxeditor.product
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry including="**/*.java" kind="src" path="src/main/java"/>
<classpathentry kind="src" path="src/test/java"/>
+ <classpathentry kind="src" path="src/main/resources/"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>
Bundle-Localization: OSGI-INF/l10n/plugin
Export-Package: eu.etaxonomy.taxeditor
Bundle-ActivationPolicy: lazy
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Import-Package: eu.etaxonomy.cdm.database,
org.apache.log4j,
org.eclipse.equinox.app,
import org.eclipse.ui.IPlaceholderFolderLayout;
import org.eclipse.ui.progress.IProgressConstants;
+import eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView;
import eu.etaxonomy.taxeditor.editor.view.descriptive.DescriptiveViewPart;
import eu.etaxonomy.taxeditor.navigation.navigator.TaxonNavigator;
-import eu.etaxonomy.taxeditor.view.derivateSearch.DerivateSearchView;
import eu.etaxonomy.taxeditor.view.datasource.CdmDataSourceViewPart;
import eu.etaxonomy.taxeditor.view.detail.DetailsViewPart;
public static final String ADDITIONAL = "additional";
- /* (non-Javadoc)
- * @see org.eclipse.ui.IPerspectiveFactory#createInitialLayout(org.eclipse.ui.IPageLayout)
- */
@Override
public void createInitialLayout(IPageLayout layout) {
layout.addView(TaxonNavigator.ID, IPageLayout.LEFT, 0.25f, layout.getEditorArea());
layout.addView(DetailsViewPart.ID, IPageLayout.RIGHT, 0.6f, layout.getEditorArea());
- layout.addView(DerivateSearchView.ID, IPageLayout.TOP, 0.5f, layout.getEditorArea());
+ layout.addView(DerivateView.ID, IPageLayout.BOTTOM, 0.5f, layout.getEditorArea());
layout.addView(DescriptiveViewPart.ID, IPageLayout.BOTTOM, 0.6f, TaxonNavigator.ID);
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry including="**/*.java" kind="src" path="src/main/java"/>
<classpathentry including="**/*.java" kind="src" path="src/test/java"/>
org.eclipse.core.expressions,
eu.etaxonomy.taxeditor.store,
eu.etaxonomy.taxeditor.cdmlib
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Bundle-ActivationPolicy: lazy
Import-Package: eu.etaxonomy.taxeditor.editor,
org.eclipse.core.runtime,
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorInput;
import eu.etaxonomy.cdm.api.service.ITaxonService;
import eu.etaxonomy.cdm.api.service.IUserService;
import eu.etaxonomy.cdm.api.service.config.NameDeletionConfigurator;
+import eu.etaxonomy.cdm.api.service.config.SynonymDeletionConfigurator;
+import eu.etaxonomy.cdm.api.service.config.TaxonDeletionConfigurator;
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
import eu.etaxonomy.cdm.model.common.Group;
import eu.etaxonomy.cdm.model.common.User;
import eu.etaxonomy.taxeditor.model.DeleteResultMessagingUtils;
import eu.etaxonomy.taxeditor.model.MessagingUtils;
import eu.etaxonomy.taxeditor.store.CdmStore;
+import eu.etaxonomy.taxeditor.ui.dialog.deleteConfigurator.DeleteConfiguratorDialog;
+import eu.etaxonomy.taxeditor.ui.dialog.deleteConfigurator.DeleteTaxonConfiguratorComposite;
/**
ITaxonService service = controller.getTaxonService();
if (object != null){
if (object instanceof Taxon){
- result = service.deleteTaxon(((TaxonBase) object).getUuid(), null, null);
+ TaxonDeletionConfigurator config = new TaxonDeletionConfigurator();
+ config.setDeleteInAllClassifications(true);
+ DeleteConfiguratorDialog dialog = new DeleteConfiguratorDialog(config, HandlerUtil.getActiveShell(event), "Confirm Deletion", null, "Do you really want to delete the taxon", MessageDialog.WARNING, new String[] { "Delete", "Skip" }, 0);
+ int result_dialog= dialog.open();
+ if (result_dialog == 1){
+ return null;
+ }
+ result = service.deleteTaxon(((TaxonBase) object).getUuid(), config, null);
errorMessage = "The taxon ";
}else{
- result = service.deleteSynonym(((Synonym)object).getUuid(), null);
+ SynonymDeletionConfigurator config = new SynonymDeletionConfigurator();
+ DeleteConfiguratorDialog dialog = new DeleteConfiguratorDialog(config, HandlerUtil.getActiveShell(event), "Confirm Deletion", null, "Do you really want to delete the synonym", MessageDialog.WARNING, new String[] { "Delete", "Skip" }, 0);
+ int result_dialog= dialog.open();
+ if (result_dialog == 1){
+ return null;
+ }
+ result = service.deleteSynonym(((Synonym)object).getUuid(), config);
errorMessage = "The synonym ";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src/main/java"/>
<classpathentry kind="src" path="src/main/resources"/>
<classpathentry exported="true" kind="lib" path="lib/cdmlib-ext-3.12.0-SNAPSHOT.jar"/>
<classpathentry exported="true" kind="lib" path="lib/cdmlib-io-3.12.0-SNAPSHOT.jar"/>
<classpathentry exported="true" kind="lib" path="lib/cdmlib-model-3.12.0-SNAPSHOT.jar"/>
- <classpathentry exported="true" kind="lib" path="lib/cdmlib-persistence-3.12.0-SNAPSHOT.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/cdmlib-persistence-3.12.0-SNAPSHOT.jar" sourcepath="/home/cmathew/.m2/repository/eu/etaxonomy/cdmlib-persistence/3.12.0-SNAPSHOT/cdmlib-persistence-3.12.0-SNAPSHOT-sources.jar"/>
<classpathentry exported="true" kind="lib" path="lib/cdmlib-print-3.12.0-SNAPSHOT.jar"/>
<classpathentry exported="true" kind="lib" path="lib/cdmlib-remote-3.12.0-SNAPSHOT.jar"/>
<classpathentry exported="true" kind="lib" path="lib/cdmlib-services-3.12.0-SNAPSHOT.jar"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>
-
org.springframework.ui,
javax.servlet.http"
Bundle-Vendor: EDIT
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Require-Bundle: org.eclipse.osgi,
org.eclipse.equinox.common,
org.apache.commons.httpclient;bundle-version="3.1.0",
URL fileURL = bundle.getEntry(jar);
File file = null;
try {
- String urlString = FileLocator.resolve(fileURL).toExternalForm().replace(" ", "%20");;
+ String urlString = FileLocator.resolve(fileURL).toExternalForm().replace(" ", "%20");
file = new File(new URI(urlString));
JarFile jarFile = new JarFile(file);
Manifest manifest = jarFile.getManifest();
cache = new Cache(getEntityCacheConfiguration(cacheId));
+ CacheManager.create().removeCache(cache.getName());
CacheManager.create().addCache(cache);
this.cdmEntitySessionManager = cdmEntitySessionManager;
--- /dev/null
+// $Id$
+/**
+* Copyright (C) 2015 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* 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.remoting.server;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang.StringEscapeUtils;
+
+import eu.etaxonomy.cdm.api.application.CdmApplicationUtils;
+import eu.etaxonomy.cdm.config.CdmPersistentXMLSource.CdmSourceProperties;
+import eu.etaxonomy.cdm.database.CdmPersistentDataSource;
+
+/**
+ * @author cmathew
+ * @date 11 Nov 2015
+ *
+ */
+public class CDMServerUtils {
+
+
+ public static String convertEditorToServerConfig() {
+ StringBuilder configStringBuilder = new StringBuilder();
+ configStringBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?> " + System.lineSeparator());
+ configStringBuilder.append("<!-- DO NOT EDIT THIS FILE MANUALLY. -->");
+ configStringBuilder.append("<!-- It is created by the Taxonomic Editor for launching a managed CDM Server. -->");
+ configStringBuilder.append("<beans xmlns=\"http://www.springframework.org/schema/beans\"" + System.lineSeparator());
+ configStringBuilder.append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + System.lineSeparator());
+ configStringBuilder.append(" xmlns:tx=\"http://www.springframework.org/schema/tx\"" + System.lineSeparator());
+ configStringBuilder.append(" xmlns:context=\"http://www.springframework.org/schema/context\"" + System.lineSeparator());
+ configStringBuilder.append(" xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" + System.lineSeparator());
+ configStringBuilder.append(" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" + System.lineSeparator());
+ configStringBuilder.append(" http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" + System.lineSeparator());
+ configStringBuilder.append("\">" + System.lineSeparator());
+ configStringBuilder.append(" <bean id=\"dataSourceProperties\" class=\"eu.etaxonomy.cdm.remote.config.DataSourceProperties\">" + System.lineSeparator());
+ configStringBuilder.append(" <property name=\"propsMap\">" + System.lineSeparator());
+ configStringBuilder.append(" <map/>" + System.lineSeparator());
+ configStringBuilder.append(" </property>" + System.lineSeparator());
+ configStringBuilder.append(" </bean>" + System.lineSeparator());
+
+ for(CdmPersistentDataSource dataSource : CdmPersistentDataSource.getAllDataSources()) {
+ String beanId = dataSource.getName();
+ String user = dataSource.getUsername();
+ String password = dataSource.getPassword();
+ String driverClass = dataSource.getCdmSourceProperty(CdmSourceProperties.DRIVER_CLASS);
+ String jdbcUrl = StringEscapeUtils.escapeXml(dataSource.getCdmSourceProperty(CdmSourceProperties.URL));
+ configStringBuilder.append(" <bean id=\"" + beanId + "\" lazy-init=\"true\" class=\"com.mchange.v2.c3p0.ComboPooledDataSource\">" + System.lineSeparator());
+ configStringBuilder.append(" <property name=\"driverClass\" value=\"" + driverClass + "\"/>" + System.lineSeparator());
+ configStringBuilder.append(" <property name=\"user\" value=\"" + user + "\"/>" + System.lineSeparator());
+ configStringBuilder.append(" <property name=\"password\" value=\"" + password + "\"/>" + System.lineSeparator());
+ configStringBuilder.append(" <property name=\"jdbcUrl\" value=\"" + jdbcUrl + "\"/>" + System.lineSeparator());
+ configStringBuilder.append(" </bean>" + System.lineSeparator());
+
+ }
+ configStringBuilder.append("</beans>" + System.lineSeparator());
+
+ return configStringBuilder.toString();
+ }
+
+ public static File writeManagedServerConfig(String config, String fileName) throws IOException {
+ File managedConfigFile = new File(CdmApplicationUtils.getWritableResourceDir(), fileName);
+ if(managedConfigFile.exists()) {
+ managedConfigFile.delete();
+ }
+ if(managedConfigFile.createNewFile()) {
+ FileUtils.writeStringToFile(managedConfigFile, config);
+ }
+ return managedConfigFile;
+ }
+
+}
private final static int PORT_LOCALHOST_DEV = 8080;
private final static String BASEPATH_LOCALHOST_DEV = "";
+ public final static int NULL_PORT = -1;
+ public final static String NULL_PORT_STRING = "N/A";
+
+
private final String name;
private final String server;
- private final int port;
+ private int port;
private final List<CdmInstanceInfo> instances;
private static List<CdmServerInfo> cdmServerInfoList;
public CdmInstanceInfo addInstance(String name, String basePath) {
- CdmInstanceInfo cii = new CdmInstanceInfo(name, basePath);
+ String _basePath = basePath;
+ if(isLocalhostMgd()) {
+ _basePath = "";
+ }
+ CdmInstanceInfo cii = new CdmInstanceInfo(name, _basePath);
instances.add(cii);
return cii;
}
public void addInstancesFromDataSourcesConfig() {
-
for(ICdmDataSource dataSource : CdmPersistentDataSource.getAllDataSources()){
- logger.warn("Adding local instance " + dataSource.getName());
+ logger.info("Adding local instance " + dataSource.getName());
addInstance(dataSource.getName(), dataSource.getName());
}
-
}
public String toString(String instanceName, int port) {
}
public boolean pingServer() {
+ if(isLocalhostMgd()) {
+ return true;
+ }
try {
Socket s = new Socket(server, port);
logger.info("[CDM-Server] Available @ " + server + ":" + port );
cdmServerInfoList.add(new CdmServerInfo(NAME_DEMO_2, SERVER_DEMO_2, 80));
cdmServerInfoList.add(new CdmServerInfo(NAME_TEST, SERVER_TEST, 80));
cdmServerInfoList.add(new CdmServerInfo(NAME_LOCALHOST, SERVER_LOCALHOST, 8080));
- cdmServerInfoList.add(new CdmServerInfo(NAME_LOCALHOST_MGD, SERVER_LOCALHOST,8080));
+ cdmServerInfoList.add(new CdmServerInfo(NAME_LOCALHOST_MGD, SERVER_LOCALHOST,NULL_PORT));
}
return cdmServerInfoList;
}
return port;
}
+ public void setPort(int port) {
+ this.port = port;
+ }
public List<CdmInstanceInfo> getInstances() throws CDMServerException {
if(instances.isEmpty()) {
/**
* The full path of the instance including the the prefix (if any).
* E.g. for an EDIT instance this would be something like "cdmserver/remoting"
- * For a managed local server this would simply be "remoting"
+ * For a managed local server this would simply be ""
*/
private final String basePath;
-<?xml version="1.0" encoding="UTF-8"?>\r
-<classpath>\r
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
- <classpathentry including="**/*.java" kind="src" path="src/main/java"/>\r
- <classpathentry including="**/*.java" kind="src" path="src/test/java"/>\r
- <classpathentry excluding="**/*.java" kind="src" path="src/main/resources"/>\r
- <classpathentry kind="output" path="target/classes"/>\r
-</classpath>\r
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry including="**/*.java" kind="src" path="src/main/java"/>
+ <classpathentry including="**/*.java" kind="src" path="src/test/java"/>
+ <classpathentry excluding="**/*.java" kind="src" path="src/main/resources"/>
+ <classpathentry kind="output" path="target/classes"/>
+</classpath>
eu.etaxonomy.taxeditor.editor.name.operation,
eu.etaxonomy.taxeditor.editor.view.concept,
eu.etaxonomy.taxeditor.editor.view.dataimport,
+ eu.etaxonomy.taxeditor.editor.view.derivate,
eu.etaxonomy.taxeditor.editor.view.descriptive,
eu.etaxonomy.taxeditor.editor.view.media,
eu.etaxonomy.taxeditor.editor.view.uses
org.eclipse.zest.layouts,
eu.etaxonomy.taxeditor.cdmlib,
org.eclipse.ui.ide
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Bundle-ActivationPolicy: lazy
Import-Package: org.eclipse.core.databinding.beans,
org.eclipse.core.databinding.observable.list,
command.name.24 = New Name\r
command.name.25 = New Team\r
command.name.26 = New Person\r
-command.name.27 = New Specimen\r
category.name.5 = -- Polytomous Keys\r
command.name.28 = New Child Node\r
command.name.29 = New Sibling Node\r
command.name.48 = delete\r
command.name.49 = delete\r
command.name.50 = delete\r
-command.name.51 = delete
\ No newline at end of file
+command.name.51 = delete
command.name.24 = Neuer Name
command.name.25 = Neues Team
command.name.26 = Neue Person
-command.name.27 = Neuer Beleg
category.name.5 = -- Polytomer Bestimmungsschl\u00fcssel
command.name.28 = Neue Kinderknoten
command.name.29 = Neuer Geschwisterknoten
command.name.24 = New Name\r
command.name.25 = New Team\r
command.name.26 = New Person\r
-command.name.27 = New Specimen\r
category.name.5 = -- Polytomous Keys\r
command.name.28 = New Child Node\r
command.name.29 = New Sibling Node\r
id="eu.etaxonomy.taxeditor.editor.group.authority"
name="%editor.name.4">
</editor>
- <editor
- class="eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView"
- default="false"
- icon="icons/derivate_view-16x16-32.png"
- id="eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView"
- name="%editor.name.5">
- </editor>
<editor
class="eu.etaxonomy.taxeditor.editor.view.dataimport.SpecimenImportEditor"
default="false"
id="eu.etaxonomy.taxeditor.editor.view.checklist.ChecklistEditor"
name="%editor.name.8">
</editor>
+ <editor
+ class="eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView"
+ default="false"
+ icon="icons/derivate_view-16x16-32.png"
+ id="eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView"
+ name="Derivative Editor">
+ </editor>
</extension>
<extension
point="org.eclipse.ui.views">
name="eu.etaxonomy.navigation.menu.new.separator2"
visible="true">
</separator>
- <command
- commandId="eu.etaxonomy.taxeditor.editor.command.new.specimen"
- label="%command.label.3"
- style="push">
- <visibleWhen
- checkEnabled="true">
- <reference
- definitionId="isCdmStoreConnected">
- </reference>
- </visibleWhen>
- </command>
<separator
name="eu.etaxonomy.navigation.menu.new.separator3"
visible="true">
</menuContribution>
<menuContribution
locationURI="menu:eu.etaxonomy.taxeditor.menu.showView?before=eu.etaxonomy.taxeditor.store.showViewMenu.details">
- <separator
- name="eu.etaxonomy.taxeditor.editor.showViewMenu"
- visible="true">
- </separator>
<command
commandId="org.eclipse.ui.views.showView"
label="%command.label.4"
</and>
</visibleWhen>
</command>
+ <separator
+ name="eu.etaxonomy.taxeditor.store.separator_derivative_start"
+ visible="true">
+ </separator>
+ <command
+ commandId="eu.etaxonomy.taxeditor.editor.openSpecimenEditor"
+ label="Derivative Editor"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <reference
+ definitionId="isCdmStoreConnected">
+ </reference>
+ </visibleWhen>
+ </command>
+ <separator
+ name="eu.etaxonomy.taxeditor.editor.separator1"
+ visible="true">
+ </separator>
+ </menuContribution>
+ <menuContribution
+ locationURI="menu:eu.etaxonomy.taxeditor.menu.showView?after=org.eclipse.ui.views.showView.supplemental">
+ <separator
+ name="eu.etaxonomy.taxeditor.store.showViewMenu.validation.separator"
+ visible="true">
+ </separator>
+ <command
+ commandId="org.eclipse.ui.views.showView"
+ label="%command.name.40"
+ style="push">
+ <parameter
+ name="org.eclipse.ui.views.showView.viewId"
+ value="eu.etaxonomy.taxeditor.editor.view.validation.problems">
+ </parameter>
+ <visibleWhen
+ checkEnabled="true">
+ <reference
+ definitionId="isCdmStoreConnected">
+ </reference>
+ </visibleWhen>
+ </command>
</menuContribution>
<menuContribution
locationURI="menu:org.eclipse.ui.main.menu.navigate">
</or>
</visibleWhen>
</menu>
- <separator
- name="taxeditor-editor.separator1"
- visible="true">
- </separator>
- <command
- commandId="eu.etaxonomy.taxeditor.editor.handler.openDerivateView"
- label="%command.label.51"
- style="push">
- <visibleWhen
- checkEnabled="true">
- <and>
- <with
- variable="selection">
- <count
- value="+">
- </count>
- </with>
- <reference
- definitionId="isIndividualsAssociation">
- </reference>
- </and>
- </visibleWhen>
- </command>
<command
commandId="eu.etaxonomy.taxeditor.editor.view.descriptive.command.moveDescriptionToTaxon"
label="%command.label.28"
label="%command.label.52"
style="push">
</command>
- <command
- commandId="eu.etaxonomy.taxeditor.editor.derivate.createFieldUnit"
- label="%command.label.53"
- style="push">
- </command>
<command
commandId="eu.etaxonomy.taxeditor.editor.derivate.deepDelete"
icon="icons/deep-delete-16x16-32.png"
</menuContribution>
<menuContribution
allPopups="false"
- locationURI="popup:eu.etaxonomy.taxeditor.navigation.navigatorpopup?after=taxeditor-navigation.separator2">
- <command
- commandId="eu.etaxonomy.taxeditor.editor.handler.openDerivateView"
- label="%command.label.55"
- style="push">
- <visibleWhen
- checkEnabled="false">
- <and>
- <reference
- definitionId="isCdmStoreConnected">
- </reference>
- <reference
- definitionId="isTaxonNode">
- </reference>
- </and>
- </visibleWhen>
- </command>
- <separator
- name="eu.etaxonomy.taxeditor.editor.separator1"
- visible="true">
- </separator>
- </menuContribution>
- <menuContribution
- locationURI="menu:eu.etaxonomy.taxeditor.menu.showView?after=org.eclipse.ui.views.showView.supplemental">
- <separator
- name="eu.etaxonomy.taxeditor.store.showViewMenu.validation.separator"
- visible="true">
- </separator>
- <command
- commandId="org.eclipse.ui.views.showView"
- label="%command.name.40"
- style="push">
- <parameter
- name="org.eclipse.ui.views.showView.viewId"
- value="eu.etaxonomy.taxeditor.editor.view.validation.problems">
- </parameter>
- <visibleWhen
- checkEnabled="true">
- <reference
- definitionId="isCdmStoreConnected">
- </reference>
- </visibleWhen>
- </command>
+ locationURI="toolbar:org.eclipse.ui.main.toolbar?after=eu.etaxonomy.taxeditor.navigation.search.toolbar">
+ <toolbar
+ id="eu.etaxonomy.taxeditor.editor.derivativeViewToolbar">
+ <command
+ commandId="eu.etaxonomy.taxeditor.editor.derivative.listenToSelectionChange"
+ icon="icons/synced.gif"
+ label="Link with Taxon Selection"
+ style="toggle">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="activePartId">
+ <equals
+ value="eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView">
+ </equals>
+ </with>
+ </visibleWhen>
+ </command>
+ </toolbar>
</menuContribution>
</extension>
<extension
</with>
</activeWhen>
</handler>
- <handler
- class="eu.etaxonomy.taxeditor.editor.view.derivate.handler.OpenDerivateEditorForTaxonHandler"
- commandId="eu.etaxonomy.taxeditor.editor.handler.openDerivateView">
- <activeWhen>
- <with
- variable="activePartId">
- <equals
- value="eu.etaxonomy.taxeditor.navigation.navigator">
- </equals>
- </with>
- </activeWhen>
- </handler>
<handler
class="eu.etaxonomy.taxeditor.editor.view.descriptive.handler.ToggleShowOnlyIndividualAssociationsHandler"
commandId="eu.etaxonomy.taxeditor.editor.handler.showOnlyIndividualAssociations">
id="eu.etaxonomy.taxeditor.editor.command.new.person"
name="%command.name.26">
</command>
- <command
- categoryId="eu.etaxonomy.taxeditor.editor.new.category"
- defaultHandler="eu.etaxonomy.taxeditor.editor.handler.create.NewSpecimenHandler"
- id="eu.etaxonomy.taxeditor.editor.command.new.specimen"
- name="%command.name.27">
- </command>
<category
id="eu.etaxonomy.taxeditor.editor.key.category"
name="%category.name.5">
defaultHandler="eu.etaxonomy.taxeditor.editor.group.authority.handler.EditCdmAuthoritiesHandler"
id="eu.etaxonomy.taxeditor.group.cdmauthorities.edit"
name="%command.name.34">
- </command>
- <command
- defaultHandler="eu.etaxonomy.taxeditor.editor.handler.OpenDerivateViewHandler"
- id="eu.etaxonomy.taxeditor.editor.handler.openDerivateView"
- name="%command.name.35">
</command>
<command
defaultHandler="eu.etaxonomy.taxeditor.editor.handler.OpenChecklistEditorHandler"
id="eu.etaxonomy.taxeditor.editor.taxonParameterType"
type="eu.etaxonomy.cdm.model.taxon.TaxonBase">
</commandParameterType>
- <command
- defaultHandler="eu.etaxonomy.taxeditor.editor.view.derivate.handler.CreateFieldUnitHandler"
- id="eu.etaxonomy.taxeditor.editor.derivate.createFieldUnit"
- name="%command.name.43">
- </command>
<command
defaultHandler="eu.etaxonomy.taxeditor.editor.view.derivate.handler.DeleteDerivateHandler"
id="eu.etaxonomy.taxeditor.editor.derivate.deepDelete"
<command
defaultHandler="eu.etaxonomy.taxeditor.editor.handler.OpenDerivateViewHandler"
id="eu.etaxonomy.taxeditor.editor.openSpecimenEditor"
- name="Open Specimen Editor">
+ name="Open Derivative Editor">
<commandParameter
id="eu.etaxonomy.taxeditor.specimenUuidParameter"
name="Specimen UUID parameter"
typeId="eu.etaxonomy.taxeditor.specimenUuidParameterType">
</commandParameter>
</command>
+ <command
+ defaultHandler="eu.etaxonomy.taxeditor.editor.view.derivate.handler.ListenToSelectionChangeHandler"
+ id="eu.etaxonomy.taxeditor.editor.derivative.listenToSelectionChange"
+ name="Link with taxon selection">
+ </command>
</extension>
<extension
package eu.etaxonomy.taxeditor.editor.handler;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-import java.util.UUID;
-
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.handlers.HandlerUtil;
-import eu.etaxonomy.cdm.model.description.IndividualsAssociation;
-import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
import eu.etaxonomy.taxeditor.editor.EditorUtil;
import eu.etaxonomy.taxeditor.editor.view.derivate.DerivateViewEditorInput;
import eu.etaxonomy.taxeditor.model.MessagingUtils;
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
- Set<UUID> selectedElementUUIDs = new HashSet<UUID>();
- Object parameter;
- //check if parameter is set
try {
- parameter = event.getObjectParameterForExecution("eu.etaxonomy.taxeditor.specimenUuidParameter");
- } catch (ExecutionException e) {
- parameter = null;
- }
- if(parameter instanceof UUID){
- selectedElementUUIDs.add((UUID) parameter);
- }
- else{
- //if not, try with current selection
- ISelection currentSelection = HandlerUtil.getCurrentSelection(event);
- if(currentSelection instanceof IStructuredSelection){
- Iterator<?> selectionIterator = ((IStructuredSelection) currentSelection).iterator();
- while(selectionIterator.hasNext()){
- Object object = selectionIterator.next();
- if(object instanceof SpecimenOrObservationBase<?>){
- selectedElementUUIDs.add(((SpecimenOrObservationBase<?>) object).getUuid());
- }
- else if(object instanceof IndividualsAssociation){
- SpecimenOrObservationBase specimen = ((IndividualsAssociation) object).getAssociatedSpecimenOrObservation();
- if(specimen!=null){
- selectedElementUUIDs.add(specimen.getUuid());
- }
- }
- }
- }
- }
- if(!selectedElementUUIDs.isEmpty()){
- DerivateViewEditorInput input = new DerivateViewEditorInput(selectedElementUUIDs);
- try {
- EditorUtil.open(input);
- } catch (PartInitException e) {
- MessagingUtils.error(OpenDerivateViewHandler.class, "Could not open Derivative Editor", e);
- } catch (NullPointerException npe){
- MessagingUtils.messageDialog("Failed to open Editor", OpenDerivateViewHandler.class, "Could not open Derivative Editor. The derivate hierarchy is corrupted!", npe);
- }
- }
- else{
- MessagingUtils.informationDialog("Empty selection", "No Specimen selected.");
+ EditorUtil.open(new DerivateViewEditorInput());
+ } catch (PartInitException e) {
+ MessagingUtils.error(OpenDerivateViewHandler.class, "Derivative Editor could not be opened", e);
}
return null;
}
+++ /dev/null
-// $Id$
-/**
-* Copyright (C) 2007 EDIT
-* European Distributed Institute of Taxonomy
-* http://www.e-taxonomy.eu
-*
-* 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.editor.handler.create;
-
-import org.apache.log4j.Logger;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-import eu.etaxonomy.taxeditor.newWizard.NewDerivedUnitBaseWizard;
-
-/**
- * @author n.hoffmann
- * @created Jun 16, 2010
- * @version 1.0
- */
-public class NewSpecimenHandler extends AbstractHandler {
- private static final Logger logger = Logger
- .getLogger(NewSpecimenHandler.class);
-
- /** {@inheritDoc} */
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- //TODO: we need to discuss how specimens should be created and handled #5244
-// ConversationHolder conversation = CdmStore.createConversation();
-// conversation.bind();
-// FieldUnit fieldUnit = FieldUnit.NewInstance();
-// DerivedUnit derivedUnit = DerivedUnit.NewInstance(SpecimenOrObservationType.PreservedSpecimen);
-// DerivationEvent.NewSimpleInstance(fieldUnit, derivedUnit, DerivationEventType.GATHERING_IN_SITU());
-// fieldUnit.setCacheStrategy(new DerivedUnitFacadeFieldUnitCacheStrategy());
-// derivedUnit.setCacheStrategy(new DerivedUnitFacadeCacheStrategy());
-// CdmStore.getService(IOccurrenceService.class).save(fieldUnit);
-// CdmStore.getService(IOccurrenceService.class).save(derivedUnit);
-// conversation.commit();
-// DerivateViewEditorInput input = new DerivateViewEditorInput(Collections.singleton(fieldUnit.getUuid()));
-// try {
-// EditorUtil.open(input);
-// } catch (PartInitException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// }
- NewDerivedUnitBaseWizard wizard = new NewDerivedUnitBaseWizard();
- wizard.init(null, null);
- WizardDialog dialog = new WizardDialog(HandlerUtil.getActiveShell(event), wizard);
- dialog.open();
- return null;
- }
-}
package eu.etaxonomy.taxeditor.editor.view.derivate;
+import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
+import java.util.HashMap;
import java.util.HashSet;
-import java.util.Map.Entry;
+import java.util.List;
+import java.util.Map;
import java.util.Set;
+import java.util.UUID;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeNode;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
+import org.eclipse.ui.IMemento;
+import org.eclipse.ui.ISelectionListener;
+import org.eclipse.ui.ISelectionService;
+import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;
import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
import eu.etaxonomy.cdm.api.conversation.IConversationEnabled;
-import eu.etaxonomy.cdm.api.service.molecular.ISequenceService;
+import eu.etaxonomy.cdm.api.service.IOccurrenceService;
+import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
import eu.etaxonomy.cdm.model.common.CdmBase;
-import eu.etaxonomy.cdm.model.molecular.Sequence;
import eu.etaxonomy.cdm.model.molecular.SingleRead;
+import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
+import eu.etaxonomy.cdm.model.taxon.Taxon;
+import eu.etaxonomy.cdm.model.taxon.TaxonNode;
import eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap;
+import eu.etaxonomy.taxeditor.editor.EditorUtil;
import eu.etaxonomy.taxeditor.editor.Messages;
+import eu.etaxonomy.taxeditor.editor.view.derivate.searchFilter.DerivateSearchCompositeController;
+import eu.etaxonomy.taxeditor.model.IContextListener;
import eu.etaxonomy.taxeditor.model.IDirtyMarkable;
import eu.etaxonomy.taxeditor.model.IPartContentHasDetails;
import eu.etaxonomy.taxeditor.model.IPartContentHasFactualData;
import eu.etaxonomy.taxeditor.model.IPartContentHasMedia;
import eu.etaxonomy.taxeditor.model.IPartContentHasSupplementalData;
import eu.etaxonomy.taxeditor.operation.IPostOperationEnabled;
+import eu.etaxonomy.taxeditor.session.ICdmEntitySession;
+import eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled;
import eu.etaxonomy.taxeditor.store.CdmStore;
import eu.etaxonomy.taxeditor.view.derivateSearch.DerivateContentProvider;
import eu.etaxonomy.taxeditor.view.derivateSearch.DerivateLabelProvider;
* Displays the derivate hierarchy of the specimen specified in the editor input.
*
*/
-public class DerivateView extends EditorPart implements IPartContentHasFactualData, IDirtyMarkable,
- IConversationEnabled, IPartContentHasDetails, IPartContentHasSupplementalData, IPartContentHasMedia,
- ISelectionChangedListener, IPostOperationEnabled{
-
+public class DerivateView extends EditorPart implements IPartContentHasFactualData, IConversationEnabled,
+ ICdmEntitySessionEnabled, IDirtyMarkable, IPostOperationEnabled, IPartContentHasDetails, IPartContentHasSupplementalData, IPartContentHasMedia,
+ IContextListener, ISelectionListener {
public static final String ID = "eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView"; //$NON-NLS-1$
public static final String YOU_NEED_TO_SAVE_BEFORE_PERFORMING_THIS_ACTION = Messages.DerivateView_YOU_NEED_TO_SAVE;
public static final String VIEW_HAS_UNSAVED_CHANGES = Messages.DerivateView_UNSAVED_CHANGES;
+ private static final List<String> SPECIMEN_INIT_STRATEGY = Arrays.asList(new String[] {
+ "descriptions",
+ "annotations",
+ "markers",
+ "credits",
+ "extensions",
+ "rights",
+ "sources",
+ "derivationEvents.derivatives.annotations",
+ "derivationEvents.derivatives.markers",
+ "derivationEvents.derivatives.credits",
+ "derivationEvents.derivatives.extensions",
+ "derivationEvents.derivatives.rights",
+ "derivationEvents.derivatives.sources"
+ });
+
private ConversationHolder conversation;
private TreeViewer viewer;
private DerivateLabelProvider labelProvider;
- private Set<SingleRead> multiLinkSingleReads;
+ private DerivateContentProvider contentProvider;
- private ISelection selection = null;
+ private DerivateSearchCompositeController derivateSearchCompositeController;
+ /**
+ * A map with keys being the derivative entities belonging to the {@link UUID}s passed to the constructor
+ * and values being the root elements of the hierarchy (may be the same objects as the derivative entities)
+ */
+ private Map<SpecimenOrObservationBase<?>, SpecimenOrObservationBase<?>> derivateToRootEntityMap;
- private DerivateContentProvider contentProvider;
+ /**
+ * The set of root elements
+ */
+ private Set<SpecimenOrObservationBase<?>> rootElements;
+
+ private ICdmEntitySession cdmEntitySession;
+
+ /**
+ * <code>true</code> if this view is listening to selection changes
+ */
+ private boolean listenToSelectionChange;
+
+ private Taxon selectedTaxon;
+
+ private ISelectionService selectionService;
/**
* Default constructor
public DerivateView() {
}
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void init(IEditorSite site, IEditorInput input) throws PartInitException {
+ this.setSite(site);
+ this.setInput(input);
+ this.derivateToRootEntityMap = new HashMap<SpecimenOrObservationBase<?>, SpecimenOrObservationBase<?>>();
+ this.rootElements = new HashSet<SpecimenOrObservationBase<?>>();
+
+ if (CdmStore.isActive() && conversation == null) {
+ conversation = CdmStore.createConversation();
+ }
+ if (CdmStore.isActive()) {
+ cdmEntitySession = CdmStore.getCurrentSessionManager().newSession(this, true);
+ }
+ //listen to context changes
+ CdmStore.getContextManager().addContextListener(this);
+ }
+
@Override
public void createPartControl(Composite parent) {
+
+ parent.setLayout(new GridLayout());
+
+ //---search and filter---
+ derivateSearchCompositeController = new DerivateSearchCompositeController(parent, this);
+ GridData gridDataSearchBar = new GridData();
+ gridDataSearchBar.horizontalAlignment = GridData.FILL;
+ gridDataSearchBar.grabExcessHorizontalSpace = true;
+ derivateSearchCompositeController.setLayoutData(gridDataSearchBar);
+ derivateSearchCompositeController.setEnabled(CdmStore.isActive());
+
+ //---tree viewer---
viewer = new TreeViewer(new Tree(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION));
+ GridData gridDataTree = new GridData();
+ gridDataTree.horizontalAlignment = GridData.FILL;
+ gridDataTree.verticalAlignment = GridData.FILL;
+ gridDataTree.grabExcessVerticalSpace = true;
+ gridDataTree.grabExcessHorizontalSpace = true;
+ viewer.getTree().setLayoutData(gridDataTree);
contentProvider = new DerivateContentProvider();
viewer.setContentProvider(contentProvider);
labelProvider = new DerivateLabelProvider();
labelProvider.setConversation(conversation);
viewer.setLabelProvider(labelProvider);
viewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
+ viewer.getTree().setEnabled(CdmStore.isActive());
// Propagate selection from viewer
getSite().setSelectionProvider(viewer);
+
//listen to selection changes
- viewer.addSelectionChangedListener(this);
+ selectionService = getSite().getWorkbenchWindow().getSelectionService();
+ selectionService.addSelectionListener(this);
//create context menu
MenuManager menuManager = new MenuManager();
Menu menu = menuManager.createContextMenu(control);
control.setMenu(menu);
- generateMultiLinkSingleReads();
- labelProvider.setMultiLinkSingleReads(multiLinkSingleReads);
- IEditorInput editorInput = getEditorInput();
- viewer.setInput(((DerivateViewEditorInput) editorInput).getRootEntities());
- //set selection to selected derivate if only one was selected
- if(editorInput instanceof DerivateViewEditorInput){
- Set<SpecimenOrObservationBase<?>> derivateEntities = ((DerivateViewEditorInput) editorInput).getDerivateEntities();
- if(derivateEntities.size()==1){
- SpecimenOrObservationBase<?> specimen = derivateEntities.iterator().next();
- if(specimen != null){
- viewer.setSelection(new StructuredSelection(new TreeNode(specimen)));
- }
- }
- }
+ //init tree
+ updateRootEntities();
//add drag'n'drop support
Transfer[] transfers = new Transfer[] {LocalSelectionTransfer.getTransfer(),};
viewer.addDropSupport(dndOperations, transfers, new DerivateDropListener(this));
}
+ public void updateRootEntities() {
+ updateRootEntities(null);
+ }
+
+ public void updateRootEntities(Collection<UUID> derivativeUuids) {
+ if(conversation!=null){
+ if (!conversation.isBound()) {
+ conversation.bind();
+ }
+ /*
+ * If the active session is not the session of the Derivate Editor then we will
+ * save it, bind temporarily to our session and rebind to the original session.
+ * This happens e.g. if a selection change happens in the taxon editor and
+ * "Link with editor" is enabled. The selection change event and thus the
+ * loading in updateRootEntities() happens in the session of the taxon
+ * editor.
+ */
+ ICdmEntitySession previousCdmEntitySession = CdmStore.getCurrentSessionManager().getActiveSession();
+ if(cdmEntitySession != null) {
+ cdmEntitySession.bind();
+ }
+
+ if(derivativeUuids!=null){
+ this.derivateToRootEntityMap = new HashMap<SpecimenOrObservationBase<?>, SpecimenOrObservationBase<?>>();
+ this.rootElements = new HashSet<SpecimenOrObservationBase<?>>();
+ for (UUID uuid : derivativeUuids) {
+ SpecimenOrObservationBase<?> derivate = CdmStore.getService(IOccurrenceService.class).load(uuid, SPECIMEN_INIT_STRATEGY);
+ if(derivate instanceof FieldUnit){
+ derivateToRootEntityMap.put(derivate, derivate);
+ }
+ else {
+ SpecimenOrObservationBase<?> topMostDerivate = EditorUtil.getTopMostDerivate(derivate);
+ if(topMostDerivate!=null){
+ derivateToRootEntityMap.put(derivate, topMostDerivate);
+ }
+ else{
+ derivateToRootEntityMap.put(derivate, derivate);
+ }
+ }
+ }
+ for (SpecimenOrObservationBase<?> specimen : derivateToRootEntityMap.values()) {
+ rootElements.add(specimen);
+ }
+ }
+ viewer.setInput(rootElements);
+ refreshTree(false);
+ previousCdmEntitySession.bind();
+ }
+ }
+
@Override
public void doSave(IProgressMonitor monitor) {
String taskName = Messages.DerivateView_SAVING_HIERARCHY;
- if(getEditorInput() instanceof DerivateViewEditorInput){
- DerivateViewEditorInput derivateViewEditorInput = (DerivateViewEditorInput) getEditorInput();
- taskName += " "+derivateViewEditorInput.getName(); //$NON-NLS-1$
- }
monitor.beginTask(taskName, 3);
if (!conversation.isBound()) {
conversation.bind();
// commit the conversation and start a new transaction immediately
conversation.commit(true);
- ((DerivateViewEditorInput) getEditorInput()).merge();
+
+ if(CdmStore.getCurrentSessionManager().isRemoting()) {
+ CdmStore.getService(IOccurrenceService.class).merge(new ArrayList<SpecimenOrObservationBase>(rootElements), true);
+ }
monitor.worked(1);
this.setDirty(false);
@Override
public String getTitleToolTip() {
- if(getEditorInput() instanceof DerivateViewEditorInput){
- DerivateViewEditorInput derivateViewEditorInput = (DerivateViewEditorInput) getEditorInput();
- return derivateViewEditorInput.getName();
- }
return Messages.DerivateView_DERIVATIVE_EDITOR;
}
- @Override
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
- setSite(site);
- setInput(input);
- if(input instanceof DerivateViewEditorInput){
- DerivateViewEditorInput derivateViewEditorInput = (DerivateViewEditorInput) input;
- conversation = derivateViewEditorInput.getConversationHolder();
- setPartName(derivateViewEditorInput.getName());
- }
- }
-
@Override
public boolean isDirty() {
return isDirty;
public void setFocus() {
viewer.getControl().setFocus();
//make sure to bind again if maybe in another view the conversation was unbound
- if(!conversation.isBound()){
+ if(conversation!=null && !conversation.isBound()){
conversation.bind();
}
- ((DerivateViewEditorInput) getEditorInput()).bind();
+ if(cdmEntitySession != null) {
+ cdmEntitySession.bind();
+ }
}
@Override
return conversation;
}
- /**
- * @return the viewer
- */
- public TreeViewer getViewer() {
- return viewer;
- }
-
@Override
public void changed(Object element) {
setDirty(true);
changed(null);
}
+ @Override
+ public Map<Object, List<String>> getPropertyPathsMap() {
+ List<String> specimenPropertyPaths = Arrays.asList(new String[] {
+ "descriptions",
+ "derivationEvents.derivates",
+ "annotations",
+ "markers",
+ "credits",
+ "extensions",
+ "rights",
+ "sources"
+ });
+ Map<Object, List<String>> specimenPropertyPathMap =
+ new HashMap<Object, List<String>>();
+ specimenPropertyPathMap.put(SpecimenOrObservationBase.class,specimenPropertyPaths);
+ return specimenPropertyPathMap;
+ }
+
/**
* Refreshes the derivate hierarchy tree and expands the tree
* to show and select the given object.
* Refreshes the derivate hierarchy tree
*/
public void refreshTree(){
- generateMultiLinkSingleReads();
- labelProvider.setMultiLinkSingleReads(multiLinkSingleReads);
- viewer.refresh();
+ refreshTree(true);
+ }
+
+ /**
+ * Refreshes the derivate hierarchy tree
+ * @param refreshViewer if <code>true</code> then also the
+ * viewer will be refreshed. This was implemented due to
+ * performance reasons. If passing <code>false</code>
+ * does what was expected use <code>false</code> preferably.
+ */
+ public void refreshTree(boolean refreshViewer){
+ //refresh typedesignations
+ labelProvider.refresh();
+ if(refreshViewer){
+ viewer.refresh();
+ }
}
//FIXME:Remoting hack to make this work for remoting
//This should actually be resolved using remoting post operations
public void remove(Object obj) {
- Set<SpecimenOrObservationBase<?>> rootEntities = ((DerivateViewEditorInput) getEditorInput()).getRootEntities();
- rootEntities.remove(obj);
- viewer.setInput(rootEntities);
- }
-
- private void generateMultiLinkSingleReads() {
- Set<SingleRead> multiLinkSingleReads = new HashSet<SingleRead>();
- for(Entry<SingleRead, Collection<Sequence>> entry:CdmStore.getService(ISequenceService.class).getSingleReadSequencesMap().entrySet()){
- if(entry.getValue().size()>1){
- multiLinkSingleReads.add(entry.getKey());
- }
- }
- this.multiLinkSingleReads = multiLinkSingleReads;
+ rootElements.remove(obj);
+ viewer.setInput(rootElements);
}
/**
* @return a set of {@link SingleRead}s that have multiple parents
*/
public Set<SingleRead> getMultiLinkSingleReads() {
- return this.multiLinkSingleReads;
+ return DerivateLabelProvider.getMultiLinkSingleReads();
}
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- this.selection = event.getSelection();
- }
-
- public ISelection getSelection() {
- return selection;
+ public Object getSelectionInput() {
+ return selectedTaxon;
}
public DerivateLabelProvider getLabelProvider() {
return true;
}
+
+ @Override
+ public boolean canAttachMedia() {
+ return true;
+ }
+
+ public void addFieldUnit(FieldUnit fieldUnit) {
+ rootElements.add(fieldUnit);
+ derivateToRootEntityMap.put(fieldUnit, fieldUnit);
+ }
+
+ @Override
+ public ICdmEntitySession getCdmEntitySession() {
+ return cdmEntitySession;
+ }
+
@Override
public void dispose() {
- ((DerivateViewEditorInput) getEditorInput()).dispose();
super.dispose();
+ if(conversation!=null){
+ conversation.close();
+ }
+ if(cdmEntitySession != null) {
+ cdmEntitySession.dispose();
+ }
}
+ @Override
+ public void selectionChanged(IWorkbenchPart part, ISelection selection) {
+ if(viewer.getTree().isDisposed()){
+ return;
+ }
+ if(listenToSelectionChange && selection instanceof IStructuredSelection){
+ Object selectedElement = ((IStructuredSelection) selection).getFirstElement();
+ if(selectedElement instanceof CdmBase){
+ if(((CdmBase) selectedElement).isInstanceOf(TaxonNode.class)){
+ selectedTaxon = HibernateProxyHelper.deproxy(selectedElement, TaxonNode.class).getTaxon();
+ }
+ else if(((CdmBase) selectedElement).isInstanceOf(Taxon.class)){
+ selectedTaxon = HibernateProxyHelper.deproxy(selectedElement, Taxon.class);
+ }
+ Collection<SpecimenOrObservationBase> fieldUnits = CdmStore.getService(IOccurrenceService.class).listFieldUnitsByAssociatedTaxon(selectedTaxon, null, null);
+ Collection<UUID> uuids = new HashSet<UUID>();
+ for (SpecimenOrObservationBase specimenOrObservationBase : fieldUnits) {
+ uuids.add(specimenOrObservationBase.getUuid());
+ }
+ updateRootEntities(uuids);
+ setPartName("Derivative Editor: " + selectedTaxon.getName());
+ }
+ }
+ }
+
+ public TreeViewer getViewer() {
+ return viewer;
+ }
+ /**
+ * {@inheritDoc}
+ */
@Override
- public boolean canAttachMedia() {
- return true;
+ public List<SpecimenOrObservationBase<?>> getRootEntities() {
+ return new ArrayList<SpecimenOrObservationBase<?>>(rootElements);
+ }
+
+ public void toggleListenToSelectionChange() {
+ listenToSelectionChange = !listenToSelectionChange;
+ derivateSearchCompositeController.setEnabled(!listenToSelectionChange);
+ if(!listenToSelectionChange){
+ selectedTaxon = null;
+ setPartName("Derivative Editor");
+ }
+ else if(selectedTaxon==null){
+ setPartName("Derivative Editor [no taxon selected]");
+ }
+ }
+
+ public boolean isListenToSelectionChange(){
+ return listenToSelectionChange;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void contextAboutToStop(IMemento memento, IProgressMonitor monitor) {
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void contextStop(IMemento memento, IProgressMonitor monitor) {
+ derivateSearchCompositeController.setEnabled(false);
+ viewer.getTree().setEnabled(false);
+ viewer.setInput(null);
}
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void contextStart(IMemento memento, IProgressMonitor monitor) {
+ derivateSearchCompositeController.setEnabled(!listenToSelectionChange);
+ viewer.getTree().setEnabled(true);
+ refreshTree();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void contextRefresh(IProgressMonitor monitor) {
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void workbenchShutdown(IMemento memento, IProgressMonitor monitor) {
+ }
+
}
*/
package eu.etaxonomy.taxeditor.editor.view.derivate;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
-
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPersistableElement;
-import eu.etaxonomy.cdm.api.application.CdmApplicationState;
-import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
-import eu.etaxonomy.cdm.api.service.IOccurrenceService;
-import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
-import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
-import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
-import eu.etaxonomy.taxeditor.editor.CdmEntitySessionInput;
-import eu.etaxonomy.taxeditor.editor.EditorUtil;
-import eu.etaxonomy.taxeditor.editor.Messages;
-import eu.etaxonomy.taxeditor.model.MessagingUtils;
-import eu.etaxonomy.taxeditor.store.CdmStore;
-import eu.etaxonomy.taxeditor.view.derivateSearch.DerivateLabelProvider;
-
/**
- * Editor input for the {@link DerivateView} which holds the currently selected derivate for which
- * the derivate hierarchy should be shown in the DerivateView.<br>
- * It also holds a {@link SpecimenOrObservationBase} which is the root of the hierarchy. (both may be the same object)
+ * Editor input for the {@link DerivateView}
+ *
* @author pplitzner
- * @date 25.11.2013
+ * @date Nov 11, 2015
*
*/
-public class DerivateViewEditorInput extends CdmEntitySessionInput implements IEditorInput {
-
- /**
- * The selected derivate {@link UUID}s
- */
- private final Set<SpecimenOrObservationBase<?>> derivateEntities;
- /**
- * List of the {@link UUID}s of the root elements of the hierarchy (may be the same objects as the derivates)
- */
- private Set<SpecimenOrObservationBase<?>> rootEntities;
- private Set<UUID> rootUUIDs;
-
- private final ConversationHolder conversationHolder;
-
- private static final List<String> SPECIMEN_INIT_STRATEGY = Arrays.asList(new String[] {
- "descriptions",
- "annotations",
- "markers",
- "credits",
- "extensions",
- "rights",
- "sources",
- "derivationEvents.derivatives.annotations",
- "derivationEvents.derivatives.markers",
- "derivationEvents.derivatives.credits",
- "derivationEvents.derivatives.extensions",
- "derivationEvents.derivatives.rights",
- "derivationEvents.derivatives.sources"
- });
-
- /**
- * Creates an editor input for the {@link DerivateView} with the currently selected derivates and the
- * corresponding {@link FieldUnit}s (both may be the same object).
- * @param derivateUuids the {@link UUID}s of the derivates for which the derivate hierarchy should be shown
- * @param rootUUIDs the root of the hierarchy
- */
- public DerivateViewEditorInput(Set<UUID> derivateUuids) {
- super(false);
- rootUUIDs = derivateUuids;
- //FIXME:Remoting temporary hack for making the sessions work
- //This should ideally be changed to initializing the
- //super class with a collection of (id) objects which can
- //then be used for the hashCode, equals methods
- initSession();
- this.conversationHolder = CdmStore.createConversation();
- this.derivateEntities = new HashSet<SpecimenOrObservationBase<?>>();
- this.rootEntities = new HashSet<SpecimenOrObservationBase<?>>();
- for (UUID uuid : derivateUuids) {
- SpecimenOrObservationBase<?> derivate = CdmStore.getService(IOccurrenceService.class).load(uuid, SPECIMEN_INIT_STRATEGY);
- derivateEntities.add(derivate);
- if(derivate instanceof FieldUnit){
- rootEntities.add(derivate);
- }
- else if(derivate instanceof DerivedUnit){
- SpecimenOrObservationBase<?> topMostDerivate = EditorUtil.getTopMostDerivate(derivate);
- if(topMostDerivate!=null){
- rootEntities.add(topMostDerivate);
- }
- }
- }
- if(rootEntities.isEmpty()){
- rootEntities = derivateEntities;
- }
- if(rootEntities.isEmpty()){
- MessagingUtils.messageDialog(Messages.DerivateViewEditorInput_FAIL_INIT, DerivateViewEditorInput.class, Messages.DerivateViewEditorInput_NO_ROOT);
- }
-
+public class DerivateViewEditorInput implements IEditorInput {
+ public DerivateViewEditorInput() {
}
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
- */
@Override
public Object getAdapter(Class adapter) {
- // TODO Auto-generated method stub
return null;
}
- /* (non-Javadoc)
- * @see org.eclipse.ui.IEditorInput#exists()
- */
@Override
public boolean exists() {
return false;
}
- /* (non-Javadoc)
- * @see org.eclipse.ui.IEditorInput#getImageDescriptor()
- */
@Override
public ImageDescriptor getImageDescriptor() {
- // TODO Auto-generated method stub
return null;
}
- /* (non-Javadoc)
- * @see org.eclipse.ui.IEditorInput#getName()
- */
@Override
public String getName() {
return getEditorName();
}
- /* (non-Javadoc)
- * @see org.eclipse.ui.IEditorInput#getPersistable()
- */
@Override
public IPersistableElement getPersistable() {
return null;
}
- /* (non-Javadoc)
- * @see org.eclipse.ui.IEditorInput#getToolTipText()
- */
@Override
public String getToolTipText() {
return getEditorName();
}
private String getEditorName() {
- String name = null;
- for( SpecimenOrObservationBase<?> specimen : rootEntities){
- if(specimen!=null){
- if(name==null){
- name = DerivateLabelProvider.getDerivateText(specimen, conversationHolder);
- }
- else{
- name += " + "+DerivateLabelProvider.getDerivateText(specimen, conversationHolder); //$NON-NLS-1$
- }
- }
- }
- return name;
- }
-
- @Override
- public Set<SpecimenOrObservationBase<?>> getRootEntities() {
- return rootEntities;
- }
-
- public Set<SpecimenOrObservationBase<?>> getDerivateEntities() {
- return derivateEntities;
- }
-
- public void addRootEntity(SpecimenOrObservationBase<?> root){
- rootEntities.add(root);
- }
-
-
- public ConversationHolder getConversationHolder() {
- return conversationHolder;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#hashCode()
- */
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((rootUUIDs == null) ? 0 : rootUUIDs.hashCode());
- return result;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- DerivateViewEditorInput other = (DerivateViewEditorInput) obj;
- if (rootUUIDs == null) {
- if (other.rootUUIDs != null) {
- return false;
- }
- } else if (!rootUUIDs.equals(other.rootUUIDs)) {
- return false;
- }
- return true;
+ return "Derivative Editor";
}
- /* (non-Javadoc)
- * @see eu.etaxonomy.taxeditor.editor.CdmEntitySessionInput#merge()
- */
- @Override
- public void merge() {
- if(CdmStore.getCurrentSessionManager().isRemoting()) {
- CdmApplicationState.getCurrentAppConfig().getOccurrenceService().merge(new ArrayList(getRootEntities()), true);
- }
-
- }
-
- /* (non-Javadoc)
- * @see eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled#getPropertyPathsMap()
- */
- @Override
- public Map<Object, List<String>> getPropertyPathsMap() {
- List<String> specimenPropertyPaths = Arrays.asList(new String[] {
- "descriptions",
- "derivationEvents.derivates",
- "annotations",
- "markers",
- "credits",
- "extensions",
- "rights",
- "sources"
- });
- Map<Object, List<String>> specimenPropertyPathMap =
- new HashMap<Object, List<String>>();
- specimenPropertyPathMap.put(SpecimenOrObservationBase.class,specimenPropertyPaths);
- return specimenPropertyPathMap;
- }
-
-
}
--- /dev/null
+package eu.etaxonomy.taxeditor.editor.view.derivate.contextMenu;
+
+import org.eclipse.jface.action.ContributionItem;
+import org.eclipse.jface.action.IContributionItem;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.actions.CompoundContributionItem;
+
+import eu.etaxonomy.cdm.api.service.IOccurrenceService;
+import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
+import eu.etaxonomy.cdm.model.common.CdmBase;
+import eu.etaxonomy.cdm.model.description.IndividualsAssociation;
+import eu.etaxonomy.cdm.model.description.TaxonDescription;
+import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
+import eu.etaxonomy.cdm.model.taxon.Taxon;
+import eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView;
+import eu.etaxonomy.taxeditor.model.MessagingUtils;
+import eu.etaxonomy.taxeditor.store.CdmStore;
+
+/**
+ * Context menu for the SingleReads in the derivate hierarchy.
+ *
+ */
+public class CreateFieldUnitContextMenu extends CompoundContributionItem {
+
+ private enum CommandType {
+ COPY_TO_CLIPBOARD, REMOVE_FROM_SEQUENCE, ADD_TO_SEQUENCE
+ }
+
+ @Override
+ protected IContributionItem[] getContributionItems() {
+ IContributionItem[] contributionItems = new IContributionItem[] {
+ new ContributionItem() {
+ @Override
+ public void fill(Menu menu, int index) {
+ final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ IWorkbenchPart activePart = window.getActivePage().getActivePart();
+ if(activePart instanceof DerivateView){
+ final DerivateView derivateView = (DerivateView) activePart;
+ if(derivateView.isListenToSelectionChange()){
+ Object selectionInput = derivateView.getSelectionInput();
+ if(selectionInput instanceof CdmBase && ((CdmBase) selectionInput).isInstanceOf(Taxon.class)){
+ final Taxon taxon = HibernateProxyHelper.deproxy(selectionInput, Taxon.class);
+ MenuItem item = new MenuItem(menu, SWT.NONE);
+ item.setText("Create FieldUnit for "+taxon.getName());
+ item.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ if(derivateView.isDirty()){
+ MessagingUtils.warningDialog(DerivateView.VIEW_HAS_UNSAVED_CHANGES, this, DerivateView.YOU_NEED_TO_SAVE_BEFORE_PERFORMING_THIS_ACTION);
+ return;
+ }
+ FieldUnit fieldUnit = FieldUnit.NewInstance();
+ fieldUnit = CdmBase.deproxy(CdmStore.getService(IOccurrenceService.class).save(fieldUnit), FieldUnit.class);
+ IndividualsAssociation association = IndividualsAssociation.NewInstance(fieldUnit);
+ TaxonDescription description;
+ if(!taxon.getDescriptions().isEmpty()){
+ description = taxon.getDescriptions().iterator().next();
+ }
+ else{
+ description = TaxonDescription.NewInstance(taxon);
+ }
+ description.addElement(association);
+
+ derivateView.getConversationHolder().commit();
+ derivateView.addFieldUnit(fieldUnit);
+ derivateView.refreshTree();
+ }
+ });
+ }
+ }
+ else{
+ MenuItem item = new MenuItem(menu, SWT.NONE);
+ item.setText("Create FieldUnit");
+ item.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ if(derivateView.isDirty()){
+ MessagingUtils.warningDialog(DerivateView.VIEW_HAS_UNSAVED_CHANGES, this, DerivateView.YOU_NEED_TO_SAVE_BEFORE_PERFORMING_THIS_ACTION);
+ return;
+ }
+ FieldUnit fieldUnit = FieldUnit.NewInstance();
+ fieldUnit = CdmBase.deproxy(CdmStore.getService(IOccurrenceService.class).save(fieldUnit), FieldUnit.class);
+ derivateView.getConversationHolder().commit();
+ derivateView.addFieldUnit(fieldUnit);
+ derivateView.refreshTree();
+ }
+ });
+ }
+ }
+ }
+ }
+ };
+ return contributionItems;
+ }
+}
+
@Override
protected IContributionItem[] getContributionItems() {
IContributionItem[] contributionItems = new IContributionItem[] {
+ new CreateFieldUnitContextMenu(),
new CreateDerivateContextMenu(),
- new SingleReadSequenceContextMenu()
+ new ListenToSelectionChangeContextMenu(),
+ new SingleReadSequenceContextMenu(),
};
return contributionItems;
}
--- /dev/null
+package eu.etaxonomy.taxeditor.editor.view.derivate.contextMenu;
+
+import org.eclipse.jface.action.ContributionItem;
+import org.eclipse.jface.action.IContributionItem;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.actions.CompoundContributionItem;
+
+import eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView;
+
+/**
+ * Context menu for the SingleReads in the derivate hierarchy.
+ *
+ */
+public class ListenToSelectionChangeContextMenu extends CompoundContributionItem {
+
+ @Override
+ protected IContributionItem[] getContributionItems() {
+ IContributionItem[] contributionItems = new IContributionItem[] {
+ new ContributionItem() {
+ @Override
+ public void fill(Menu menu, int index) {
+ final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ IWorkbenchPart activePart = window.getActivePage().getActivePart();
+ if(activePart instanceof DerivateView){
+ final DerivateView derivateView = (DerivateView) activePart;
+ MenuItem item = new MenuItem(menu, SWT.NONE);
+ if(derivateView.isListenToSelectionChange()){
+ item.setText("Unlink from taxon selection");
+ }
+ else{
+ item.setText("Link with taxon selection");
+ }
+ item.addSelectionListener(new SelectionAdapterExtension(derivateView));
+ }
+ }
+ }
+ };
+ return contributionItems;
+ }
+
+ private final class SelectionAdapterExtension extends SelectionAdapter {
+
+ private final DerivateView derivateView;
+
+ private SelectionAdapterExtension(DerivateView derivateView) {
+ this.derivateView = derivateView;
+ }
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ derivateView.toggleListenToSelectionChange();
+ }
+ }
+}
+
+++ /dev/null
-package eu.etaxonomy.taxeditor.editor.view.derivate.handler;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-
-import eu.etaxonomy.cdm.api.service.IOccurrenceService;
-import eu.etaxonomy.cdm.model.common.CdmBase;
-import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
-import eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView;
-import eu.etaxonomy.taxeditor.editor.view.derivate.DerivateViewEditorInput;
-import eu.etaxonomy.taxeditor.model.AbstractUtility;
-import eu.etaxonomy.taxeditor.model.MessagingUtils;
-import eu.etaxonomy.taxeditor.store.CdmStore;
-
-public class CreateFieldUnitHandler extends AbstractHandler {
-
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- if(AbstractUtility.getActivePart() instanceof DerivateView){
- DerivateView derivateView = (DerivateView)AbstractUtility.getActivePart();
- if(derivateView.isDirty()){
- MessagingUtils.warningDialog(DerivateView.VIEW_HAS_UNSAVED_CHANGES, this, DerivateView.YOU_NEED_TO_SAVE_BEFORE_PERFORMING_THIS_ACTION);
- return null;
- }
- FieldUnit fieldUnit = FieldUnit.NewInstance();
- fieldUnit = CdmBase.deproxy(CdmStore.getService(IOccurrenceService.class).save(fieldUnit), FieldUnit.class);
- derivateView.getConversationHolder().commit();
- DerivateViewEditorInput input = (DerivateViewEditorInput) derivateView.getEditorInput();
- input.addRootEntity(fieldUnit);
- derivateView.refreshTree();
- }
- return null;
- }
-
-}
--- /dev/null
+package eu.etaxonomy.taxeditor.editor.view.derivate.handler;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipse.ui.handlers.HandlerUtil;
+
+import eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView;
+
+public class ListenToSelectionChangeHandler extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ IWorkbenchPart activePart = HandlerUtil.getActivePart(event);
+ if(activePart instanceof DerivateView){
+ DerivateView derivativeEditor = (DerivateView)activePart;
+ derivativeEditor.toggleListenToSelectionChange();
+ }
+ return null;
+ }
+
+}
+++ /dev/null
-// $Id$
-/**
-* Copyright (C) 2014 EDIT
-* European Distributed Institute of Taxonomy
-* http://www.e-taxonomy.eu
-*
-* 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.editor.view.derivate.handler;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.UUID;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-import eu.etaxonomy.cdm.api.service.IOccurrenceService;
-import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
-import eu.etaxonomy.cdm.model.taxon.Taxon;
-import eu.etaxonomy.cdm.model.taxon.TaxonNode;
-import eu.etaxonomy.taxeditor.editor.EditorUtil;
-import eu.etaxonomy.taxeditor.editor.Messages;
-import eu.etaxonomy.taxeditor.editor.handler.OpenDerivateViewHandler;
-import eu.etaxonomy.taxeditor.editor.view.derivate.DerivateViewEditorInput;
-import eu.etaxonomy.taxeditor.model.MessagingUtils;
-import eu.etaxonomy.taxeditor.store.CdmStore;
-
-/**
- * @author pplitzner
- * @date Nov 25, 2014
- *
- */
-public class OpenDerivateEditorForTaxonHandler extends AbstractHandler {
-
- private static final String COULD_NOT_OPEN_DERIVATIVE_EDITOR = Messages.OpenDerivateEditorForTaxonHandler_COULD_NOT_OPEN_EDITOR;
-
- /* (non-Javadoc)
- * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
- */
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ISelection currentSelection = HandlerUtil.getCurrentSelection(event);
- if(currentSelection instanceof IStructuredSelection){
- Iterator<?> selectionIterator = ((IStructuredSelection) currentSelection).iterator();
- Set<UUID> derivateUuids = new HashSet<UUID>();
- while(selectionIterator.hasNext()){
- Object object = selectionIterator.next();
- if(object instanceof TaxonNode){
- TaxonNode node = (TaxonNode)object;
- Taxon taxon = node.getTaxon();
- List<SpecimenOrObservationBase> listByAssociatedTaxon = CdmStore.getService(IOccurrenceService.class).listByAssociatedTaxon(null, null, taxon, null, null, null, null, null);
- for (SpecimenOrObservationBase specimenOrObservationBase : listByAssociatedTaxon) {
- derivateUuids.add(specimenOrObservationBase.getUuid());
- }
- }
- }
- if(derivateUuids.isEmpty()){
- MessagingUtils.warningDialog(COULD_NOT_OPEN_DERIVATIVE_EDITOR, this, Messages.OpenDerivateEditorForTaxonHandler_NO_DERIVATIVES_FOUND);
- return null;
- }
- DerivateViewEditorInput input = new DerivateViewEditorInput(derivateUuids);
- try {
- EditorUtil.open(input);
- } catch (PartInitException e) {
- MessagingUtils.error(OpenDerivateViewHandler.class, COULD_NOT_OPEN_DERIVATIVE_EDITOR, e);
- } catch (NullPointerException npe){
- MessagingUtils.messageDialog(Messages.OpenDerivateEditorForTaxonHandler_FAILED_TO_OPEN, OpenDerivateViewHandler.class, Messages.OpenDerivateEditorForTaxonHandler_HIERARCHY_CORRUPTED, npe);
- }
- }
- return null;
- }
-
-}
import eu.etaxonomy.cdm.model.molecular.SingleRead;
import eu.etaxonomy.taxeditor.editor.Messages;
import eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView;
-import eu.etaxonomy.taxeditor.model.AbstractUtility;
import eu.etaxonomy.taxeditor.model.MessagingUtils;
import eu.etaxonomy.taxeditor.operation.AbstractPostOperation;
import eu.etaxonomy.taxeditor.operation.IPostOperationEnabled;
//update DerivateView
derivateView.getConversationHolder().commit();
IStatus returnStatus = postExecute(null);
- //close if no more items left
- if(derivateView.getViewer().getTree().getItemCount()<1){
- AbstractUtility.close(derivateView);
- }
return returnStatus;
}
}
* 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.view.derivateSearch;
+package eu.etaxonomy.taxeditor.editor.view.derivate.searchFilter;
-import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.wb.swt.ResourceManager;
*
*/
public class DerivateSearchComposite extends Composite {
+
+ public static final int ALL_SPECIMENS = 0;
+ public static final int ASSIGNED_SPECIMENS = 1;
+ public static final int UNASSIGNED_SPECIMENS = 2;
+
private final FormToolkit formToolkit = new FormToolkit(Display.getDefault());
private final Text searchField;
- private final Table table;
- private final TableViewer resultViewer;
private final Combo comboDerivateType;
private final Button buttonSearch;
- private final Button btnFilterUndeterminedSpecimen;
private final Text textTaxonName;
private final Button btnBrowseTaxa;
private final Label lblTaxon;
private final Label lblDerivateType;
private final Button btnClearTaxon;
+ private Label lbltaxonAssignment;
+ private Combo comboTaxonAssignment;
+ private Label lblTitleCache;
/**
* Create the composite.
+ *
* @param parent
* @param style
*/
public DerivateSearchComposite(Composite parent, int style) {
super(parent, style);
- setLayout(new GridLayout(4, false));
+ setLayout(new GridLayout(7, false));
lblTaxon = new Label(this, SWT.NONE);
lblTaxon.setText("Taxon");
- textTaxonName = formToolkit.createText(this, "New Text", SWT.NONE);
+ textTaxonName = formToolkit.createText(this, "New Text", SWT.BORDER);
textTaxonName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
textTaxonName.setEnabled(false);
textTaxonName.setText("");
btnBrowseTaxa = formToolkit.createButton(this, "", SWT.NONE);
+ btnBrowseTaxa.setAlignment(SWT.RIGHT);
btnBrowseTaxa.setImage(ResourceManager.getPluginImage("eu.etaxonomy.taxeditor.store", "icons/open.gif"));
btnClearTaxon = formToolkit.createButton(this, "", SWT.NONE);
- btnClearTaxon.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
+ btnClearTaxon.setAlignment(SWT.RIGHT);
+ btnClearTaxon.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false, 1, 1));
btnClearTaxon.setImage(ResourceManager.getPluginImage("eu.etaxonomy.taxeditor.store", "icons/trash.gif"));
+ lbltaxonAssignment = new Label(this, SWT.NONE);
+ lbltaxonAssignment.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
+ lbltaxonAssignment.setText("Taxon assignment");
+
+ comboTaxonAssignment = new Combo(this, SWT.NONE);
+ comboTaxonAssignment.setItems(new String[] { "All", "Yes", "No" });
+ comboTaxonAssignment.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
+ formToolkit.adapt(comboTaxonAssignment);
+ formToolkit.paintBordersFor(comboTaxonAssignment);
+ comboTaxonAssignment.select(ALL_SPECIMENS);
+ new Label(this, SWT.NONE);
+
+ lblTitleCache = new Label(this, SWT.NONE);
+ lblTitleCache.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
+ lblTitleCache.setText("Title Cache");
+
+ searchField = formToolkit.createText(this, "New Text", SWT.BORDER);
+ searchField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1));
+ searchField.setText("");
+
lblDerivateType = new Label(this, SWT.NULL);
+ lblDerivateType.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblDerivateType.setText("Derivative Type");
comboDerivateType = new Combo(this, SWT.READ_ONLY);
comboDerivateType.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
formToolkit.paintBordersFor(comboDerivateType);
- btnFilterUndeterminedSpecimen = new Button(this, SWT.CHECK);
- btnFilterUndeterminedSpecimen.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- btnFilterUndeterminedSpecimen.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- }
- });
- btnFilterUndeterminedSpecimen.setText("Determined");
-
- buttonSearch = new Button(this, SWT.NONE);
- formToolkit.adapt(buttonSearch, true, true);
- buttonSearch.setText("Search");
-
- searchField = formToolkit.createText(this, "New Text", SWT.NONE);
- searchField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
- searchField.setText("");
- new Label(this, SWT.NONE);
- new Label(this, SWT.NONE);
-
- resultViewer = new TableViewer(this, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI);
- table = resultViewer.getTable();
- table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1));
+ buttonSearch = new Button(this, SWT.NONE);
+ formToolkit.adapt(buttonSearch, true, true);
+ buttonSearch.setText("Search");
}
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}
+
public Text getSearchField() {
return searchField;
}
- public TableViewer getResultViewer() {
- return resultViewer;
- }
+
public Combo getComboDerivateType() {
return comboDerivateType;
}
+
public Button getButtonSearch() {
return buttonSearch;
}
@Override
- public void setEnabled(boolean enabled){
+ public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
searchField.setEnabled(enabled);
- table.setEnabled(enabled);
- // resultViewer.setEnabled(enabled);
comboDerivateType.setEnabled(enabled);
+ comboTaxonAssignment.setEnabled(enabled);
buttonSearch.setEnabled(enabled);
- btnFilterUndeterminedSpecimen.setEnabled(enabled);
btnBrowseTaxa.setEnabled(enabled);
+ btnClearTaxon.setEnabled(enabled);
lblTaxon.setEnabled(enabled);
+ lblTitleCache.setEnabled(enabled);
+ lbltaxonAssignment.setEnabled(enabled);
lblDerivateType.setEnabled(enabled);
}
- public Button getBtnFilterUndeterminedSpecimen() {
- return btnFilterUndeterminedSpecimen;
- }
+
+
public Button getBtnBrowseTaxa() {
return btnBrowseTaxa;
}
+
public Text getTextTaxonName() {
return textTaxonName;
}
+
public Button getBtnClearTaxon() {
return btnClearTaxon;
}
+ public Combo getComboTaxonAssignment() {
+ return comboTaxonAssignment;
+ }
+
+ public Label getLbltaxonAssignment() {
+ return lbltaxonAssignment;
+ }
}
* 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.view.derivateSearch;
+package eu.etaxonomy.taxeditor.editor.view.derivate.searchFilter;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.List;
+import java.util.UUID;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.commands.NotEnabledException;
-import org.eclipse.core.commands.NotHandledException;
-import org.eclipse.core.commands.common.NotDefinedException;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Widget;
-import org.eclipse.ui.handlers.IHandlerService;
import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
import eu.etaxonomy.cdm.api.service.IOccurrenceService;
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationType;
import eu.etaxonomy.cdm.model.taxon.Taxon;
-import eu.etaxonomy.taxeditor.model.AbstractUtility;
-import eu.etaxonomy.taxeditor.model.MessagingUtils;
+import eu.etaxonomy.cdm.model.taxon.TaxonBase;
+import eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView;
import eu.etaxonomy.taxeditor.store.CdmStore;
import eu.etaxonomy.taxeditor.store.SearchManager;
import eu.etaxonomy.taxeditor.ui.dialog.selection.SelectionDialogFactory;
import eu.etaxonomy.taxeditor.ui.mvc.combo.EnumTermComboController;
+import eu.etaxonomy.taxeditor.view.derivateSearch.DerivateLabelProvider;
/**
* Controller class for the {@link DerivateSearchComposite}.<br>
private final DerivateSearchComposite derivateSearchComposite;
private EnumTermComboController<SpecimenOrObservationType> comboSpecimenTypeController;
- private final DerivateSearchView derivateSearchView;
private DerivateLabelProvider labelProvider;
private Taxon selectedTaxon;
+ private DerivateView derivativeEditor;
- /**
- * @param parent
- * @param derivateSearchView
- */
- public DerivateSearchCompositeController(Composite parent, DerivateSearchView derivateSearchView) {
+ public DerivateSearchCompositeController(Composite parent, DerivateView derivativeEditor) {
this.derivateSearchComposite = new DerivateSearchComposite(parent, SWT.NONE);
- this.derivateSearchView = derivateSearchView;
+ this.derivativeEditor = derivativeEditor;
init();
}
derivateSearchComposite.getBtnBrowseTaxa().addListener(SWT.Selection, this);
derivateSearchComposite.getBtnClearTaxon().addListener(SWT.Selection, this);
-
- //result table
- TableViewer resultViewer = derivateSearchComposite.getResultViewer();
- resultViewer.setContentProvider(new ArrayContentProvider());
- labelProvider = new DerivateLabelProvider();
- resultViewer.setLabelProvider(labelProvider);
- resultViewer.addDoubleClickListener(new IDoubleClickListener() {
- @Override
- public void doubleClick(DoubleClickEvent event) {
- String commandId = "eu.etaxonomy.taxeditor.editor.handler.openDerivateView";
-
- IHandlerService handlerService = (IHandlerService) AbstractUtility.getService(IHandlerService.class);
- try {
- handlerService.executeCommand(commandId, null);
- } catch (ExecutionException e) {
- MessagingUtils.error(DerivateSearchCompositeController.class, e);
- } catch (NotDefinedException e) {
- MessagingUtils.error(DerivateSearchCompositeController.class, e);
- } catch (NotEnabledException e) {
- MessagingUtils.error(DerivateSearchCompositeController.class, e);
- } catch (NotHandledException e) {
- MessagingUtils.error(DerivateSearchCompositeController.class, e);
- }
-
- }
- });
-
}
private void searchDerivates(){
- if(!derivateSearchView.getConversationHolder().isBound()){
- derivateSearchView.setFocus(); //rebind the conversation
- }
-
String queryString = derivateSearchComposite.getSearchField().getText();
SpecimenOrObservationType specimenType = comboSpecimenTypeController.getSelection();
config.setSpecimenType(specimenType.equals(SpecimenOrObservationType.Unknown)?null:specimenType);//unknown := all types
config.setTitleSearchString(queryString);
if(selectedTaxon!=null){
- config.setRetrieveIndirectlyAssociatedSpecimens(true);
config.setSpecimenType(null);
}
occurrences = specimensOfCorrectType;
}
- //filter out assigned specimens
- if(derivateSearchComposite.getBtnFilterUndeterminedSpecimen().getSelection()){
- List<SpecimenOrObservationBase> specimensWithNoDetermination = new ArrayList<SpecimenOrObservationBase>();
- for(SpecimenOrObservationBase<?> result:occurrences){
- if(CdmStore.getService(IOccurrenceService.class).countDeterminations(result, null)==0){
- specimensWithNoDetermination.add(result);
+ //filter out (un-)assigned specimens
+ if(selectedTaxon==null){
+ int selectionIndex = derivateSearchComposite.getComboTaxonAssignment().getSelectionIndex();
+ List<SpecimenOrObservationBase<?>> specimenWithAssociations = new ArrayList<SpecimenOrObservationBase<?>>();
+ if(selectionIndex!=DerivateSearchComposite.ALL_SPECIMENS){
+ for (SpecimenOrObservationBase specimenOrObservationBase : occurrences) {
+ Collection<TaxonBase<?>> associatedTaxa = CdmStore.getService(IOccurrenceService.class).listAssociatedTaxa(specimenOrObservationBase, null, null, null, null);
+ if(!associatedTaxa.isEmpty()){
+ specimenWithAssociations.add(specimenOrObservationBase);
+ specimenWithAssociations.addAll(CdmStore.getService(IOccurrenceService.class).getFieldUnits(specimenOrObservationBase.getUuid()));
+ }
}
}
- occurrences = specimensWithNoDetermination;
+ if(selectionIndex==DerivateSearchComposite.UNASSIGNED_SPECIMENS){
+ occurrences.removeAll(specimenWithAssociations);
+ }
+ else if(selectionIndex==DerivateSearchComposite.ASSIGNED_SPECIMENS){
+ occurrences = new ArrayList<SpecimenOrObservationBase>(specimenWithAssociations);
+ }
+ }
+ List<UUID> derivateUuids = new ArrayList<UUID>();
+ for (SpecimenOrObservationBase specimenOrObservationBase : occurrences) {
+ derivateUuids.add(specimenOrObservationBase.getUuid());
}
- derivateSearchComposite.getResultViewer().setInput(occurrences);
+ derivativeEditor.updateRootEntities(derivateUuids);
}
@Override
searchDerivates();
}
else if(eventSource==derivateSearchComposite.getBtnBrowseTaxa()){
- selectedTaxon = SelectionDialogFactory.getSelectionFromDialog(Taxon.class, derivateSearchView.getSite().getShell(), derivateSearchView.getConversationHolder(), null);
+ selectedTaxon = SelectionDialogFactory.getSelectionFromDialog(Taxon.class, this.derivateSearchComposite.getShell(), derivativeEditor.getConversationHolder(), null);
if(selectedTaxon!=null){
derivateSearchComposite.getTextTaxonName().setText(selectedTaxon.getTitleCache());
}
+ derivateSearchComposite.getComboTaxonAssignment().select(DerivateSearchComposite.ASSIGNED_SPECIMENS);
+ derivateSearchComposite.getComboTaxonAssignment().setEnabled(false);
+ derivateSearchComposite.getLbltaxonAssignment().setEnabled(false);
}
else if(eventSource==derivateSearchComposite.getBtnClearTaxon()){
selectedTaxon = null;
derivateSearchComposite.getTextTaxonName().setText("");
+ derivateSearchComposite.getComboTaxonAssignment().select(DerivateSearchComposite.ALL_SPECIMENS);
+ derivateSearchComposite.getComboTaxonAssignment().setEnabled(true);
+ derivateSearchComposite.getLbltaxonAssignment().setEnabled(true);
}
}
*/
public void setEnabled(boolean enabled) {
if(!derivateSearchComposite.isDisposed()){
- derivateSearchComposite.setEnabled(enabled);
+ GridData layoutData = (GridData) derivateSearchComposite.getLayoutData();
+ layoutData.exclude = !enabled;
+ derivateSearchComposite.setVisible(enabled);
+ derivateSearchComposite.getParent().layout(true);
}
}
+ public void setLayoutData(Object layoutData){
+ derivateSearchComposite.setLayoutData(layoutData);
+ }
+
/**
* Resets all input fields
*/
public void reset(){
if(!derivateSearchComposite.isDisposed()){
- derivateSearchComposite.getResultViewer().setInput(null);
derivateSearchComposite.getSearchField().setText("");
derivateSearchComposite.getComboDerivateType().deselectAll();
comboSpecimenTypeController.setSelection(SpecimenOrObservationType.Unknown);
selectedTaxon = null;
}
- public TableViewer getResultViewer() {
- return derivateSearchComposite.getResultViewer();
- }
-
- public void setFocus() {
- derivateSearchComposite.getResultViewer().getControl().setFocus();
- }
-
- /**
- * @param conversationHolder
- */
public void setConversation(ConversationHolder conversationHolder) {
labelProvider.setConversation(conversationHolder);
}
import org.eclipse.swt.dnd.DragSourceAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
+import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
import eu.etaxonomy.cdm.model.description.DescriptionBase;
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
import eu.etaxonomy.taxeditor.model.FeatureNodeContainer;
public class DescriptionElementDragListener extends DragSourceAdapter {
private DescriptiveViewPart part;
+ private DescriptionBase description;
public DescriptionElementDragListener(DescriptiveViewPart part){
this.part = part;
return;
// FIXME what to do here?
if (event.detail != DND.DROP_NONE) {
- IStructuredSelection selection = (IStructuredSelection) part.getViewer()
- .getSelection();
- part.changed(null);
+ //IStructuredSelection selection = (IStructuredSelection) part.getViewer().getSelection();
+ part.getViewer().refresh();
+
+ part.changed(null);
}
}
List<DescriptionElementBase> descriptionElements = new ArrayList<DescriptionElementBase>();
for (Object object : selection.toList()){
if(object instanceof DescriptionBase){
- descriptionElements.addAll(((DescriptionBase) object).getElements());
+ if (!((DescriptionBase) object).getElements().isEmpty()){
+ descriptionElements.addAll(((DescriptionBase) object).getElements());
+ }
+ description = HibernateProxyHelper.deproxy(object, DescriptionBase.class);
+
}else if(object instanceof FeatureNodeContainer){
descriptionElements.addAll(((FeatureNodeContainer) object).getDescriptionElements());
}else if(object instanceof DescriptionElementBase){
}
if (DescriptionElementTransfer.getInstance().isSupportedType(
event.dataType)) {
- event.data = descriptionElements.toArray(new DescriptionElementBase[descriptionElements.size()]);
+ if (!descriptionElements.isEmpty()){
+ event.data = descriptionElements.toArray(new DescriptionElementBase[descriptionElements.size()]);
+ }
+
}
+
}
/**
boolean isCopy = getCurrentOperation() == DND.DROP_COPY ? true : false;
// cannot drop a feature node onto itself
- for (Object droppedElement : droppedElements) {
- if (droppedElement == null){
- MessagingUtils.warningDialog("Operation not supported yet", this, "We are currently unable to drag and drop a newly created element. Please save the editor to make this work.");
- return false;
- }
- if(! (droppedElement instanceof DescriptionElementBase)){
- return false;
- }else{
- DescriptionElementBase descriptionElement = (DescriptionElementBase) droppedElement;
-
- if (descriptionElement.getInDescription().equals(target)) {
+ if (droppedElements != null){
+ for (Object droppedElement : droppedElements) {
+ if (droppedElement == null){
+ MessagingUtils.warningDialog("Operation not supported yet", this, "We are currently unable to drag and drop a newly created element. Please save the editor to make this work.");
return false;
}
-
- descriptionElements.add(descriptionElement);
- }
+ if(! (droppedElement instanceof DescriptionElementBase)){
+ return false;
+ }else{
+ DescriptionElementBase descriptionElement = (DescriptionElementBase) droppedElement;
+
+ if (descriptionElement.getInDescription().equals(target)) {
+ return false;
+ }
+
+ descriptionElements.add(descriptionElement);
+ }
+ }
+
+ AbstractPostOperation operation = new MoveDescriptionElementsOperation("Move Descriptions", EditorUtil.getUndoContext(), target, descriptionElements, isCopy, null);
+
+ EditorUtil.executeOperation(operation);
+ return true;
}
+ MessagingUtils.warningDialog("Operation not supported yet", this, "We are unable to drag and drop empty descriptions");
+
+ return false;
- AbstractPostOperation operation = new MoveDescriptionElementsOperation("Move Descriptions", EditorUtil.getUndoContext(), target, descriptionElements, isCopy, null);
-
- EditorUtil.executeOperation(operation);
-
- return true;
}
/* (non-Javadoc)
package eu.etaxonomy.taxeditor.editor.view.descriptive;
import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeNode;
-import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.PartInitException;
import eu.etaxonomy.cdm.model.common.CdmBase;
import eu.etaxonomy.cdm.model.description.DescriptionBase;
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
import eu.etaxonomy.cdm.model.description.IDescribable;
-import eu.etaxonomy.cdm.model.description.IndividualsAssociation;
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
import eu.etaxonomy.cdm.model.taxon.Taxon;
import eu.etaxonomy.taxeditor.bulkeditor.BulkEditor;
import eu.etaxonomy.taxeditor.editor.EditorUtil;
import eu.etaxonomy.taxeditor.editor.view.checklist.ChecklistEditor;
import eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView;
-import eu.etaxonomy.taxeditor.editor.view.derivate.DerivateViewEditorInput;
import eu.etaxonomy.taxeditor.editor.view.media.MediaViewPart;
import eu.etaxonomy.taxeditor.model.AbstractUtility;
import eu.etaxonomy.taxeditor.model.FeatureNodeContainer;
import eu.etaxonomy.taxeditor.model.IPartContentHasFactualData;
import eu.etaxonomy.taxeditor.model.IPartContentHasSupplementalData;
import eu.etaxonomy.taxeditor.model.ImageResources;
-import eu.etaxonomy.taxeditor.model.MessagingUtils;
import eu.etaxonomy.taxeditor.store.CdmStore;
import eu.etaxonomy.taxeditor.view.AbstractCdmEditorViewPart;
import eu.etaxonomy.taxeditor.view.detail.DetailsViewPart;
import eu.etaxonomy.taxeditor.view.supplementaldata.SupplementalDataViewPart;
/**
- * <p>DescriptiveViewPart class.</p>
- *
* @author n.hoffmann
* @created Jun 9, 2010
* @version 1.0
createToolbar();
- // set initial input
-// if(getEditor() != null){
-// viewer.setInput(getEditor().getEditorInput());
-// }
-
- viewer.addDoubleClickListener(new IDoubleClickListener() {
- @Override
- public void doubleClick(DoubleClickEvent event) {
- //Open derivate editor when specimen description element is double clicked
- TreeSelection selection = (TreeSelection) viewer.getSelection();
- Iterator iterator = selection.iterator();
- Set<UUID> specimenUuids = new HashSet<UUID>();
- while(iterator.hasNext()){
- Object next = iterator.next();
- if(next instanceof IndividualsAssociation){
- SpecimenOrObservationBase<?> specimen = ((IndividualsAssociation)next).getAssociatedSpecimenOrObservation();
- if(specimen!=null){
- specimenUuids.add(specimen.getUuid());
- }
- }
- }
- try {
- if(!specimenUuids.isEmpty()){
- EditorUtil.open(new DerivateViewEditorInput(specimenUuids));
- }
- } catch (PartInitException e) {
- MessagingUtils.error(DescriptiveViewPart.class, "Could not open Derivative Editor", e);
- }
-
-
- //TODO: extend command to accept parameter to open editor
-// String commandId = "eu.etaxonomy.taxeditor.editor.handler.openDerivateView";
-// IHandlerService handlerService = (IHandlerService) AbstractUtility.getService(IHandlerService.class);
-// try {
-// handlerService.executeCommand(commandId, null);
-// } catch (ExecutionException e) {
-// MessagingUtils.error(DerivateSearchCompositeController.class, e);
-// } catch (NotDefinedException e) {
-// MessagingUtils.error(DerivateSearchCompositeController.class, e);
-// } catch (NotEnabledException e) {
-// MessagingUtils.error(DerivateSearchCompositeController.class, e);
-// } catch (NotHandledException e) {
-// MessagingUtils.error(DerivateSearchCompositeController.class, e);
-// }
-
- }
- });
}
- /* (non-Javadoc)
- * @see eu.etaxonomy.taxeditor.model.AbstractCdmViewPart#getInitialSelection()
- */
/** {@inheritDoc} */
@Override
protected ISelection getInitialSelection() {
return viewer;
}
- /**
- * <p>onComplete</p>
- *
- * @return a boolean.
- */
@Override
public boolean onComplete() {
return false;
for(DescriptionElementBase deBase : descriptionElements) {
descriptionElementsUuid.add(deBase.getUuid());
}
-
+ UpdateResult result;
if(targetDescription == null){
- UpdateResult result = service.moveDescriptionElementsToDescription(descriptionElementsUuid, targetTaxonUuid, moveMessage, isCopy);
+ result = service.moveDescriptionElementsToDescription(descriptionElementsUuid, targetTaxonUuid, moveMessage, isCopy);
} else {
UUID targetDescriptionUuid = targetDescription.getUuid();
- service.moveDescriptionElementsToDescription(descriptionElementsUuid, targetDescriptionUuid, isCopy);
+ result = service.moveDescriptionElementsToDescription(descriptionElementsUuid, targetDescriptionUuid, isCopy);
+
}
return postExecute(targetDescription);
}
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.common.NotDefinedException;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TreeNode;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
+import eu.etaxonomy.cdm.model.common.CdmBase;
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
import eu.etaxonomy.cdm.model.taxon.Taxon;
-import eu.etaxonomy.cdm.model.taxon.TaxonBase;
-import eu.etaxonomy.taxeditor.bulkeditor.BulkEditor;
import eu.etaxonomy.taxeditor.bulkeditor.BulkEditorUtil;
-import eu.etaxonomy.taxeditor.bulkeditor.input.OccurrenceEditorInput;
import eu.etaxonomy.taxeditor.editor.EditorUtil;
-import eu.etaxonomy.taxeditor.editor.TaxonEditorInput;
-import eu.etaxonomy.taxeditor.editor.view.derivate.DerivateView;
-import eu.etaxonomy.taxeditor.editor.view.derivate.DerivateViewEditorInput;
-import eu.etaxonomy.taxeditor.editor.view.descriptive.DescriptiveViewPart;
import eu.etaxonomy.taxeditor.editor.view.descriptive.operation.AddDerivedUnitFacadeMediaOperation;
-import eu.etaxonomy.taxeditor.editor.view.descriptive.operation.CreateSpecimenDescriptionOperation;
import eu.etaxonomy.taxeditor.editor.view.descriptive.operation.CreateTaxonDescriptionOperation;
import eu.etaxonomy.taxeditor.editor.view.media.MediaViewPart;
import eu.etaxonomy.taxeditor.model.AbstractUtility;
import eu.etaxonomy.taxeditor.operation.IPostOperationEnabled;
/**
- * <p>AddImageGalleryHandler class.</p>
- *
* @author p.ciardelli
* @version $Id: $
*/
public class AddImageGalleryHandler extends AbstractHandler {
- /* (non-Javadoc)
- * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
- */
/** {@inheritDoc} */
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
- IWorkbenchPart part = HandlerUtil.getActivePart(event);
- IPostOperationEnabled postOperationEnabled = (part instanceof IPostOperationEnabled) ? (IPostOperationEnabled) part : null;
+ IWorkbenchPart part = HandlerUtil.getActivePart(event);
+ IPostOperationEnabled postOperationEnabled = (part instanceof IPostOperationEnabled) ? (IPostOperationEnabled) part : null;
+ if(part instanceof MediaViewPart){
+ Object viewerInput = ((MediaViewPart)part).getViewer().getInput();
+ try {
+ if(viewerInput instanceof CdmBase){
+ if(((CdmBase) viewerInput).isInstanceOf(Taxon.class)){
+ Taxon taxon = HibernateProxyHelper.deproxy(viewerInput, Taxon.class);
- IEditorPart editor = HandlerUtil.getActiveEditor(event);
- IEditorInput input = editor.getEditorInput();
+ AbstractPostOperation<?> operation = new CreateTaxonDescriptionOperation(event.getCommand().getName(),
+ EditorUtil.getUndoContext(), taxon, postOperationEnabled, true);
- if (input instanceof TaxonEditorInput) {
- Taxon taxon = ((TaxonEditorInput) input).getTaxon();
- AbstractPostOperation<?> operation;
- try {
- // TODO use undo context specific to editor
- operation = new CreateTaxonDescriptionOperation(event.getCommand().getName(),
- EditorUtil.getUndoContext(), taxon, postOperationEnabled, true);
- AbstractUtility.executeOperation(operation);
- } catch (NotDefinedException e) {
- MessagingUtils.warn(getClass(), "Command name not set.");
- }
- }
- else if(input instanceof OccurrenceEditorInput){
- BulkEditor bulkEditor = (BulkEditor) editor;
- ISelection selection = bulkEditor.getSelectionProvider().getSelection();
- invokeOperation(event, postOperationEnabled, selection);
- }
- else if(input instanceof DerivateViewEditorInput){
- ISelection selection = ((DerivateView)editor).getSelection();
- invokeOperation(event, postOperationEnabled, selection);
- } else if(part instanceof MediaViewPart){
- Object viewerInput = ((MediaViewPart)part).getViewer().getInput();
-
- if(viewerInput instanceof Taxon){
- Taxon taxon = HibernateProxyHelper.deproxy(viewerInput, Taxon.class);
- AbstractPostOperation<?> operation;
- try {
- // TODO use undo context specific to editor
- operation = new CreateTaxonDescriptionOperation(event.getCommand().getName(),
- EditorUtil.getUndoContext(), taxon, postOperationEnabled, true);
- AbstractUtility.executeOperation(operation);
- } catch (NotDefinedException e) {
- MessagingUtils.warn(getClass(), "Command name not set.");
- }
-
- }
- }
-
- return null;
- }
+ AbstractUtility.executeOperation(operation);
+ }
+ else if(((CdmBase) viewerInput).isInstanceOf(SpecimenOrObservationBase.class)){
+ SpecimenOrObservationBase<?> specimen = HibernateProxyHelper.deproxy(viewerInput, SpecimenOrObservationBase.class);
- /**
- * @param event
- * @param postOperationEnabled
- * @param selection
- */
- private void invokeOperation(ExecutionEvent event, IPostOperationEnabled postOperationEnabled, ISelection selection) {
- if(selection instanceof IStructuredSelection){
- Object element = ((IStructuredSelection) selection).getFirstElement();
- if(element instanceof TreeNode){
- element = ((TreeNode) element).getValue();
- }
- if(element instanceof SpecimenOrObservationBase<?>){
- try {
- AbstractPostOperation<?> operation = new AddDerivedUnitFacadeMediaOperation(event.getCommand().getName(),
- BulkEditorUtil.getUndoContext(), (SpecimenOrObservationBase<?>)element, postOperationEnabled);
- AbstractUtility.executeOperation(operation);
- } catch (NotDefinedException e) {
- MessagingUtils.warn(getClass(), "Command name not set.");
- }
- }
- }
- }
+ AbstractPostOperation<?> operation = new AddDerivedUnitFacadeMediaOperation(event.getCommand().getName(),
+ BulkEditorUtil.getUndoContext(), specimen, postOperationEnabled);
+
+ AbstractUtility.executeOperation(operation);
+ }
+ }
+ } catch (NotDefinedException e) {
+ MessagingUtils.warn(getClass(), "Command name not set.");
+ }
+ }
+ return null;
+ }
-}
+}
\ No newline at end of file
-<?xml version="1.0" encoding="UTF-8"?>\r
-<classpath>\r
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
- <classpathentry kind="src" path="src"/>\r
- <classpathentry kind="output" path="target"/>\r
-</classpath>\r
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="target"/>
+</classpath>
org.eclipse.core.runtime,
org.eclipse.help.ui,
org.eclipse.help.webapp
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Bundle-ActivationPolicy: lazy
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry exported="true" kind="lib" path="lib/bioinfweb-commons-bio-2-SNAPSHOT.jar"/>
<classpathentry exported="true" kind="lib" path="lib/bioinfweb-commons-core-2-SNAPSHOT.jar"/>
Bundle-ActivationPolicy: lazy
Import-Package: javax.swing
Require-Bundle: org.eclipse.swt
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry including="**/*.java" kind="src" path="src/main/java"/>
<classpathentry kind="output" path="target/classes"/>
eu.etaxonomy.taxeditor.editor,
eu.etaxonomy.taxeditor.store,
eu.etaxonomy.taxeditor.molecular.lib
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Bundle-ActivationPolicy: lazy
Bundle-Vendor: EDIT
Export-Package: eu.etaxonomy.taxeditor.molecular,
-<?xml version="1.0" encoding="UTF-8"?>\r
-<classpath>\r
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
- <classpathentry including="**/*.java" kind="src" path="src/main/java"/>\r
- <classpathentry including="**/*.java" kind="src" path="src/test/java"/>\r
- <classpathentry including="**/*.java" kind="src" path="src/test/resources"/>\r
- <classpathentry kind="output" path="target/classes"/>\r
-</classpath>\r
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry including="**/*.java" kind="src" path="src/main/java"/>
+ <classpathentry including="**/*.java" kind="src" path="src/test/java"/>
+ <classpathentry including="**/*.java" kind="src" path="src/test/resources"/>
+ <classpathentry kind="output" path="target/classes"/>
+</classpath>
org.eclipse.ui.forms.widgets,
org.osgi.framework
Bundle-Activator: eu.etaxonomy.taxeditor.navigation.internal.TaxeditorNavigationPlugin
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Bundle-ClassPath: .,
activation-1.1.jar,
antlr-2.7.6.jar,
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry including="**/*.java" kind="src" path="src/main/java"/>
<classpathentry kind="output" path="target/classes"/>
Bundle-ActivationPolicy: lazy
Bundle-Vendor: EDIT
Bundle-Activator: eu.etaxonomy.taxeditor.printpublisher.internal.PrintpublisherPlugin
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Bundle-ClassPath: .,
activation-1.1.jar,
antlr-2.7.6.jar,
-<?xml version="1.0" encoding="UTF-8"?>\r
-<classpath>\r
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
- <classpathentry including="**/*.java" kind="src" path="src/main/java"/>\r
- <classpathentry including="**/*.java" kind="src" path="src/test/java"/>\r
- <classpathentry kind="src" path="src/main/resources"/>\r
- <classpathentry including="**/*.java" kind="src" path="src/test/resources"/>\r
- <classpathentry kind="output" path="target/classes"/>\r
-</classpath>\r
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry including="**/*.java" kind="src" path="src/main/java"/>
+ <classpathentry including="**/*.java" kind="src" path="src/test/java"/>
+ <classpathentry kind="src" path="src/main/resources"/>
+ <classpathentry including="**/*.java" kind="src" path="src/test/resources"/>
+ <classpathentry kind="output" path="target/classes"/>
+</classpath>
eu.etaxonomy.taxeditor.ui.dialog.selection,
eu.etaxonomy.taxeditor.ui.element,
eu.etaxonomy.taxeditor.ui.group.grantedauthority,
+ eu.etaxonomy.taxeditor.ui.mvc.combo,
eu.etaxonomy.taxeditor.ui.section,
eu.etaxonomy.taxeditor.ui.section.agent,
eu.etaxonomy.taxeditor.ui.section.classification,
eu.etaxonomy.taxeditor.view.derivateSearch,
eu.etaxonomy.taxeditor.view.detail,
eu.etaxonomy.taxeditor.view.specimenSearch,
- eu.etaxonomy.taxeditor.view.supplementaldata
+ eu.etaxonomy.taxeditor.view.supplementaldata,
+ org.eclipse.wb.swt
Require-Bundle: org.eclipse.osgi,
org.eclipse.ui,
org.eclipse.jface.text,
org.eclipse.core.databinding.observable,
org.eclipse.core.databinding.property,
org.eclipse.jface.databinding
-Import-Package: org.eclipse.core.commands,
+Import-Package: eu.etaxonomy.taxeditor.webapp,
+ org.eclipse.core.commands,
org.eclipse.core.commands.operations,
org.eclipse.core.expressions,
org.eclipse.core.runtime,
org.osgi.framework,
org.osgi.service.prefs;version="1.1.1"
Bundle-ActivationPolicy: lazy
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Bundle-ClassPath: .,
activation-1.1.1.jar,
antlr-2.7.7.jar,
name="%view.name.5"
restorable="true">
</view>
- <view
- class="eu.etaxonomy.taxeditor.view.derivateSearch.DerivateSearchView"
- icon="icons/derivate_search_view-16x16-32.png"
- id="eu.etaxonomy.taxeditor.view.derivateSearch.DerivateSearchView"
- name="%view.name.6"
- restorable="true">
- </view>
<view
allowMultiple="false"
class="eu.etaxonomy.taxeditor.view.sessions.SessionsViewPart"
label="%menu.label">
<command
commandId="org.eclipse.ui.views.showView"
- label="%command.label"
- style="push">
- <parameter
- name="org.eclipse.ui.views.showView.viewId"
- value="eu.etaxonomy.taxeditor.view.derivateSearch.DerivateSearchView">
- </parameter>
- <visibleWhen
- checkEnabled="true">
- <reference
- definitionId="isCdmStoreConnected">
- </reference>
- </visibleWhen>
- </command>
- <separator
- name="eu.etaxonomy.taxeditor.store.showViewMenu.details"
- visible="true">
- </separator>
- <command
- commandId="org.eclipse.ui.views.showView"
+ id="eu.etaxonomy.taxeditor.store.showViewMenu.details"
label="%command.label.0"
style="push">
<parameter
</visibleWhen>
</command>
</menuContribution>
- <menuContribution
- allPopups="false"
- locationURI="popup:eu.etaxonomy.taxeditor.view.derivateSearch.DerivateSearchView">
- <command
- commandId="eu.etaxonomy.taxeditor.editor.handler.openDerivateView"
- label="%command.label.openInSpecimenEditor"
- style="push">
- <visibleWhen
- checkEnabled="true">
- <with
- variable="selection">
- <count
- value="+">
- </count>
- </with>
- </visibleWhen>
- </command>
- </menuContribution>
</extension>
<extension
point="org.eclipse.ui.handlers">
+++ /dev/null
-package eu.etaxonomy.taxeditor.handler;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-public class CreateFieldUnitHandler extends AbstractHandler {
-
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ISelection currentSelection = HandlerUtil.getCurrentSelection(event);
- if(currentSelection instanceof IStructuredSelection){
- System.out.println(currentSelection);
- }
- return null;
- }
-
-}
*/
@Override
protected void javaToNative(Object object, TransferData transferData) {
- byte[] bytes = toByteArray((T[]) object);
- if (bytes != null)
- super.javaToNative(bytes, transferData);
+ if (object != null){
+ byte[] bytes = toByteArray((T[]) object);
+ if (bytes != null)
+ super.javaToNative(bytes, transferData);
+ }
}
/* (non-Javadoc)
@Override
protected Object nativeToJava(TransferData transferData) {
byte[] bytes = (byte[]) super.nativeToJava(transferData);
- return fromByteArray(bytes);
+ if (bytes != null){
+ return fromByteArray(bytes);
+ }
+ return null;
}
+
protected byte[] toByteArray(T[] elements) {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
package eu.etaxonomy.taxeditor.newWizard;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-import org.eclipse.core.commands.Command;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.commands.NotEnabledException;
-import org.eclipse.core.commands.NotHandledException;
-import org.eclipse.core.commands.ParameterizedCommand;
-import org.eclipse.core.commands.common.NotDefinedException;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialogWithToggle;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.commands.ICommandService;
-import org.eclipse.ui.handlers.IHandlerService;
-
import eu.etaxonomy.cdm.api.facade.DerivedUnitFacade;
import eu.etaxonomy.cdm.api.facade.DerivedUnitFacadeNotSupportedException;
import eu.etaxonomy.cdm.api.service.IOccurrenceService;
import eu.etaxonomy.cdm.model.occurrence.MediaSpecimen;
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationType;
-import eu.etaxonomy.taxeditor.model.AbstractUtility;
import eu.etaxonomy.taxeditor.model.IDerivedUnitFacadePart;
-import eu.etaxonomy.taxeditor.model.MessagingUtils;
-import eu.etaxonomy.taxeditor.preference.IPreferenceKeys;
import eu.etaxonomy.taxeditor.preference.PreferencesUtil;
import eu.etaxonomy.taxeditor.store.CdmStore;
import eu.etaxonomy.taxeditor.ui.section.occurrence.DerivedUnitBaseWizardPage;
import eu.etaxonomy.taxeditor.ui.section.occurrence.FieldUnitGeneralWizardPage;
import eu.etaxonomy.taxeditor.ui.section.occurrence.FieldUnitWizardPage;
import eu.etaxonomy.taxeditor.ui.section.occurrence.GatheringEventWizardPage;
-import eu.etaxonomy.taxeditor.view.derivateSearch.DerivateSearchCompositeController;
/**
* @author n.hoffmann
return "Specimen";
}
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean performFinish() {
- boolean performFinish = super.performFinish();
- int returnCode = IDialogConstants.NO_ID;
- if (!PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.PROMPT_FOR_OPEN_SPECIMEN_IN_EDITOR)){
- MessageDialogWithToggle messageDialog = MessageDialogWithToggle.openYesNoQuestion(getShell(),
- "Choose opening option", "Do you want to open the specimen in the specimen editor?",
- "Remember my decision?", false, PreferencesUtil.getPreferenceStore(),
- IPreferenceKeys.ALWAYS_OPEN_SPECIMEN_IN_EDITOR);
- returnCode = messageDialog.getReturnCode();
- PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.PROMPT_FOR_OPEN_SPECIMEN_IN_EDITOR, messageDialog.getToggleState());
- if (returnCode != IDialogConstants.YES_ID) {
- return performFinish;
- }
- }
- if (returnCode==IDialogConstants.YES_ID ||
- PreferencesUtil.getPreferenceStore().getString(IPreferenceKeys.ALWAYS_OPEN_SPECIMEN_IN_EDITOR)
- .equals(MessageDialogWithToggle.ALWAYS)) {
- IHandlerService handlerService = (IHandlerService) AbstractUtility.getService(IHandlerService.class);
-
- // get the command from plugin.xml
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- ICommandService cmdService = (ICommandService) window.getService(ICommandService.class);
- Command command = cmdService.getCommand("eu.etaxonomy.taxeditor.editor.openSpecimenEditor");
- Map<String, UUID> parameters = new HashMap<String, UUID>();
- parameters.put("eu.etaxonomy.taxeditor.specimenUuidParameter", getEntity().getUuid());
- ParameterizedCommand parameterizedCommand = ParameterizedCommand.generateCommand(command, parameters);
-
-
- // execute the command
- try {
- handlerService.executeCommand(parameterizedCommand, null);
- } catch (ExecutionException e) {
- MessagingUtils.error(DerivateSearchCompositeController.class, e);
- } catch (NotDefinedException e) {
- MessagingUtils.error(DerivateSearchCompositeController.class, e);
- } catch (NotEnabledException e) {
- MessagingUtils.error(DerivateSearchCompositeController.class, e);
- } catch (NotHandledException e) {
- MessagingUtils.error(DerivateSearchCompositeController.class, e);
- }
- }
-
- return performFinish;
- }
-
-
}
public static final String SHOW_ADVANCED_MEDIA_SECTION = "eu.etaxonomy.taxeditor.media.showAdvancedMedia";
- public static final String ALWAYS_OPEN_SPECIMEN_IN_EDITOR = "eu.etaxonomy.taxeditor.specimen.alwaysOpenSpecimenInEditor";
-
public static final String PROMPT_FOR_OPEN_SPECIMEN_IN_EDITOR = "eu.etaxonomy.taxeditor.specimen.promptForOpenSpecimenInEditor";
// TODO RL
*/
package eu.etaxonomy.taxeditor.preference;
-import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.preference.BooleanFieldEditor;
-import org.eclipse.jface.preference.ComboFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
addField(new BooleanFieldEditor(IPreferenceKeys.SHOW_TAXON_ASSOCIATIONS,
"Show taxon associations of a specimen in the details view",
getFieldEditorParent()));
- addField(new ComboFieldEditor(IPreferenceKeys.ALWAYS_OPEN_SPECIMEN_IN_EDITOR,
- "Open newly created specimens in specimen editor", new String[][] {
- { "always", MessageDialogWithToggle.ALWAYS }, { "never", MessageDialogWithToggle.NEVER } },
- getFieldEditorParent()));
}
import eu.etaxonomy.taxeditor.ui.dialog.RemotingLoginDialog;
import eu.etaxonomy.taxeditor.util.ProgressMonitorClientManager;
import eu.etaxonomy.taxeditor.view.datasource.CdmDataSourceViewPart;
+import eu.etaxonomy.taxeditor.webapp.CDMServer;
/**
* This implementation of ICdmDataRepository depends on hibernate sessions to
private static CdmStoreConnector job;
+ private static CDMServer managedServer;
+
private Language language;
private ICdmSource cdmSource;
return cdmSource;
}
+
+ public static void setManagedServer(CDMServer server) {
+ managedServer = server;
+ }
+
+ public static CDMServer getManagedServer() {
+ return managedServer;
+ }
+
}
*/
package eu.etaxonomy.taxeditor.ui.dialog;
+import java.io.File;
+import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.events.IExpansionListener;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
+import org.eclipse.ui.progress.IProgressConstants;
import org.eclipse.wb.swt.SWTResourceManager;
import org.osgi.service.prefs.BackingStoreException;
import org.osgi.service.prefs.Preferences;
import eu.etaxonomy.taxeditor.preference.IPreferenceKeys;
import eu.etaxonomy.taxeditor.preference.PreferencesUtil;
import eu.etaxonomy.taxeditor.remoting.server.CDMServerException;
+import eu.etaxonomy.taxeditor.remoting.server.CDMServerUtils;
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
import eu.etaxonomy.taxeditor.remoting.source.CdmServerInfo;
import eu.etaxonomy.taxeditor.remoting.source.CdmServerInfo.CdmInstanceInfo;
import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
import eu.etaxonomy.taxeditor.store.CdmStore;
+import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
+import eu.etaxonomy.taxeditor.webapp.CDMEmbeddedServerException;
+import eu.etaxonomy.taxeditor.webapp.CDMServer;
+import eu.etaxonomy.taxeditor.webapp.ICDMServerError;
+
/**
* @author cmathew
* @date 20 Jan 2015
*
*/
-public class RemotingLoginDialog extends Dialog {
+public class RemotingLoginDialog extends Dialog implements ICDMServerError {
protected Object result;
protected Shell shlConnect;
private final static String STATUS_AVAILABLE = "Available";
private final static String STATUS_NOT_AVAILABLE = "Not Available";
+ private final static String STATUS_STARTED = "Started";
+ private final static String STATUS_NOT_STARTED = "Not Started";
private final static String STATUS_RETRIEVING = "Retrieving ...";
private final static String STATUS_CHECKING_AVAILABILITY = "Checking ...";
private final static String STATUS_NO_INSTANCES = "No Instances Found";
private final static String LAST_SERVER_KEY = "lastServerKey";
private final static String LAST_INSTANCE_KEY = "lastInstanceKey";
+ private final static String REFRESH_LABEL = "Refresh";
private Composite remotingComposite;
private CdmServerInfo selectedCsii;
private CdmInstanceInfo selectedCdmInstance;
private Button btnCdmServerRefresh;
+ private Button btnCdmInstanceRefresh;
+ private Button btnStopServer;
private Composite loginComposite;
private Label lblLogin;
private Text txtLogin;
private boolean autoConnect = false;
private boolean loadLoginPrefs = true;
private boolean isDevRemoteSource = false;
-
+ private Job serverJob;
/**
* Create the dialog.
* @param parent
* @return the result
*/
public Object open() {
- // ICdmRemoteSource devRemoteSource = CdmServerInfo.getDevServerRemoteSource();
- // if(devRemoteSource != null) {
- // connect(devRemoteSource);
- // } else {
+
createContents();
if(serverName == null && instanceName == null) {
readPrefLastServerInstance();
display.sleep();
}
}
- //}
+
return result;
}
comboCdmInstance.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
- updateSelectedCdmInstance();
- checkSelectedCdmInstance();
+ refreshCdmInstance();
}
});
GridData gd_comboCdmInstance = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
gd_txtCdmInstanceStatus.widthHint = 100;
txtCdmInstanceStatus.setLayoutData(gd_txtCdmInstanceStatus);
- Button btnCdmInstanceRefresh = new Button(cdmServerComposite, SWT.FLAT);
+ btnCdmInstanceRefresh = new Button(cdmServerComposite, SWT.FLAT);
btnCdmInstanceRefresh.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
btnConnect.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
- connect();
+ if(selectedCsii.isLocalhostMgd() && !isSelectedCdmInstanceRunningInManagedServer()) {
+ startManagedServer();
+ } else {
+ connect();
+ }
}
});
btnConnect.setText("Connect");
txtServerVersion = new Text(compAdvanced, SWT.BORDER);
txtServerVersion.setEditable(false);
txtServerVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
- new Label(compAdvanced, SWT.NONE);
- new Label(compAdvanced, SWT.NONE);
+ btnStopServer = new Button(compAdvanced, SWT.FLAT);
+ btnStopServer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
+ btnStopServer.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseUp(MouseEvent e) {
+ stopManagedServer();
+ }
+ });
+ btnStopServer.setText("Stop Managed Server");
lblEditorVersion = new Label(compAdvanced, SWT.CENTER);
lblEditorVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
private void updatePort() {
txtPort.setText("");
if(selectedCsii != null) {
- txtPort.setText(String.valueOf(selectedCsii.getPort()));
+ int port = selectedCsii.getPort();
+ if(port == CdmServerInfo.NULL_PORT) {
+ txtPort.setText(CdmServerInfo.NULL_PORT_STRING);
+ } else {
+ txtPort.setText(String.valueOf(port));
+ }
}
}
private int getPort() {
- int port = 0;
+ int port = CdmServerInfo.NULL_PORT;
try {
port = Integer.valueOf(txtPort.getText());
} catch (NumberFormatException nfe) {
- setMessage("Port should be an integer");
+ if(!CdmServerInfo.NULL_PORT_STRING.equals(txtPort.getText())) {
+ setMessage("Port should be an integer");
+ }
}
return port;
}
if(selectedCsii.pingServer()) {
txtCdmServerStatus.setText(STATUS_AVAILABLE);
populateCdmInstanceCombo(true);
- txtServerVersion.setText(selectedCsii.getCdmlibServicesVersion());
- txtServerVersion.setToolTipText(generateLastModifiedTooltip(selectedCsii.getCdmlibLastModified()));
-
+ String serverVersionTimestamp = generateLastModifiedTooltip(selectedCsii.getCdmlibLastModified());
+ txtServerVersion.setText(selectedCsii.getCdmlibServicesVersion() + ":" + serverVersionTimestamp);
} else {
txtCdmServerStatus.setText(STATUS_NOT_AVAILABLE);
comboCdmInstance.removeAll();
txtCdmInstanceStatus.setText(STATUS_RETRIEVING);
txtCdmInstanceStatus.setToolTipText("");
- Job job = new Job("Retrieve Server Instances") {
+ serverJob = new Job("Retrieve Server Instances") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
} else {
comboCdmInstance.select(instanceIndex);
}
- updateSelectedCdmInstance();
- checkSelectedCdmInstance();
+ refreshCdmInstance();
comboCdmInstance.setEnabled(true);
if(autoConnect) {
connect();
if(txtCdmServerStatus.getText().equals(STATUS_AVAILABLE) && !isDevRemoteSource) {
// Start the Job
- job.schedule();
+ serverJob.schedule();
}
+
}
private void refreshCdmInstance() {
clearOnInstanceChange();
updateSelectedCdmInstance();
checkSelectedCdmInstance();
+ updateManagedServerControls();
}
private void updateSelectedCdmInstance() {
int selIndex = comboCdmInstance.getSelectionIndex();
if(selIndex != -1) {
selectedCdmInstance = selectedCsii.getInstanceFromName(comboCdmInstance.getItem(selIndex));
+
if(loadLoginPrefs && !isDevRemoteSource) {
readPrefCredentials();
}
}
}
+ private void updateManagedServerControls() {
+ if(selectedCsii.isLocalhostMgd()) {
+ if(isSelectedCdmInstanceRunningInManagedServer()) {
+ txtCdmInstanceStatus.setText(STATUS_STARTED);
+ } else {
+ txtCdmInstanceStatus.setText(STATUS_NOT_STARTED);
+ }
+ btnConnect.setEnabled(true);
+ selectedCsii.setPort(getManagedServerPort());
+ updatePort();
+ }
+
+
+ if(isManagedServerRunning()) {
+ btnStopServer.setEnabled(true);
+ } else {
+ btnStopServer.setEnabled(false);
+ }
+ }
+
+ private boolean isManagedServerRunning() {
+ return CdmStore.getManagedServer() != null && CdmStore.getManagedServer().isAlive();
+ }
+
+ private boolean isSelectedCdmInstanceRunningInManagedServer() {
+ return CdmStore.getManagedServer() != null &&
+ CdmStore.getManagedServer().isAlive() &&
+ selectedCsii.isLocalhostMgd() &&
+ CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName());
+ }
+
+ private boolean isActiveCdmInstanceRunningInManagedServer() {
+ return CdmStore.getManagedServer() != null &&
+ CdmStore.getManagedServer().isAlive() &&
+ CdmStore.isActive() &&
+ CdmServerInfo.NAME_LOCALHOST_MGD.equals(CdmStore.getActiveCdmSource().getName());
+ }
+
+
+ private void startManagedServer() {
+ if(isManagedServerRunning()) {
+ if(CdmStore.getManagedServer().getDataSourceName().equals(selectedCdmInstance.getName())) {
+ return;
+ } else {
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ stopManagedServer();
+ }
+ });
+ }
+ }
+
+
+ Job job = new Job("Managed CDM Server Launch") {
+
+ @Override
+ public IStatus run(IProgressMonitor monitor) {
+ String mgdServerConfigFileName = "mgd.datasources.xml";
+ String config = CDMServerUtils.convertEditorToServerConfig();
+ File managedServerConfigFile;
+ int maxUnits = 50;
+ monitor.beginTask("Launching Managed CDM Server", maxUnits);
+ try {
+ monitor.subTask("Generating datasources config file for " + selectedCdmInstance.getName());
+ managedServerConfigFile = CDMServerUtils.writeManagedServerConfig(config, mgdServerConfigFileName);
+ monitor.worked(1);
+ CdmStore.setManagedServer(new CDMServer(selectedCdmInstance.getName(), managedServerConfigFile));
+ monitor.subTask("Starting Managed CDM Server. This may take a while.");
+ CdmStore.getManagedServer().start(false, RemotingLoginDialog.this);
+ int serverUnits = 0;
+
+ // the following loop is a 'fake' progress monitoring where the progress
+ // bar is advanced by one unit every second until maxUnits -2
+ while(!CdmStore.getManagedServer().isStarted()) {
+ if(serverUnits < maxUnits - 2) {
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ }
+ monitor.worked(1);
+ serverUnits++;
+ }
+ }
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ hide(false);
+ updateManagedServerControls();
+ connect();
+ }
+ });
+ } catch (IOException ioe) {
+ MessagingUtils.errorDialog("Error generating server config file",
+ this,
+ ioe.getMessage(),
+ TaxeditorStorePlugin.PLUGIN_ID,
+ ioe,
+ true);
+ } catch (CDMEmbeddedServerException cse) {
+ MessagingUtils.errorDialog("Error starting managed server",
+ this,
+ cse.getMessage(),
+ TaxeditorStorePlugin.PLUGIN_ID,
+ cse,
+ true);
+ } finally {
+ monitor.done();
+ }
+ return Status.OK_STATUS;
+ }
+ };
+
+ // configure the job
+ job.setProperty(IProgressConstants.KEEP_PROPERTY, true);
+ job.setUser(true);
+ // schedule job
+ hide(true);
+ job.schedule();
+ }
+
+ private void stopManagedServer() {
+ try {
+ CdmStore.getManagedServer().stop();
+ } catch (Exception e) {
+ MessagingUtils.errorDialog("Error stopping managed server",
+ this,
+ "Could not stop managed server running at port " + CdmStore.getManagedServer().getPort() + ". Please stop it manually",
+ TaxeditorStorePlugin.PLUGIN_ID,
+ e,
+ true);
+ }
+ CdmStore.setManagedServer(null);
+ updateManagedServerControls();
+ }
+
+ private int getManagedServerPort() {
+ return CdmStore.getManagedServer() == null ? CdmServerInfo.NULL_PORT : CdmStore.getManagedServer().getPort();
+ }
+
private void checkSelectedCdmInstance() {
boolean available = false;
String status = STATUS_NOT_AVAILABLE;
setMessage(message);
}
}
-
}
-
}
private void connect() {
}
private String generateLastModifiedTooltip(String cdmlibLastModified) {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd 'at' HH:mm:ss z");
+ if(StringUtils.isBlank(cdmlibLastModified)) {
+ return "";
+ }
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.z");
Date cdmlibLastModifiedDate;
String cdmlibLastModifiedTimestamp = "";
cdmlibLastModifiedDate = new Date(Long.valueOf(cdmlibLastModified));
cdmlibLastModifiedTimestamp = sdf.format(cdmlibLastModifiedDate);
- return "last modified : " + cdmlibLastModifiedTimestamp;
+ return cdmlibLastModifiedTimestamp;
}
private void setEditorInfo() {
txtEditorCDMVersion.setText(CdmMetaData.getDbSchemaVersion());
- txtEditorVersion.setText(CdmApplicationState.getCdmlibVersion());
- txtEditorVersion.setToolTipText(generateLastModifiedTooltip(CdmApplicationState.getCdmlibLastModified()));
+ String editorVersionTimestamp = generateLastModifiedTooltip(CdmApplicationState.getCdmlibLastModified());
+ txtEditorVersion.setText(CdmApplicationState.getCdmlibVersion() + ":" + editorVersionTimestamp);
}
private void clearOnServerChange() {
txtServerCDMVersion.setText("");
}
- private void updateOnServerChange(String serverVersion, String serverVersionTooltip) {
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void handleError(final Throwable t) {
+
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ serverJob.cancel();
+ String title = "CDM Server launch error";
+ String message = t.getMessage();
+
+
+ MessagingUtils.errorDialog(title,
+ this,
+ message,
+ TaxeditorStorePlugin.PLUGIN_ID,
+ t,
+ true);
+ }
+ });
}
+
}
import eu.etaxonomy.cdm.api.service.config.DeleteConfiguratorBase;
import eu.etaxonomy.cdm.api.service.config.SpecimenDeleteConfigurator;
import eu.etaxonomy.cdm.api.service.config.TaxonBaseDeletionConfigurator;
+import eu.etaxonomy.cdm.api.service.config.TaxonDeletionConfigurator;
import eu.etaxonomy.cdm.api.service.config.TaxonNodeDeletionConfigurator;
/**
@Override
protected Control createCustomArea(Composite parent) {
DeleteConfiguratorComposite composite = new DeleteConfiguratorComposite(parent, NONE);
- if(configurator instanceof TaxonBaseDeletionConfigurator){
- composite.addConfiguratorComposite(new DeleteTaxonConfiguratorComposite((TaxonBaseDeletionConfigurator) configurator, composite.getSectionConfigure(), SWT.NONE));
+ if(configurator instanceof TaxonDeletionConfigurator){
+ composite.addConfiguratorComposite(new DeleteTaxonConfiguratorComposite((TaxonDeletionConfigurator) configurator, composite.getSectionConfigure(), SWT.NONE));
}
else if(configurator instanceof SpecimenDeleteConfigurator){
composite.addConfiguratorComposite(new DeleteSpecimenConfiguratorComposite((SpecimenDeleteConfigurator) configurator, composite.getSectionConfigure(), SWT.NONE));
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.forms.widgets.FormToolkit;
-import eu.etaxonomy.cdm.api.service.config.TaxonBaseDeletionConfigurator;
+import eu.etaxonomy.cdm.api.service.config.TaxonDeletionConfigurator;
+import eu.etaxonomy.cdm.common.CdmUtils;
+import eu.etaxonomy.cdm.model.taxon.Classification;
+
/**
* @author pplitzner
private final DataBindingContext m_bindingContext;
private final FormToolkit toolkit = new FormToolkit(Display.getCurrent());
- private final TaxonBaseDeletionConfigurator configurator;
+ private final TaxonDeletionConfigurator configurator;
private final Button btnDeleteTaxonName;
+ private final Button btnDeleteInAllClassifications;
+ private Combo classificationSelectionCombo;
+
+
/**
* Create the composite.
* @param parent
* @param style
*/
- public DeleteTaxonConfiguratorComposite(TaxonBaseDeletionConfigurator configurator, Composite parent, int style) {
+ public DeleteTaxonConfiguratorComposite(TaxonDeletionConfigurator configurator, Composite parent, int style) {
super(parent, style);
this.configurator = configurator;
addDisposeListener(new DisposeListener() {
btnDeleteTaxonName = new Button(this, SWT.CHECK);
btnDeleteTaxonName.setText("Delete taxon name if possible");
+ btnDeleteTaxonName.setSelection(true);
+
+ btnDeleteInAllClassifications = new Button(this, SWT.CHECK);
+ btnDeleteInAllClassifications.setText("Delete taxon in all classifications");
+ btnDeleteInAllClassifications.setSelection(true);
+
m_bindingContext = initDataBindings();
}
//
IObservableValue observeSelectionBtnDeleteTaxonNameObserveWidget = WidgetProperties.selection().observe(btnDeleteTaxonName);
IObservableValue deleteNameIfPossibleConfiguratorObserveValue = PojoProperties.value("deleteNameIfPossible").observe(configurator);
+
+ IObservableValue observeSelectionBtnDeleteInAllClassificationObserveWidget = WidgetProperties.selection().observe(btnDeleteInAllClassifications);
+ IObservableValue deleteInAllClassificationsConfiguratorObserveValue = PojoProperties.value("deleteInAllClassifications").observe(configurator);
bindingContext.bindValue(observeSelectionBtnDeleteTaxonNameObserveWidget, deleteNameIfPossibleConfiguratorObserveValue, null, null);
+ bindingContext.bindValue(observeSelectionBtnDeleteInAllClassificationObserveWidget, deleteInAllClassificationsConfiguratorObserveValue, null, null);
//
return bindingContext;
}
+
+ /* private Control createClassificationSelectionCombo(Composite parent){
+// classifications = CdmStore.getTaxonTreeService().list(null, null, null, null, null);
+
+ Composite classificationSelection = new Composite(parent, SWT.NULL);
+ classificationSelection.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
+
+ GridLayout layout = new GridLayout();
+ classificationSelection.setLayout(layout);
+
+ Label label = new Label(classificationSelection, SWT.NULL);
+ // TODO not working is not really true but leave it here to remind everyone that this is under construction
+ label.setText("Select Classification");
+ classificationSelectionCombo = new Combo(classificationSelection, SWT.BORDER | SWT.READ_ONLY);
+ classificationSelectionCombo.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
+ List<Classification> classifications =
+
+ for(Classification tree : classifications){
+ classificationSelectionCombo.add(tree.getName().getText(), classifications.indexOf(tree));
+
+ }
+
+ classificationSelectionCombo.select(classifications.indexOf(selectedClassification));
+
+ // TODO remember last selection
+ classificationSelectionCombo.addSelectionListener(this);
+
+
+
+ return classificationSelection;
+ }*/
}
import eu.etaxonomy.cdm.model.occurrence.Collection;
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
+import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
import eu.etaxonomy.cdm.model.reference.Reference;
import eu.etaxonomy.cdm.model.taxon.Classification;
import eu.etaxonomy.cdm.model.taxon.Synonym;
return null;
}
if(clazz.equals(DerivedUnit.class)){
- return (T) DerivedUnitSelectionDialog.select(shell, conversation, (DerivedUnit) currentSelection);
+ return (T) DerivedUnitSelectionDialog.select(shell, conversation, (DerivedUnit) currentSelection);
}
if(clazz.equals(FieldUnit.class)){
- return (T) FieldUnitSelectionDialog.select(shell, conversation, (FieldUnit) currentSelection);
+ return (T) FieldUnitSelectionDialog.select(shell, conversation, (FieldUnit) currentSelection);
+ }
+ if(clazz.equals(SpecimenOrObservationBase.class)){
+ return (T) SpecimenOrObservationBaseSelectionDialog.select(shell, conversation, (SpecimenOrObservationBase) currentSelection);
}
if(clazz.equals(NamedArea.class)){
if(parentElement instanceof IEntityElement && ((IEntityElement) parentElement).getEntity() instanceof DerivedUnitFacade){
--- /dev/null
+// $Id$
+/**
+* Copyright (C) 2007 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* 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.ui.dialog.selection;
+
+import java.util.UUID;
+
+import org.eclipse.swt.widgets.Shell;
+
+import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
+import eu.etaxonomy.cdm.api.service.IOccurrenceService;
+import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
+import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
+import eu.etaxonomy.taxeditor.newWizard.AbstractNewEntityWizard;
+import eu.etaxonomy.taxeditor.newWizard.NewDerivedUnitBaseWizard;
+import eu.etaxonomy.taxeditor.store.CdmStore;
+
+/**
+ * @author pplitzner
+ */
+public class SpecimenOrObservationBaseSelectionDialog extends
+ AbstractFilteredCdmResourceSelectionDialog<SpecimenOrObservationBase> {
+
+ public static SpecimenOrObservationBase select(Shell shell, ConversationHolder conversation, SpecimenOrObservationBase observation){
+ SpecimenOrObservationBaseSelectionDialog dialog = new SpecimenOrObservationBaseSelectionDialog(shell, conversation,
+ "Choose field unit or derived unit", false, SpecimenOrObservationBaseSelectionDialog.class.getCanonicalName(), observation);
+ return getSelectionFromDialog(dialog);
+ }
+
+ protected SpecimenOrObservationBaseSelectionDialog(Shell shell, ConversationHolder conversation,
+ String title, boolean multi, String settings,
+ SpecimenOrObservationBase cdmObject) {
+ super(shell, conversation, title, multi, settings, cdmObject);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected SpecimenOrObservationBase getPersistentObject(UUID uuid) {
+ Object object = CdmStore.getService(IOccurrenceService.class).load(uuid);
+ return HibernateProxyHelper.deproxy(object, SpecimenOrObservationBase.class);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected void initModel() {
+ model = CdmStore.getService(IOccurrenceService.class).getUuidAndTitleCache();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected AbstractNewEntityWizard getNewEntityWizard(String parameter) {
+ return new NewDerivedUnitBaseWizard();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected String getNewWizardLinkText() {
+ return String.format("Create a new <a>%1s</a>", "field unit/derived unit");
+ }
+}
*/
@Override
public ConversationHolder getConversationHolder() {
- if(getParentElement() instanceof RootElement || getParentElement() == null){
-
- IEditorPart activeEditor = AbstractUtility.getActiveEditor();
- if(activeEditor instanceof IConversationEnabled){
- ConversationHolder conversation = ((IConversationEnabled) AbstractUtility.getActiveEditor()).getConversationHolder();
- return conversation;
- }
- }else if(getParentElement() instanceof IConversationEnabled){
- return ((IConversationEnabled) getParentElement()).getConversationHolder();
- }
+ if(AbstractUtility.getActivePart() instanceof IConversationEnabled){
+ return ((IConversationEnabled) AbstractUtility.getActivePart()).getConversationHolder();
+ }
+ if(getParentElement() instanceof RootElement || getParentElement() == null){
+
+ IEditorPart activeEditor = AbstractUtility.getActiveEditor();
+ if(activeEditor instanceof IConversationEnabled){
+ ConversationHolder conversation = ((IConversationEnabled) AbstractUtility.getActiveEditor()).getConversationHolder();
+ return conversation;
+ }
+ }else if(getParentElement() instanceof IConversationEnabled){
+ return ((IConversationEnabled) getParentElement()).getConversationHolder();
+ }
MessagingUtils.messageDialog("Could not get conversation for AbstractFormSection",
getClass(), "There is an error in the implementation. There should have been an active editor but it wasn't",
new IllegalArgumentException());
import eu.etaxonomy.taxeditor.ui.section.occurrence.SpecimenCollectionDetailSection;
import eu.etaxonomy.taxeditor.ui.section.occurrence.SpecimenHierarchyDetailElement;
import eu.etaxonomy.taxeditor.ui.section.occurrence.SpecimenHierarchyDetailSection;
+import eu.etaxonomy.taxeditor.ui.section.occurrence.association.DerivedUnitTypeDesignationElement;
+import eu.etaxonomy.taxeditor.ui.section.occurrence.association.DerivedUnitTypeDesignationSection;
import eu.etaxonomy.taxeditor.ui.section.occurrence.association.TaxonAssociationDetailElement;
import eu.etaxonomy.taxeditor.ui.section.occurrence.association.TaxonAssociationDetailSection;
import eu.etaxonomy.taxeditor.ui.section.occurrence.derivedUnit.PreservedSpecimenCurrentDeterminationDetailSection;
return section;
}
+ public DerivedUnitTypeDesignationSection createDerivedUnitTypeDesignationSection(ConversationHolder conversation, ICdmFormElement parentElement, ISelectionProvider selectionProvider, int style){
+ DerivedUnitTypeDesignationSection section = new DerivedUnitTypeDesignationSection(this, conversation, parentElement, style);
+ addAndAdaptSection(parentElement, section);
+ return section;
+ }
+
public TaxonAssociationDetailSection createTaxonAssociationDetailSection(ConversationHolder conversation, ICdmFormElement parentElement, ISelectionProvider selectionProvider, int style){
TaxonAssociationDetailSection section = new TaxonAssociationDetailSection(this, conversation, parentElement, selectionProvider, style);
addAndAdaptSection(parentElement, section);
element = new SynonymRelationshipDetailElement(this, parentElement, (SynonymRelationship) entity, removeListener,
style);
} else if (entity instanceof SpecimenTypeDesignation) {
- element = new SpecimenTypeDesignationElement(this, parentElement, (SpecimenTypeDesignation) entity,
- removeListener, style);
+ if(parentElement instanceof DerivedUnitTypeDesignationSection){
+ element = new DerivedUnitTypeDesignationElement(this, parentElement, (SpecimenTypeDesignation) entity,
+ removeListener, style);
+ }
+ else{
+ element = new SpecimenTypeDesignationElement(this, parentElement, (SpecimenTypeDesignation) entity,
+ removeListener, style);
+ }
} else if (entity instanceof StateData) {
element = new StateDataElement(this, parentElement, (StateData) entity, removeListener, style);
} else if (entity instanceof StatisticalMeasurementValue) {
/** {@inheritDoc} */
@Override
public DescriptionElementSource createNewElement() {
- if(getEntity().getId() == 0) {
+ /* if(getEntity().getId() == 0) {
MessagingUtils.warningDialog("Description not saved", this, "Please save the newly created description before adding source");
return null;
- }
+ }*/
return DescriptionElementSource.NewInstance(OriginalSourceType.PrimaryTaxonomicSource);
}
// $Id$
/**
* Copyright (C) 2007 EDIT
- * European Distributed Institute of Taxonomy
+ * European Distributed Institute of Taxonomy
* http://www.e-taxonomy.eu
- *
+ *
* 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.
*/
import eu.etaxonomy.cdm.model.common.Language;
import eu.etaxonomy.cdm.model.common.LanguageString;
import eu.etaxonomy.cdm.model.description.IndividualsAssociation;
-import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
+import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
import eu.etaxonomy.taxeditor.store.CdmStore;
import eu.etaxonomy.taxeditor.ui.element.CdmFormFactory;
import eu.etaxonomy.taxeditor.ui.element.ICdmFormElement;
import eu.etaxonomy.taxeditor.ui.selection.EntitySelectionElement;
/**
- * <p>
- * IndividualsAssociationDetailElement class.
- * </p>
- *
* @author n.hoffmann
* @created Jun 10, 2010
* @version 1.0
AbstractDetailedDescriptionDetailElement<IndividualsAssociation> {
private TextWithLabelElement text_description;
- private EntitySelectionElement<DerivedUnit> selection_derivedUnit;
+ private EntitySelectionElement<SpecimenOrObservationBase> selection_derivedUnit;
- /**
- * <p>
- * Constructor for IndividualsAssociationDetailElement.
- * </p>
- *
- * @param formFactory
- * a {@link eu.etaxonomy.taxeditor.ui.element.CdmFormFactory}
- * object.
- * @param formElement
- * a {@link eu.etaxonomy.taxeditor.ui.element.ICdmFormElement}
- * object.
- * @param entity
- * a
- * {@link eu.etaxonomy.cdm.model.description.IndividualsAssociation}
- * object.
- * @param style
- * a int.
- */
public IndividualsAssociationDetailElement(CdmFormFactory formFactory,
ICdmFormElement formElement, IndividualsAssociation entity,
int style) {
protected void createControls(ICdmFormElement formElement,
IndividualsAssociation entity, int style) {
selection_derivedUnit = formFactory
- .createSelectionElement(DerivedUnit.class,
- getConversationHolder(), formElement, "Unit",
- CdmBase.deproxy(entity.getAssociatedSpecimenOrObservation(),DerivedUnit.class),
+ .createSelectionElement(SpecimenOrObservationBase.class,
+ getConversationHolder(), formElement, "Occurrence/Unit",
+ CdmBase.deproxy(entity.getAssociatedSpecimenOrObservation(),SpecimenOrObservationBase.class),
EntitySelectionElement.ALL, style);
text_description = formFactory.createMultiLineTextWithLabel(
--- /dev/null
+// $Id$
+/**
+ * Copyright (C) 2007 EDIT
+ * European Distributed Institute of Taxonomy
+ * http://www.e-taxonomy.eu
+ *
+ * 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.ui.section.occurrence.association;
+
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.swt.events.SelectionListener;
+
+import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
+import eu.etaxonomy.cdm.model.common.TermType;
+import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation;
+import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignationStatus;
+import eu.etaxonomy.cdm.model.name.TaxonNameBase;
+import eu.etaxonomy.taxeditor.ui.combo.TermComboElement;
+import eu.etaxonomy.taxeditor.ui.element.AbstractFormSection;
+import eu.etaxonomy.taxeditor.ui.element.CdmFormFactory;
+import eu.etaxonomy.taxeditor.ui.element.ICdmFormElement;
+import eu.etaxonomy.taxeditor.ui.section.name.AbstractTypeDesignationElement;
+import eu.etaxonomy.taxeditor.ui.selection.EntitySelectionElement;
+
+/**
+ * @author n.hoffmann
+ * @created May 17, 2010
+ * @version 1.0
+ */
+public class DerivedUnitTypeDesignationElement extends AbstractTypeDesignationElement<SpecimenTypeDesignation> {
+
+ private TermComboElement<SpecimenTypeDesignationStatus> combo_typeStatus;
+
+ private List<EntitySelectionElement<TaxonNameBase>> selectionTaxonNames;
+ private ICdmFormElement parentFormElement;
+ private int style;
+
+ private EntitySelectionElement<TaxonNameBase> selectionTaxonName;
+
+ public DerivedUnitTypeDesignationElement(CdmFormFactory formFactory,
+ AbstractFormSection section, SpecimenTypeDesignation entity,
+ SelectionListener removeListener, int style) {
+ super(formFactory, section, entity, removeListener, style);
+ }
+
+ @Override
+ public void setEntity(SpecimenTypeDesignation entity) {
+ super.setEntity(entity);
+ Set<TaxonNameBase> typifiedNames = entity.getTypifiedNames();
+ if(typifiedNames.size()==1){
+ selectionTaxonName.setEntity(typifiedNames.iterator().next());
+ }
+ else if(typifiedNames.size()>1){
+ formFactory.createLabel(getLayoutComposite(), "!!!!!!!!");
+ }
+
+ SpecimenTypeDesignationStatus typeStatus = (SpecimenTypeDesignationStatus) HibernateProxyHelper
+ .deproxy(entity.getTypeStatus());
+ combo_typeStatus.setSelection(typeStatus);
+ checkbox_notDesignated.setSelection(entity.isNotDesignated());
+
+// for (TaxonNameBase taxonNameBase : typifiedNames) {
+// EntitySelectionElement<TaxonNameBase> selectionElement = formFactory.createSelectionElement(
+// TaxonNameBase.class, getConversationHolder(), parentFormElement, "Scientific Name", null,
+// EntitySelectionElement.EDITABLE | EntitySelectionElement.SELECTABLE, style);
+// selectionElement.setEntity(taxonNameBase);
+// }
+
+
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void createControls(ICdmFormElement element, int style) {
+ this.parentFormElement = element;
+ this.style = style;
+
+ selectionTaxonName = formFactory.createSelectionElement(
+ TaxonNameBase.class, getConversationHolder(), parentFormElement, "Scientific Name", null,
+ EntitySelectionElement.EDITABLE | EntitySelectionElement.SELECTABLE, style);
+
+ combo_typeStatus = formFactory.createDefinedTermComboElement(TermType.SpecimenTypeDesignationStatus,
+ parentFormElement, "Designation Status", null, style);
+
+ super.createControls(element, style);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void handleEvent(Object eventSource) {
+ if (eventSource == selectionTaxonName) {
+ selectionTaxonName.getSelection().addTypeDesignation(getEntity(), false);
+ } else if (eventSource == combo_typeStatus) {
+ getEntity().setTypeStatus(combo_typeStatus.getSelection());
+ } else if (eventSource == checkbox_notDesignated) {
+ getEntity().setNotDesignated(checkbox_notDesignated.getSelection());
+ } else if (eventSource == selection_reference) {
+ getEntity().setCitation(selection_reference.getSelection());
+ } else if (eventSource == text_referenceDetail) {
+ getEntity().setCitationMicroReference(
+ text_referenceDetail.getText());
+ }
+ }
+
+}
--- /dev/null
+// $Id$
+/**
+* Copyright (C) 2015 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* 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.ui.section.occurrence.association;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+
+import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
+import eu.etaxonomy.cdm.api.facade.DerivedUnitFacade;
+import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation;
+import eu.etaxonomy.cdm.model.name.TaxonNameBase;
+import eu.etaxonomy.taxeditor.ui.element.CdmFormFactory;
+import eu.etaxonomy.taxeditor.ui.element.ICdmFormElement;
+import eu.etaxonomy.taxeditor.ui.section.AbstractEntityCollectionSection;
+
+/**
+ * @author pplitzner
+ * @date Oct 29, 2015
+ *
+ */
+public class DerivedUnitTypeDesignationSection extends AbstractEntityCollectionSection<DerivedUnitFacade, SpecimenTypeDesignation> {
+
+ private Collection<SpecimenTypeDesignation> typeDesignations;
+
+ public DerivedUnitTypeDesignationSection(CdmFormFactory formFactory,
+ ConversationHolder conversation, ICdmFormElement parentElement, int style) {
+ super(formFactory, conversation, parentElement, "Type Designations", style);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public Collection<SpecimenTypeDesignation> getCollection(DerivedUnitFacade entity) {
+ typeDesignations = entity.innerDerivedUnit().getSpecimenTypeDesignations();
+ return typeDesignations;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public SpecimenTypeDesignation createNewElement() {
+ return SpecimenTypeDesignation.NewInstance();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void addElement(SpecimenTypeDesignation element) {
+ element.setTypeSpecimen(getEntity().innerDerivedUnit());
+ typeDesignations.add(element);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void removeElement(SpecimenTypeDesignation element) {
+ List<SpecimenTypeDesignation> toRemove = new ArrayList<SpecimenTypeDesignation>();
+ for (SpecimenTypeDesignation specimenTypeDesignation : typeDesignations) {
+ if(element.equals(specimenTypeDesignation)){
+ toRemove.add(specimenTypeDesignation);
+ }
+ }
+ for (SpecimenTypeDesignation specimenTypeDesignation : toRemove) {
+ specimenTypeDesignation.removeType();
+ Set<TaxonNameBase> names = specimenTypeDesignation.getTypifiedNames();
+ for (TaxonNameBase taxonNameBase : names) {
+ taxonNameBase.removeTypeDesignation(specimenTypeDesignation);
+ }
+ }
+ typeDesignations.removeAll(toRemove);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public String getEmptyString() {
+ return "No type designation yet.";
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected String getTooltipString() {
+ return "Add a type designation";
+ }
+
+
+}
\ No newline at end of file
import java.util.ArrayList;
import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ExecutionException;
import eu.etaxonomy.cdm.api.facade.DerivedUnitFacade;
import eu.etaxonomy.cdm.api.service.IOccurrenceService;
-import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
-import eu.etaxonomy.cdm.model.common.CdmBase;
-import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation;
-import eu.etaxonomy.cdm.model.name.TaxonNameBase;
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
import eu.etaxonomy.taxeditor.model.MessagingUtils;
import eu.etaxonomy.taxeditor.store.CdmStore;
*/
public class TaxonAssociationDetailElement extends AbstractCdmDetailElement<DerivedUnitFacade> implements IDoubleClickListener{
-
private TableViewer associationsViewer;
- private TableViewer typeDesignationViewer;
public TaxonAssociationDetailElement(CdmFormFactory formFactory, ICdmFormElement formElement) {
super(formFactory, formElement);
//TODO add context menu for deleting associations
Collection<TaxonBase<?>> associatedTaxa = CdmStore.getService(IOccurrenceService.class).listAssociatedTaxa(entity.innerDerivedUnit(), null, null, null, null);
- Collection<SpecimenTypeDesignation> typeDesignations = CdmStore.getService(IOccurrenceService.class).listTypeDesignations(entity.innerDerivedUnit(), null, null, null, null);
if(!associatedTaxa.isEmpty()){
associationsViewer = new TableViewer(getLayoutComposite(), SWT.FULL_SELECTION);
label.setLayoutData(LayoutConstants.FILL_HORIZONTALLY(2, 1));
}
- //TODO implement service method for this which is just used in the label provider
- Collection<TaxonBase<?>> typedTaxa = new HashSet<TaxonBase<?>>();
- for (SpecimenTypeDesignation specimenTypeDesignation : typeDesignations) {
- for (TaxonNameBase taxonNameBase : specimenTypeDesignation.getTypifiedNames()) {
- Set taxa = taxonNameBase.getTaxa();
- for (Object taxon : taxa) {
- if(taxon instanceof CdmBase && ((CdmBase)taxon).isInstanceOf(TaxonBase.class)){
- typedTaxa.add(HibernateProxyHelper.deproxy(taxon, TaxonBase.class));
- }
- }
- }
- }
- if(!typedTaxa.isEmpty()){
- Label typeLabel = formFactory.createLabel(getLayoutComposite(), "Type Designations");
- typeLabel.setLayoutData(LayoutConstants.FILL_HORIZONTALLY(2, 1));
-
- typeDesignationViewer = new TableViewer(getLayoutComposite(), SWT.FULL_SELECTION);
- typeDesignationViewer.getTable().setLayoutData(LayoutConstants.FILL_HORIZONTALLY(2, 1));
- typeDesignationViewer.setContentProvider(new ArrayContentProvider());
- typeDesignationViewer.setInput(typedTaxa);
- typeDesignationViewer.addDoubleClickListener(this);
- }
}
/** {@inheritDoc} */
import eu.etaxonomy.cdm.model.name.NonViralName;
import eu.etaxonomy.cdm.model.occurrence.Collection;
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
+import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
+import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
+import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationType;
import eu.etaxonomy.cdm.model.reference.Reference;
import eu.etaxonomy.taxeditor.model.AbstractUtility;
import eu.etaxonomy.taxeditor.model.IDirtyMarkable;
addPage(new NonViralNameWizardPage(formFactory,
selectionElement.getConversationHolder(),
(NonViralName) entity));
- } else if (entity instanceof DerivedUnit) {
+ } else if (entity instanceof SpecimenOrObservationBase) {
DerivedUnitFacade facade;
try {
- facade = DerivedUnitFacade.NewInstance(
- (DerivedUnit) entity,
- PreferencesUtil.getDerivedUnitConfigurator());
+ if(((SpecimenOrObservationBase) entity).isInstanceOf(DerivedUnit.class)){
+ facade = DerivedUnitFacade.NewInstance(
+ HibernateProxyHelper.deproxy(entity, DerivedUnit.class),
+ PreferencesUtil.getDerivedUnitConfigurator());
+ }
+ else {
+ facade = DerivedUnitFacade.NewInstance(SpecimenOrObservationType.FieldUnit,
+ HibernateProxyHelper.deproxy(entity, FieldUnit.class),
+ PreferencesUtil.getDerivedUnitConfigurator());
+ }
+
} catch (DerivedUnitFacadeNotSupportedException e) {
// we should never get here
throw new IllegalStateException();
selectionElement.getConversationHolder(), facade));
addPage(new FieldUnitWizardPage(formFactory,
selectionElement.getConversationHolder(), facade));
- addPage(new DerivedUnitBaseWizardPage(formFactory,
- selectionElement.getConversationHolder(), facade));
+ if(facade.innerDerivedUnit()!=null){
+ addPage(new DerivedUnitBaseWizardPage(formFactory,
+ selectionElement.getConversationHolder(), facade));
+ }
} else if (entity instanceof Collection) {
addPage(new CollectionWizardPage(formFactory,
selectionElement.getConversationHolder(),
}
@Override
- public List<CdmBase> getRootEntities() {
+ public List<? extends CdmBase> getRootEntities() {
return Arrays.asList((CdmBase)getViewer().getInput());
}
package eu.etaxonomy.taxeditor.view.derivateSearch;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@Override
public Object[] getElements(Object inputElement) {
rootNodes = new ArrayList<TreeNode>();
- if(inputElement instanceof Set){
- for (Object o: (Set)inputElement) {
+ if(inputElement instanceof Collection){
+ for (Object o: (Collection)inputElement) {
if(o instanceof SpecimenOrObservationBase){
SpecimenOrObservationBase<?> rootElement = (SpecimenOrObservationBase<?>)o;
if(rootElement!=null){
*/
package eu.etaxonomy.taxeditor.view.derivateSearch;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import org.hibernate.LazyInitializationException;
import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
+import eu.etaxonomy.cdm.api.service.IOccurrenceService;
+import eu.etaxonomy.cdm.api.service.molecular.ISequenceService;
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
import eu.etaxonomy.cdm.model.common.CdmBase;
import eu.etaxonomy.cdm.model.common.DefinedTerm;
import eu.etaxonomy.cdm.model.molecular.DnaSample;
import eu.etaxonomy.cdm.model.molecular.Sequence;
import eu.etaxonomy.cdm.model.molecular.SingleRead;
+import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation;
+import eu.etaxonomy.cdm.model.name.TaxonNameBase;
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
import eu.etaxonomy.cdm.model.occurrence.GatheringEvent;
private static final String NO_SAMPLE_DESIGNATION = "[no sample designation]";
- private Set<SingleRead> multiLinkSingleReads;
+ private static Set<SingleRead> multiLinkSingleReads;
+
+ private static Map<DerivedUnit, List<SpecimenTypeDesignation>> typeDesignations;
private ConversationHolder conversation;
derivate = node.getValue();
}
- conversation.bind();
+ if(conversation!=null){
+ conversation.bind();
+ }
final String emptyString = "";
final String separator = " ";
else if(derivate instanceof DerivedUnit){
DerivedUnit derivedUnit = (DerivedUnit)derivate;
if(derivedUnit.getRecordBasis()==SpecimenOrObservationType.PreservedSpecimen){
+ //check for type designation
+ if(typeDesignations.get(derivedUnit)==null){
+ for (SpecimenTypeDesignation specimenTypeDesignation : CdmStore.getService(IOccurrenceService.class).listTypeDesignations(derivedUnit, null, null, null, null)) {
+ addTypeDesignation(derivedUnit, specimenTypeDesignation);
+ }
+ }
//java.util.Collection<FieldUnit> fieldUnits = CdmStore.getService(IOccurrenceService.class).getFieldUnits(derivedUnit.getUuid());
//TODO : This is not generic anymore for performance reasons
Set<SpecimenOrObservationBase> originals = derivedUnit.getOriginals();
}
String mostSignificantIdentifier = derivedUnit.getMostSignificantIdentifier();
label += mostSignificantIdentifier!=null?mostSignificantIdentifier+separator:emptyString;
+ //type designation extension
+ List<SpecimenTypeDesignation> list = typeDesignations.get(derivedUnit);
+ if(list!=null){
+ for (SpecimenTypeDesignation specimenTypeDesignation : list) {
+ label += "("+specimenTypeDesignation.getTypeStatus()+" of ";
+ for (TaxonNameBase taxonNameBase : specimenTypeDesignation.getTypifiedNames()) {
+ label += taxonNameBase+separator;
+ }
+ if(label.endsWith(separator)){
+ label = label.substring(0, label.length()-separator.length());
+ }
+ label += ")";
+ }
+ }
}
else if(derivedUnit.getRecordBasis()==SpecimenOrObservationType.TissueSample){
//TissueSample should only be created by using it's own class
return label;
}
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ColumnLabelProvider#getImage(java.lang.Object)
- */
@Override
public Image getImage(Object element) {
if(element instanceof TreeNode){
}
else if(cdmBase.isInstanceOf(SingleRead.class)){
- if(multiLinkSingleReads.contains(element)){
+ if(multiLinkSingleReads!=null && multiLinkSingleReads.contains(element)){
return ImageResources.getImage(ImageResources.SINGLE_READ_DERIVATE_MULTILINK);
}
else{
}
/**
- * @param multiLinkSingleReads2
+ * Refreshes cached label extensions
+ * @param multiLinkSingleReads
*/
- public void setMultiLinkSingleReads(Set<SingleRead> multiLinkSingleReads) {
- this.multiLinkSingleReads = multiLinkSingleReads;
+ public void refresh() {
+ DerivateLabelProvider.multiLinkSingleReads = new HashSet<SingleRead>();
+ for(Entry<SingleRead, Collection<Sequence>> entry:CdmStore.getService(ISequenceService.class).getSingleReadSequencesMap().entrySet()){
+ if(entry.getValue().size()>1){
+ multiLinkSingleReads.add(entry.getKey());
+ }
+ }
+ DerivateLabelProvider.typeDesignations = new HashMap<DerivedUnit, List<SpecimenTypeDesignation>>();
+ }
+
+ private static void addTypeDesignation(DerivedUnit derivedUnit, SpecimenTypeDesignation typeDesignation){
+ List<SpecimenTypeDesignation> list = typeDesignations.get(derivedUnit);
+ if(list==null){
+ list = new ArrayList<SpecimenTypeDesignation>();
+ }
+ list.add(typeDesignation);
+ typeDesignations.put(derivedUnit, list);
+ }
+
+ public static Set<SingleRead> getMultiLinkSingleReads() {
+ return multiLinkSingleReads;
}
}
+++ /dev/null
-// $Id$
-/**
- * Copyright (C) 2013 EDIT
- * European Distributed Institute of Taxonomy
- * http://www.e-taxonomy.eu
- *
- * 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.view.derivateSearch;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.part.ViewPart;
-
-import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
-import eu.etaxonomy.cdm.model.common.CdmBase;
-import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
-import eu.etaxonomy.taxeditor.model.IContextListener;
-import eu.etaxonomy.taxeditor.session.ICdmEntitySession;
-import eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled;
-import eu.etaxonomy.taxeditor.store.CdmStore;
-
-/**
- * This view allows to search for and filter {@link SpecimenOrObservationBase}s and display
- * the results in a list. The results can be selected and opened in an editor.
- */
-public class DerivateSearchView extends ViewPart implements IContextListener, ICdmEntitySessionEnabled {
-
- public static final String ID = "eu.etaxonomy.taxeditor.view.derivateSearch.DerivateSearchView";
- private DerivateSearchCompositeController derivateSearchCompositeController;
- private ConversationHolder conversationHolder;
- private ICdmEntitySession cdmEntitySession;
-
- /**
- * Constructs a new DerivateSearchView and registers it to listen to context changes
- */
- public DerivateSearchView() {
- CdmStore.getContextManager().addContextListener(this);
- }
-
- @Override
- public void createPartControl(Composite parent) {
-
- derivateSearchCompositeController = new DerivateSearchCompositeController(parent, this);
- getSite().setSelectionProvider(derivateSearchCompositeController.getResultViewer());
- derivateSearchCompositeController.setEnabled(CdmStore.isActive());
-
- //create context menu
- MenuManager menuManager = new MenuManager();
- getSite().registerContextMenu(menuManager, derivateSearchCompositeController.getResultViewer());
- Control control = derivateSearchCompositeController.getResultViewer().getControl();
- Menu menu = menuManager.createContextMenu(control);
- control.setMenu(menu);
- }
-
- @Override
- public void setFocus() {
- derivateSearchCompositeController.setFocus();
- //make sure to bind again if maybe in another view the conversation was unbound
- if(getConversationHolder()!=null && !getConversationHolder().isClosed() && !getConversationHolder().isBound()){
- getConversationHolder().bind();
- }
- if(getCdmEntitySession() != null) {
- getCdmEntitySession().bind();
- }
- }
-
- @Override
- public void contextAboutToStop(IMemento memento, IProgressMonitor monitor) {
- }
-
- @Override
- public void contextStop(IMemento memento, IProgressMonitor monitor) {
- derivateSearchCompositeController.setEnabled(false);
- derivateSearchCompositeController.reset();
- }
-
- @Override
- public void contextStart(IMemento memento, IProgressMonitor monitor) {
- derivateSearchCompositeController.setEnabled(true);
- }
-
- @Override
- public void contextRefresh(IProgressMonitor monitor) {
- initConversation();
- initSession();
- }
-
- private void initSession() {
- if(CdmStore.isActive()) {
- cdmEntitySession = CdmStore.getCurrentSessionManager().newSession(this, true);
- }
- }
-
- private void initConversation(){
- if(conversationHolder==null){
- conversationHolder = CdmStore.createConversation();
- derivateSearchCompositeController.setConversation(conversationHolder);
- }
- }
-
- @Override
- public void workbenchShutdown(IMemento memento, IProgressMonitor monitor) {
- }
-
- public ConversationHolder getConversationHolder() {
- if(CdmStore.isActive() && conversationHolder==null){
- initConversation();
- }
- return conversationHolder;
- }
-
-
- @Override
- public void dispose() {
- if(conversationHolder!=null){
- conversationHolder.close();
- }
-
- if(cdmEntitySession != null) {
- cdmEntitySession.dispose();
- }
- super.dispose();
- }
-
-
- /* (non-Javadoc)
- * @see eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled#getCdmEntitySession()
- */
- @Override
- public ICdmEntitySession getCdmEntitySession() {
- initSession();
- return cdmEntitySession;
- }
-
- /* (non-Javadoc)
- * @see eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled#getRootEntities()
- */
- @Override
- public <T extends CdmBase> Collection<T> getRootEntities() {
- // TODO Auto-generated method stub
- return null;
- }
-
- /* (non-Javadoc)
- * @see eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled#getPropertyPathsMap()
- */
- @Override
- public Map<Object, List<String>> getPropertyPathsMap() {
- // TODO Auto-generated method stub
- return null;
- }
-}
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPart;
+import eu.etaxonomy.cdm.api.conversation.IConversationEnabled;
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
import eu.etaxonomy.cdm.model.common.CdmBase;
import eu.etaxonomy.cdm.model.description.Feature;
@Override
protected void selectionChanged_internal(IWorkbenchPart part, ISelection selection){
- if(AbstractUtility.getActiveEditor() == null){
+ if(AbstractUtility.getActiveEditor() == null && !(AbstractUtility.getActivePart() instanceof IConversationEnabled)){
showEmptyPage();
return;
}
import eu.etaxonomy.taxeditor.ui.section.occurrence.FieldUnitDetailSection;
import eu.etaxonomy.taxeditor.ui.section.occurrence.FieldUnitGeneralDetailSection;
import eu.etaxonomy.taxeditor.ui.section.occurrence.GatheringEventDetailSection;
+import eu.etaxonomy.taxeditor.ui.section.occurrence.association.DerivedUnitTypeDesignationSection;
import eu.etaxonomy.taxeditor.ui.section.occurrence.association.TaxonAssociationDetailSection;
import eu.etaxonomy.taxeditor.ui.section.occurrence.dna.DnaQualityDetailSection;
import eu.etaxonomy.taxeditor.ui.section.occurrence.dna.DnaSampleGeneralDetailSection;
addPart(determinationDetailSection);
}
+ formFactory.createHorizontalSeparator(parent, SWT.BORDER);
+ DerivedUnitTypeDesignationSection derivedUnitTypeDesignationSection = formFactory.createDerivedUnitTypeDesignationSection(getConversationHolder(), parent, this, ExpandableComposite.TWISTIE);
+ addPart(derivedUnitTypeDesignationSection);
+
}
private void createFieldUnitSection(RootElement parent) {
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry including="**/*.java" kind="src" path="src/test/java"/>
<classpathentry excluding="**/*.java" kind="src" path="src/test/resources"/>
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
+org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.source=1.6
+org.eclipse.jdt.core.compiler.source=1.7
Bundle-Version: 3.12.0.qualifier
Bundle-ActivationPolicy: lazy
Bundle-Vendor: EDIT
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
org.eclipse.ui.ide,
org.junit;bundle-version="4.8.2",
+ eu.etaxonomy.taxeditor.webapp,
eu.etaxonomy.taxeditor.cdmlib,
eu.etaxonomy.taxeditor.bulkeditor,
eu.etaxonomy.taxeditor.editor,
org.apache.log4j,
org.hamcrest,
org.eclipse.swtbot.eclipse.core,
- org.eclipse.swtbot.eclipse.finder
+ org.eclipse.swtbot.eclipse.finder,
+ eu.etaxonomy.taxeditor.webapp;bundle-version="3.12.0"
Eclipse-RegisterBuddy: org.apache.log4j, org.eclipse.swtbot.swt.finder
Bundle-ClassPath: .,
lib/byte-buddy-0.5.1.jar,
lib/unitils-dbmaintainer-3.4.2.jar,
lib/unitils-dbunit-3.4.2.jar,
lib/unitils-spring-3.4.2.jar,
- lib/dbunit-2.4.9.jar
\ No newline at end of file
+ lib/dbunit-2.4.9.jar
*/
package eu.etaxonomy.taxeditor.httpinvoker;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
import java.lang.reflect.Field;
-import java.net.URL;
import java.util.Map;
-import java.util.Properties;
import net.sf.ehcache.CacheManager;
import org.apache.log4j.Logger;
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.Platform;
-import org.junit.Assert;
import org.junit.BeforeClass;
-import org.osgi.framework.Bundle;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.core.io.Resource;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import eu.etaxonomy.taxeditor.remoting.cache.CdmTransientEntityCacher;
import eu.etaxonomy.taxeditor.remoting.source.CdmPersistentRemoteSource;
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
-import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSourceException;
import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
import eu.etaxonomy.taxeditor.session.CdmEntitySession;
import eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled;
public abstract class BaseRemotingTest extends ThreadedTest {
private static final Logger logger = Logger.getLogger(BaseRemotingTest.class);
-
- public static final Resource SERVER_PROPERTIES_FILE =
- new ClassPathResource("server.properties");
-
private static ICdmRemoteSource cdmRemoteSource;
private static CdmPersistentRemoteSource remotePersistentSource;
-
- public static boolean useManagedServer = true;
-
-
protected static ICdmEntitySessionManager cdmEntitySessionManager;
- private final static String DEFAULT_USER = "admin";
- private final static String DEFAULT_PASSWORD = "00000";
-
- private static String userHomeKey = "user.home";
-
- private static String user = DEFAULT_USER;
- private static String password = DEFAULT_PASSWORD;
-
-
- protected static CDMServer cdmServer;
-
@BeforeClass
public static void initializeBaseRemotingTest() {
DatabaseUnitils.disableConstraints();
try {
- String userHomeDirPath;
- Bundle bundle = Platform.getBundle("eu.etaxonomy.taxeditor.test");
-
- URL userHomeDirURL = bundle.getEntry("src/test/resources");
- File userHomeDir = new File(FileLocator.resolve(userHomeDirURL).toURI());
- userHomeDirPath = userHomeDir.getAbsolutePath();
-
- URL serverPropertiesURL = bundle.getEntry("src/test/resources/server.properties");
- File serverPropertiesFile = new File(FileLocator.resolve(serverPropertiesURL).toURI());
- InputStream inputStream = new FileInputStream(serverPropertiesFile);
-
- Properties prop = new Properties();
- if (inputStream != null) {
- prop.load(inputStream);
- inputStream.close();
- }
-
- logger.info("Setting user.home to " + userHomeDirPath);
- System.setProperty(userHomeKey, userHomeDirPath);
-
-
- cdmServer = new CDMServer("cdmTest", serverPropertiesURL);
-
-
- if(prop.getProperty("user") != null) {
- user = prop.getProperty("user");
- }
-
- if(prop.getProperty("password") != null) {
- password = prop.getProperty("password");
- }
-
- initializeController(cdmServer.getName(),
- cdmServer.getHost(),
- cdmServer.getPort(),
- cdmServer.getContextPath(),
+ initializeController(sourceName,
+ host,
+ httpPort,
+ contextPath,
NomenclaturalCode.ICNAFP,
user,
password);
null);
CdmApplicationState.setCurrentAppConfig(remoteApplicationController);
CdmApplicationState.setCdmServiceCacher(new CdmServiceCacher());
- try {
- remotePersistentSource = CdmPersistentRemoteSource.NewInstance(sourceName);
- } catch (CdmRemoteSourceException e) {
- Assert.fail("Default Remote Persistent Source failed to load. Reason : " + e.getMessage());
- }
+
cdmEntitySessionManager = getRemoteApplicationController().getCdmEntitySessionManager();
CdmApplicationState.setCurrentDataChangeService(new CdmDataChangeService());
+++ /dev/null
-// $Id$
-/**
- * Copyright (C) 2014 EDIT
- * European Distributed Institute of Taxonomy
- * http://www.e-taxonomy.eu
- *
- * 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.httpinvoker;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.util.Properties;
-
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanException;
-import javax.management.MBeanServerConnection;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-import javax.management.remote.JMXConnector;
-import javax.management.remote.JMXConnectorFactory;
-import javax.management.remote.JMXServiceURL;
-import javax.sql.DataSource;
-
-import org.apache.log4j.Logger;
-import org.eclipse.core.runtime.FileLocator;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.core.io.Resource;
-import org.unitils.database.annotations.TestDataSource;
-
-import eu.etaxonomy.cdm.database.CdmPersistentDataSource;
-import eu.etaxonomy.cdm.database.ICdmDataSource;
-import eu.etaxonomy.taxeditor.remoting.server.CDMServerException;
-import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSourceBase;
-
-/**
- *
- * (Singleton) Server instance which manages a compatible cdmlib-webapp-war.
- * This is done by launching a jetty instance (using jetty-runner) as an
- * executed process. The choice of the external process over a more
- * preferable 'embedded jetty' instance is due to problems arising from the
- * class loading of classes (e.g. from hibernate core) which are needed
- * for both the webapp as well as the remoting client.
- *
- * @author cmathew
- * @date 23 Sep 2014
- *
- */
-
-public class CDMServer {
-
- public static final Logger logger = Logger.getLogger(CDMServer.class);
-
- @TestDataSource
- protected DataSource dataSource;
-
- private final String name = "default";
- private final String host = "127.0.0.1";
- private int httpPort = 9090;
- private int stopPort = 9191;
- private String stopKey = "jetty-cdm-server";
- private final String contextPath = "";
-
- public static final Resource DEFAULT_CDM_WEBAPP_RESOURCE =
- new ClassPathResource("/etc/jetty/cdmlib-remote-webapp.war");
-
- public static final Resource DEFAULT_DATASOURCE_FILE =
- new ClassPathResource("datasources.xml");
-
- public static final Resource DEFAULT_JETTY_RUNNER_RESOURCE =
- new ClassPathResource("/etc/jetty/jetty-runner-9.2.3.v20140905.jar");
-
- public static final Resource DEFAULT_JETTY_RESOURCE =
- new ClassPathResource("/etc/jetty/start-9.2.3.v20140905.jar");
-
- private static CDMServer cdmServer = null;
- private static CDMServerException cdmse = null;
-
- private boolean serverAlreadyRunning = false;
-
- private File dataSourcesFile;
- private final String dataSourceName;
-
- public CDMServer(String dataSourceName, URL serverPropertiesURL) throws CDMServerException {
- this.dataSourceName = dataSourceName;
- Properties prop = new Properties();
-
- try {
- File serverPropertiesFile = new File(FileLocator.resolve(serverPropertiesURL).toURI());
- InputStream inputStream = new FileInputStream(serverPropertiesFile);
-
- prop.load(inputStream);
- inputStream.close();
-
- } catch (FileNotFoundException e) {
- throw new CDMServerException(e);
- } catch (URISyntaxException e) {
- throw new CDMServerException(e);
- } catch (IOException e) {
- throw new CDMServerException(e);
- }
-
-
-
- if(prop.getProperty("httpPort") != null) {
- setHttpPort(Integer.valueOf(prop.getProperty("httpPort")));
- }
-
- if(prop.getProperty("stopPort") != null) {
- setStopPort(Integer.valueOf(prop.getProperty("stopPort")));
- }
-
- if(prop.getProperty("stopKey") != null) {
- setStopKey(prop.getProperty("stopKey"));
- }
-
- }
-
-
-
- public String getName() {
- return name;
- }
-
- public String getHost() {
- return host;
- }
-
- public int getPort() {
- return httpPort;
- }
-
- public String getContextPath() {
- return contextPath;
- }
-
- public void setHttpPort(int port) {
- this.httpPort = port;
- }
-
- public void setStopPort(int stopPort) {
- this.stopPort = stopPort;
- }
-
- public void setStopKey(String stopKey) {
- this.stopKey = stopKey;
- }
-
-
- public static boolean isRunningInEclipse() {
- return (System.getProperty("sun.java.command") != null &&
- System.getProperty("sun.java.command").startsWith("org.eclipse.jdt.internal.junit.runner.RemoteTestRunner"));
- }
-
- private String getVMArgs() throws IOException {
- StringBuilder sb = new StringBuilder();
- sb.append(" -Dspring.profiles.active=remoting");
- sb.append(" -Dcdm.beanDefinitionFile=" + DEFAULT_DATASOURCE_FILE.getFile().getAbsolutePath());
- sb.append(" -Dcdm.datasource=cdmTest");
- return sb.toString();
- }
-
- private String getStartServerArgs() throws IOException {
- StringBuilder sb = new StringBuilder();
- sb.append(" --port " + httpPort);
- return sb.toString();
- }
-
- private String getStopServerSettings() {
- StringBuilder sb = new StringBuilder();
- sb.append(" --stop-port ");
- sb.append(stopPort);
- sb.append(" --stop-key ");
- sb.append(stopKey);
- return sb.toString();
- }
-
- private String getStopServerArgs() {
- StringBuilder sb = new StringBuilder();
- sb.append(" STOP.PORT=");
- sb.append(stopPort);
- sb.append(" STOP.KEY=");
- sb.append(stopKey);
- return sb.toString();
- }
-
-
- public void start() throws CDMServerException {
-
- /**
- * First check if the CDM server responds to a service request, which implies that
- * the server has started properly. If no response is received then check if the
- * server is listening on specific host / port, which implies that the server
- * has started but incorrectly, in which case we try to force stop it (if we can)
- * and start a new server.
- */
- if(isStarted(1)) {
- logger.info("[CDM-Server] Server already running @ " + host + ":" + httpPort );
- serverAlreadyRunning = true;
- return;
- }
-
- Thread t = new Thread() {
- @Override
- public void run() {
-
- StringBuffer output = new StringBuffer();
- try{
- Process p;
- String command = "java "
- + getVMArgs()
- + " -jar "
- + DEFAULT_JETTY_RUNNER_RESOURCE.getFile().getAbsolutePath()
- + getStartServerArgs()
- + getStopServerSettings()
- + " "
- + DEFAULT_CDM_WEBAPP_RESOURCE.getFile().getAbsolutePath();
- logger.info("[CDM-Server] Starting server with Command : " + command);
- p = Runtime.getRuntime().exec(command);
-
- BufferedReader inpReader =
- new BufferedReader(new InputStreamReader(p.getInputStream()));
-
- BufferedReader errReader =
- new BufferedReader(new InputStreamReader(p.getErrorStream()));
-
- String line = "";
- while ((line = inpReader.readLine())!= null) {
- logger.info("[CDM-Server Start] : " + line);
- }
-
- while ((line = errReader.readLine())!= null) {
- logger.info("[CDM-Server Start] : " + line);
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- cdmse = new CDMServerException(e);
- }
- }
- };
-
- t.setDaemon(true);
- cdmse = null;
- t.start();
-
- if(isStarted(50)) {
- logger.info("[CDM-Server] Server running @ " + host + ":" + httpPort );
- } else {
- logger.info("[CDM-Server] Server not started within given interval");
- // making sure to kill server if it is not started correctly
- try {
- stop(true);
- } catch (Exception e) {
- throw new CDMServerException("CDM Server could not be stopped : " + e.getMessage());
- }
- throw new CDMServerException("CDM Server not started : ");
- }
-
- }
-
-
- public boolean isStarted(int checkingIntervals) throws CDMServerException {
- CdmRemoteSourceBase crsb = new CdmRemoteSourceBase("local-cdm-server",
- host,
- httpPort,
- contextPath,
- null);
- int intervalsCount = 0;
- do {
- try {
- if(cdmse != null) {
- return false;
- }
- boolean check = crsb.checkConnection();
- if(check) {
- logger.info("[CDM-Server] Running @ " + host + ":" + httpPort );
- return true;
- }
- } catch (Exception e) {
-
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException ie) {
- throw new CDMServerException("Error checking CDM Server status", ie);
- }
- intervalsCount++;
- } while (intervalsCount < checkingIntervals);
- return false;
- }
-
- public void stop() throws Exception {
- stop(false);
- }
-
- public void stop(boolean force) throws Exception {
-
- if(!force) {
- if(!cdmServer.isStarted(1)) {
- logger.info("[CDM-Server] Server already stopped @ " + host + ":" + httpPort );
- return;
- }
- }
-
- if(serverAlreadyRunning) {
- return;
- }
- Thread t = new Thread() {
- @Override
- public void run() {
- StringBuffer output = new StringBuffer();
- try{
- Process p;
- String command = "java -jar " + DEFAULT_JETTY_RESOURCE.getFile().getAbsolutePath()
- + getStopServerArgs() + " --stop ";
- logger.info("[CDM-Server] Stop Command : " + command);
- p = Runtime.getRuntime().exec(command);
-
- BufferedReader inpReader =
- new BufferedReader(new InputStreamReader(p.getInputStream()));
-
- BufferedReader errReader =
- new BufferedReader(new InputStreamReader(p.getErrorStream()));
-
- String line = "";
- while ((line = inpReader.readLine())!= null) {
- logger.info("[CDM-Server Stop] : " + line);
- }
-
- while ((line = errReader.readLine())!= null) {
- logger.info("[CDM-Server Stop] : " + line);
- }
- logger.info("CDM-Server Stopped : ");
- } catch (Exception e) {
- logger.info("[CDM-Server] Could not stop @ " + host + ":" + httpPort + ". Please kill it manually");
-
- }
-
- }
- };
-
- t.setDaemon(true);
- t.start();
-
- }
-
- public static void stopServerViaJMX(int jmxPort) throws CDMServerException {
- String JMX_URL = "service:jmx:rmi:///jndi/rmi://localhost:" + jmxPort + "/jmxrmi";
- logger.warn("Shutting down Jetty instance ... ");
-
- try {
- JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(JMX_URL), null);
- connector.connect(null);
- MBeanServerConnection connection = connector.getMBeanServerConnection();
- ObjectName objectName = new ObjectName("org.eclipse.jetty.server:type=server,id=0");
- connection.invoke(objectName, "stop", null, null);
- logger.warn("Shutdown command sent");
- } catch (InstanceNotFoundException e) {
- throw new CDMServerException(e);
- } catch (MBeanException e) {
- throw new CDMServerException(e);
- } catch (ReflectionException e) {
- throw new CDMServerException(e);
- } catch (IOException e) {
- throw new CDMServerException(e);
- } catch (MalformedObjectNameException e) {
- throw new CDMServerException(e);
- }
- }
-
- public void convertEditorToServerConfig() {
- String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> " + System.lineSeparator() +
- "<beans xmlns=\"http://www.springframework.org/schema/beans\"" + System.lineSeparator() +
- "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + System.lineSeparator() +
- "xmlns:tx=\"http://www.springframework.org/schema/tx\"" + System.lineSeparator() +
- "xmlns:context=\"http://www.springframework.org/schema/context\"" + System.lineSeparator() +
- "xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" + System.lineSeparator() +
- "http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" + System.lineSeparator() +
- "http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" + System.lineSeparator() +
- ">" + System.lineSeparator() +
- "<bean id=\"dataSourceProperties\" class=\"eu.etaxonomy.cdm.remote.config.DataSourceProperties\">" + System.lineSeparator() +
- " <property name=\"propsMap\">" + System.lineSeparator() +
- " <map/>" + System.lineSeparator() +
- " </property>" + System.lineSeparator() +
- "</bean>";
-
- for(ICdmDataSource dataSource : CdmPersistentDataSource.getAllDataSources()) {
-
- }
- }
-}
+++ /dev/null
-/**
- * Copyright (C) 2014 EDIT
- * European Distributed Institute of Taxonomy
- * http://www.e-taxonomy.eu
- *
- * 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.httpinvoker;
-
-
-import java.util.Map;
-
-import org.apache.log4j.Logger;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import eu.etaxonomy.cdm.config.CdmPersistentSourceUtils;
-import eu.etaxonomy.cdm.config.CdmSourceException;
-import eu.etaxonomy.cdm.model.metadata.CdmMetaData.MetaDataPropertyName;
-import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
-import eu.etaxonomy.taxeditor.remoting.source.CdmPersistentRemoteSource;
-import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
-import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSourceException;
-import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
-
-/**
- * Class to test the cdm persistent source functionality, including
- * initialising / saving / updating and deleting
- *
- * Corresponding test sources settings can be found at
- * /src/text/resources/eu.etaxonomy.cdm/cdm.datasources.xml
- *
- */
-public class CdmPersistentRemoteSourceTest extends BaseRemotingTest {
- private static final Logger logger = Logger.getLogger(CdmPersistentRemoteSourceTest.class);
-
- private CdmPersistentRemoteSource remotePersistentSource;
-
- @BeforeClass
- public static void initialize() {
- }
-
- @Test
- public void whenLoadingExistingCompleteRemoteSourceThenLoadIsSuccessful() {
-
- remotePersistentSource = getCdmPersistentRemoteSource();
-
- String expectedServer = "127.0.0.1";
- String expectedPort = "9090";
- String expectedContextPath = "";
- logger.info("Default remote source server : " + remotePersistentSource.getServer());
- Assert.assertTrue("Default server should be " + expectedServer,
- expectedServer.equals(remotePersistentSource.getServer()));
-
- logger.info("Default remote source port : " + remotePersistentSource.getPort());
- Assert.assertTrue("Default port should be 9090",
- expectedPort.equals(String.valueOf(remotePersistentSource.getPort())));
-
- logger.info("Default remote source context path : " + remotePersistentSource.getContextPath());
- Assert.assertTrue("Default remote source context path should be " + expectedContextPath,
- expectedContextPath.equals(remotePersistentSource.getContextPath()));
-
- logger.info("Default remote source nomenclatural code : " + remotePersistentSource.getNomenclaturalCode().toString());
- Assert.assertTrue("Default NomenclaturalCode should be ICNAFP",
- NomenclaturalCode.ICNAFP.equals(remotePersistentSource.getNomenclaturalCode()));
- }
-
-
-
-
- @Test
- public void whenConnectingToAnActiveServerThenConnectSuccessfully() {
- // check if active server throws the right exception
-
- remotePersistentSource = getCdmPersistentRemoteSource();
-
- String dbSchemaVersion = "";
- try {
- dbSchemaVersion = remotePersistentSource.getDbSchemaVersion();
- } catch (CdmSourceException e) {
- Assert.fail("getDbSchemaVersion() on active cdm server should not have thrown CdmSourceException");
- }
- logger.info("dbSchemaVersion is " + dbSchemaVersion);
-
-
- boolean isDbEmpty = false;
- try {
- isDbEmpty = remotePersistentSource.isDbEmpty();
- } catch (CdmSourceException e) {
- Assert.fail("isDbEmpty() on active cdm server should not have thrown CdmSourceException");
- }
- Assert.assertFalse(isDbEmpty);
-
-
- boolean check = false;
- try {
- check = remotePersistentSource.checkConnection();
- } catch (CdmSourceException e) {
- Assert.fail("checkConnection() on active cdm server should not have thrown CdmSourceException");
- }
- Assert.assertTrue(check);
-
-
- }
-
- @Test
- public void whenRequestingMetadatFromRemoteSourceThenMetaDataIsRetrieved() {
- try {
- remotePersistentSource = getCdmPersistentRemoteSource();
- Map<MetaDataPropertyName, String> cdmMetaDataMap = remotePersistentSource.getMetaDataMap();
- for(MetaDataPropertyName mdpn : cdmMetaDataMap.keySet()) {
- String value = cdmMetaDataMap.get(mdpn);
- logger.info("MetaData Property " + mdpn.name() + " has value " + value);
- Assert.assertNotNull("Meta Data Value for property for " + mdpn.name() + " should not be null", value);
- }
- } catch (CdmSourceException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- @Test
- public void whenLoadingNonExistingRemoteSourceThenThrowException() {
- try {
- remotePersistentSource = CdmPersistentRemoteSource.NewInstance("nonExistingSource");
- Assert.fail("Initialising a non-existing remote source should throw an exception");
- } catch (CdmRemoteSourceException e) {
- logger.info(e.getMessage());
- }
- }
-
- @Test
- public void whenLoadingExistingIncompleteRemoteSourceThenThrowException() {
- try {
- remotePersistentSource = CdmPersistentRemoteSource.NewInstance("incomplete");
- Assert.fail("Initialising an incomplete remote source should throw an exception");
- } catch (CdmRemoteSourceException e) {
- //Assert.assertThat(e.getMessage(), containsString("Required property '" + CdmSourceProperties.SERVER.toString() + "' is missing"));
- }
- }
-
- @Test
- public void whenSavingUpdatingDeletingNewCompleteRemoteSourceThenSaveUpdateDeleteIsSuccessful() {
- String strRemoteSource = "local";
- Assert.assertFalse("New remote source '" + strRemoteSource + "' should not yet exist in source settings file",
- CdmPersistentRemoteSource.exists(strRemoteSource));
- try {
- ICdmRemoteSource remoteSource =
- CdmRemoteSource.NewInstance(strRemoteSource,
- "127.0.0.1",
- 8080,
- "col",
- NomenclaturalCode.ICNAFP);
- remotePersistentSource = CdmPersistentRemoteSource.save(strRemoteSource,remoteSource);
-
- logger.info("Server : " + remotePersistentSource.getServer());
- Assert.assertTrue("Server value should be equal",
- remoteSource.getServer().equals(remotePersistentSource.getServer()));
-
- logger.info("Port : " + remotePersistentSource.getPort());
- Assert.assertTrue("Port value should be equal",
- remoteSource.getPort() == remotePersistentSource.getPort());
-
- logger.info("Context Path : " + remotePersistentSource.getContextPath());
- Assert.assertTrue("Context Path value should be equal",
- remoteSource.getContextPath().equals(remotePersistentSource.getContextPath()));
-
- logger.info("Nomenclatural Code : " + remotePersistentSource.getNomenclaturalCode().name());
- Assert.assertTrue("Nomenclatural Code value should be equal",
- remoteSource.getNomenclaturalCode().name().equals(remotePersistentSource.getNomenclaturalCode().name()));
-
- Assert.assertTrue("New remote source '" + strRemoteSource + "' should be saved in source settings file",
- CdmPersistentRemoteSource.exists(strRemoteSource));
-
- remoteSource = CdmRemoteSource.NewInstance(strRemoteSource,
- "127.0.0.55",
- 9090,
- "cyprus",
- NomenclaturalCode.ICNB);
- remotePersistentSource = CdmPersistentRemoteSource.update(strRemoteSource,remoteSource);
-
- logger.info("Server : " + remotePersistentSource.getServer());
- Assert.assertTrue("Server value should be equal",
- remoteSource.getServer().equals(remotePersistentSource.getServer()));
-
- logger.info("Port : " + remotePersistentSource.getPort());
- Assert.assertTrue("Port value should be equal",
- remoteSource.getPort() == remotePersistentSource.getPort());
-
- logger.info("Context Path : " + remotePersistentSource.getContextPath());
- Assert.assertTrue("Context Path value should be equal",
- remoteSource.getContextPath().equals(remotePersistentSource.getContextPath()));
-
- logger.info("Nomenclatural Code : " + remotePersistentSource.getNomenclaturalCode().name());
- Assert.assertTrue("Nomenclatural Code value should be equal",
- remoteSource.getNomenclaturalCode().name().equals(remotePersistentSource.getNomenclaturalCode().name()));
-
- Assert.assertTrue("New remote source '" + strRemoteSource + "' should be saved in source settings file",
- CdmPersistentRemoteSource.exists(strRemoteSource));
-
- CdmPersistentSourceUtils.delete(remotePersistentSource);
-
- Assert.assertFalse("New remote source '" + strRemoteSource + "' should no longer exist in source settings file",
- CdmPersistentRemoteSource.exists(strRemoteSource));
-
- } catch (CdmRemoteSourceException e) {
- Assert.fail("Saving a new complete remote source should not throw an exception");
- logger.info(e.getMessage());
- }
- }
-
-
-
-}
public void whenConnectingToInactiveServerThenFailToConnect() {
// check if non-active server throws the right exception
- CdmRemoteSource inactiveCrs = CdmRemoteSource.NewInstance(cdmServer.getName(),
- cdmServer.getHost(),
+ CdmRemoteSource inactiveCrs = CdmRemoteSource.NewInstance(sourceName,
+ host,
808080,
- cdmServer.getContextPath(),
+ contextPath,
NomenclaturalCode.ICNAFP);
try {
inactiveCrs.getDbSchemaVersion();
@Test
public void whenConnectingToAnActiveServerThenConnectSuccessfully() {
// check if active server throws the right exception
- CdmRemoteSource activeCrs = CdmRemoteSource.NewInstance(cdmServer.getName(),
- cdmServer.getHost(),
- cdmServer.getPort(),
- cdmServer.getContextPath(),
+ CdmRemoteSource activeCrs = CdmRemoteSource.NewInstance(sourceName,
+ host,
+ httpPort,
+ contextPath,
NomenclaturalCode.ICNAFP);
String dbSchemaVersion = "";
try {
*/
package eu.etaxonomy.taxeditor.httpinvoker;
+import java.io.File;
+import java.io.IOException;
+import java.net.URISyntaxException;
import java.net.URL;
import org.apache.log4j.Logger;
+import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.junit.Assert;
-import org.junit.Ignore;
import org.junit.Test;
import org.osgi.framework.Bundle;
-import org.unitils.UnitilsJUnit4;
-import eu.etaxonomy.taxeditor.remoting.server.CDMServerException;
+import eu.etaxonomy.taxeditor.remoting.server.CDMServerUtils;
+import eu.etaxonomy.taxeditor.webapp.CDMEmbeddedServerException;
+import eu.etaxonomy.taxeditor.webapp.CDMServer;
+import eu.etaxonomy.taxeditor.webapp.ICDMServerError;
+
/**
* @author cmathew
* @date 6 Oct 2014
*
*/
-public class CdmServerTest extends UnitilsJUnit4 {
+public class CdmServerTest extends TestConfig {
private static final Logger logger = Logger.getLogger(CdmServerTest.class);
- @Ignore // this should be targetting integration or production
+
+
@Test
- public void startCdmServer() throws CDMServerException {
+ public void generateConfigFile() throws IOException {
+ String mgdServerConfigFileName = "test.mgd.datasources.xml";
+ String config = CDMServerUtils.convertEditorToServerConfig();
+ CDMServerUtils.writeManagedServerConfig(config, mgdServerConfigFileName);
+ }
+
+ @Test
+ public void manageCdmServer() throws IOException, URISyntaxException, CDMEmbeddedServerException {
Bundle bundle = Platform.getBundle("eu.etaxonomy.taxeditor.test");
- URL serverPropertiesURL = bundle.getEntry("src/test/resources/server.properties");
- CDMServer cdmServer = new CDMServer("cdmTest", serverPropertiesURL);
- cdmServer .start();
+ URL mgdDatasourcesConfigURL = bundle.getEntry("src/test/resources/.cdmLibrary/writableResources/mgd.datasources.xml");
+ File mgdDatasourcesConfigFile = new File(FileLocator.resolve(mgdDatasourcesConfigURL).toURI());
+ CDMServer cdmServer = new CDMServer("cdmTest", mgdDatasourcesConfigFile);
+ cdmServer.start(new ICDMServerError() {
+ @Override
+ public void handleError(Throwable t) {
+ Assert.fail("Error starting server. Reason : " + t.getMessage());
+ }
+ });
try {
- cdmServer.stop(true);
+ cdmServer.stop();
} catch (Exception e) {
e.printStackTrace();
- Assert.fail("Server could not be stopped. Reason : " + e.getMessage());
+ Assert.fail("Error stopping server. Reason : " + e.getMessage());
}
}
-
}
--- /dev/null
+// $Id$
+/**
+* Copyright (C) 2015 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* 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.httpinvoker;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Properties;
+
+import org.apache.log4j.Logger;
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.core.runtime.Platform;
+import org.junit.BeforeClass;
+import org.osgi.framework.Bundle;
+import org.unitils.UnitilsJUnit4;
+
+/**
+ * @author cmathew
+ * @date 11 Nov 2015
+ *
+ */
+public abstract class TestConfig extends UnitilsJUnit4 {
+
+ private static final Logger logger = Logger.getLogger(TestConfig.class);
+
+ private final static String DEFAULT_USER = "admin";
+ private final static String DEFAULT_PASSWORD = "00000";
+ private final static int DEFAULT_HTTP_PORT = 9090;
+ private final static String DEFAULT_CONTEXT_PATH = "";
+ private final static String DEFAULT_SOURCE_NAME = "default";
+ private final static String DEFAULT_HOST = "localhost";
+
+ private static String userHomeKey = "user.home";
+
+ protected static String user = DEFAULT_USER;
+ protected static String password = DEFAULT_PASSWORD;
+ protected static int httpPort = DEFAULT_HTTP_PORT;
+ protected static String contextPath = DEFAULT_CONTEXT_PATH;
+ protected static String sourceName = DEFAULT_SOURCE_NAME;
+ protected static String host = DEFAULT_HOST;
+
+ @BeforeClass
+ public static void initializeTestConfig() {
+ try {
+ String userHomeDirPath;
+ Bundle bundle = Platform.getBundle("eu.etaxonomy.taxeditor.test");
+
+ URL userHomeDirURL = bundle.getEntry("src/test/resources");
+ File userHomeDir = new File(FileLocator.resolve(userHomeDirURL).toURI());
+ userHomeDirPath = userHomeDir.getAbsolutePath();
+
+ URL serverPropertiesURL = bundle.getEntry("src/test/resources/server.properties");
+ File serverPropertiesFile = new File(FileLocator.resolve(serverPropertiesURL).toURI());
+ InputStream inputStream = new FileInputStream(serverPropertiesFile);
+
+ Properties prop = new Properties();
+
+ prop.load(inputStream);
+ inputStream.close();
+
+
+ logger.warn("Setting user.home to " + userHomeDirPath);
+ System.setProperty(userHomeKey, userHomeDirPath);
+
+
+ if(prop.getProperty("user") != null) {
+ user = prop.getProperty("user");
+ }
+
+ if(prop.getProperty("password") != null) {
+ password = prop.getProperty("password");
+ }
+
+ if(prop.getProperty("httpPort") != null) {
+ httpPort = Integer.valueOf(prop.getProperty("httpPort"));
+ }
+
+ if(prop.getProperty("contextPath") != null) {
+ contextPath = prop.getProperty("contextPath");
+ }
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ // Assert.fail("Server failed to start. Reason : " + e.getMessage());
+ }
+ }
+
+}
import java.util.Set;
import org.junit.After;
-import org.unitils.UnitilsJUnit4;
/**
* @author cmathew
* @date 16 Oct 2015
*
*/
-public abstract class ThreadedTest extends UnitilsJUnit4 {
+public abstract class ThreadedTest extends TestConfig {
private Set<TestThread> threadPool = new HashSet<TestThread>();
<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
- <bean id="defaultRemoteSource">
- <property name="server" value="127.0.0.1" />
- <property name="port" value="9090" />
- <property name="contextPath" value="" />
- </bean>
- <bean id="incompleteRemoteSource">
- <property name="port" value="9090" />
- <property name="contextPath" value="" />
+<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
+ ls
+ <bean id="cdmTestDataSource" class="eu.etaxonomy.cdm.database.LocalH2" lazy-init="true">
+ <property name="driverClassName" value="org.h2.Driver" />
+ <property name="url" value="jdbc:h2:file:./target/classes/h2/cdmTest;AUTO_SERVER=TRUE" />
+ <property name="username" value="sa" />
+ <property name="password" value="" />
+ <property name="mode" value="embedded" />
+ <property name="nomenclaturalCode" value="ICNAFP" />
</bean>
</beans>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
+ http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
+">
+ <bean id="dataSourceProperties" class="eu.etaxonomy.cdm.remote.config.DataSourceProperties">
+ <property name="propsMap">
+ <map/>
+ </property>
+ </bean>
+ <bean id="cdmTest" lazy-init="true" class="com.mchange.v2.c3p0.ComboPooledDataSource">
+ <property name="driverClass" value="org.h2.Driver"/>
+ <property name="user" value="sa"/>
+ <property name="password" value=""/>
+ <property name="jdbcUrl" value="jdbc:h2:file:./target/classes/h2/cdmTest;AUTO_SERVER=TRUE"/>
+ </bean>
+</beans>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- DO NOT EDIT THIS FILE MANUALLY. --><!-- It is created by the Taxonomic Editor for launching a managed CDM Server. --><beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
+ http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
+">
+ <bean id="dataSourceProperties" class="eu.etaxonomy.cdm.remote.config.DataSourceProperties">
+ <property name="propsMap">
+ <map/>
+ </property>
+ </bean>
+ <bean id="cdmTest" lazy-init="true" class="com.mchange.v2.c3p0.ComboPooledDataSource">
+ <property name="driverClass" value="org.h2.Driver"/>
+ <property name="user" value="sa"/>
+ <property name="password" value=""/>
+ <property name="jdbcUrl" value="jdbc:h2:file:/exthd1/home/Development/EDIT/taxeditor/eu.etaxonomy.taxeditor.test/src/test/resources/.cdmLibrary/writableResources/h2/LocalH2/cdmTest;AUTO_SERVER=TRUE"/>
+ </bean>
+</beans>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
-<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
- <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
- <param name="Target" value="System.out"/>
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%d %p [%c] - %m%n"/>
- </layout>
- <filter class="org.apache.log4j.filter.ExpressionFilter">
- <param name="expression" value="msg like '.*has a maxElementsInMemory of 0. This might lead to performance degradation or OutOfMemoryError at Terracotta client.*'" />
- <param name="acceptOnMatch" value="false"/>
- </filter>
- </appender>
- <root>
- <priority value ="WARN" />
- <appender-ref ref="CONSOLE"/>
- </root>
- <logger name="org.hibernate.proxy.AbstractLazyInitializer">
- <level value="info"/>
- </logger>
- <logger name="org.hibernate.collection.internal.AbstractPersistentCollection">
- <level value="info"/>
- </logger>
+<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
+ debug="false">
+ <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
+ <param name="Target" value="System.out" />
+ <layout class="org.apache.log4j.PatternLayout">
+ <param name="ConversionPattern" value="%d %p [%c] - %m%n" />
+ </layout>
+ </appender>
+ <root>
+ <priority value="WARN" />
+ <appender-ref ref="CONSOLE" />
+ </root>
</log4j:configuration>
\ No newline at end of file
stopKey=jetty-cdm-server
user=admin
password=00000
+contextPath=
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry exported="true" kind="lib" path="lib/mysql-connector-java-5.1.24.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/javax.servlet-api-3.1.0.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/jetty-all-9.2.9.v20150224.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/log4j-1.2.17.jar"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src/main/java"/>
+ <classpathentry kind="src" path="src/main/resources"/>
+ <classpathentry kind="output" path="target/classes"/>
+</classpath>
--- /dev/null
+/bin/
+/target/
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>eu.etaxonomy.taxeditor.webapp</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
--- /dev/null
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.7
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.7
--- /dev/null
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Webapp
+Bundle-SymbolicName: eu.etaxonomy.taxeditor.webapp;singleton:=true
+Bundle-Version: 3.12.0.qualifier
+Require-Bundle: org.eclipse.core.runtime
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
+Bundle-ActivationPolicy: lazy
+Export-Package: eu.etaxonomy.taxeditor.webapp
+Bundle-ClassPath: .,
+ lib/log4j-1.2.17.jar,
+ lib/jetty-all-9.2.9.v20150224.jar,
+ lib/javax.servlet-api-3.1.0.jar,
+ lib/mysql-connector-java-5.1.24.jar
+Bundle-Vendor: EDIT
+Import-Package: org.eclipse.jface.resource,
+ org.eclipse.ui.plugin
+Bundle-Activator: eu.etaxonomy.taxeditor.webapp.TaxeditorWebappPlugin
--- /dev/null
+source.. = src/main/java/,\
+ src/main/resources/
+bin.includes = META-INF/,\
+ .,\
+ lib/log4j-1.2.17.jar,\
+ lib/jetty-all-9.2.9.v20150224.jar,\
+ lib/javax.servlet-api-3.1.0.jar,\
+ lib/mysql-connector-java-5.1.24.jar,\
+ lib/cdmlib-remote-webapp.war
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <parent>
+ <groupId>eu.etaxonomy</groupId>
+ <artifactId>taxeditor-parent</artifactId>
+ <version>3.12.0-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>eu.etaxonomy.taxeditor.webapp</artifactId>
+ <packaging>eclipse-plugin</packaging>
+ <name>CDM Library Webapp Plugin</name>
+ <description>CDM Library webapp as a plugin</description>
+
+ <build>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <version>2.7</version>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <version>2.4</version>
+ <executions>
+ <execution>
+ <id>copy-dependency-war</id>
+ <phase>validate</phase>
+ <goals>
+ <goal>copy-dependencies</goal>
+ </goals>
+ <configuration>
+ <includeArtifactIds>
+ cdmlib-remote-webapp
+ </includeArtifactIds>
+ <outputDirectory>
+ ${basedir}/lib
+ </outputDirectory>
+ <overWriteReleases>true</overWriteReleases>
+ <overWriteSnapshots>true</overWriteSnapshots>
+ <excludeTransitive>true</excludeTransitive>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <version>1.7</version>
+ <executions>
+ <execution>
+ <id>update-snapshot-jar-names</id>
+ <phase>validate</phase>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ <configuration>
+ <target>
+ <echo>Anonymizing war</echo>
+ <move todir="./lib">
+ <fileset dir="./lib" />
+ <mapper type="regexp"
+ from="(^cdmlib\-remote\-webapp).*(\.war)" to="\1\2" />
+ </move>
+ </target>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ <repositories>
+ <repository>
+ <id>SpringSource Enterprise Bundle Repository - External Bundle
+ Milestones
+ </id>
+ <url>http://repository.springsource.com/maven/bundles/milestone
+ </url>
+ </repository>
+ <repository>
+ <id>SpringSource Enterprise Bundle Repository - SpringSource
+ Bundle
+ Releases
+ </id>
+ <url>http://repository.springsource.com/maven/bundles/release
+ </url>
+ </repository>
+ <repository>
+ <id>SpringSource Enterprise Bundle Repository - External Bundle
+ Releases
+ </id>
+ <url>http://repository.springsource.com/maven/bundles/external
+ </url>
+ </repository>
+ </repositories>
+ <dependencies>
+ <dependency>
+ <groupId>eu.etaxonomy</groupId>
+ <artifactId>cdmlib-remote-webapp</artifactId>
+ <version>${cdmlib.version}</version>
+ <type>war</type>
+ </dependency>
+ </dependencies>
+</project>
+
--- /dev/null
+// $Id$
+/**
+* Copyright (C) 2014 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* 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.webapp;
+
+/**
+ * @author cmathew
+ * @date 23 Sep 2014
+ *
+ */
+public class CDMEmbeddedServerException extends Exception {
+
+ public CDMEmbeddedServerException(String message) {
+ super(message);
+ }
+
+ public CDMEmbeddedServerException(Exception e) {
+ super(e);
+ }
+
+ public CDMEmbeddedServerException(String message,Exception e) {
+ super(message,e);
+ }
+
+}
--- /dev/null
+// $Id$
+/**
+ * Copyright (C) 2014 EDIT
+ * European Distributed Institute of Taxonomy
+ * http://www.e-taxonomy.eu
+ *
+ * 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.webapp;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanException;
+import javax.management.MBeanServerConnection;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+import javax.management.ReflectionException;
+import javax.management.remote.JMXConnector;
+import javax.management.remote.JMXConnectorFactory;
+import javax.management.remote.JMXServiceURL;
+
+import org.apache.log4j.Logger;
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.util.StringUtil;
+import org.eclipse.jetty.util.preventers.AppContextLeakPreventer;
+import org.eclipse.jetty.webapp.WebAppContext;
+import org.osgi.framework.Bundle;
+
+/**
+ *
+ * (Singleton) Server instance which manages a compatible cdmlib-webapp-war.
+ * This is done by launching a jetty instance (using jetty-runner) as an
+ * executed process. The choice of the external process over a more
+ * preferable 'embedded jetty' instance is due to problems arising from the
+ * class loading of classes (e.g. from hibernate core) which are needed
+ * for both the webapp as well as the remoting client.
+ *
+ * @author cmathew
+ * @date 23 Sep 2014
+ *
+ */
+
+public class CDMServer {
+
+ public static final Logger logger = Logger.getLogger(CDMServer.class);
+
+
+ private final String dataSourceName;
+ private final String host = "127.0.0.1";
+ private int httpPort = 9090;
+ private final String contextPath = "/";
+
+ private File warFile;
+ private Server server;
+
+
+ public CDMServer(String dataSourceName, File dataSourcesFile) throws CDMEmbeddedServerException {
+ if(StringUtil.isBlank(dataSourceName)) {
+ throw new CDMEmbeddedServerException("DataSource name is not valid");
+ }
+
+ if(dataSourcesFile == null || !dataSourcesFile.exists()) {
+ throw new CDMEmbeddedServerException("DataSource config file does not exist");
+ }
+ this.dataSourceName = dataSourceName;
+ Bundle bundle = Platform.getBundle("eu.etaxonomy.taxeditor.webapp");
+ URL warURL = bundle.getEntry("lib/cdmlib-remote-webapp.war");
+
+ try {
+ URL resolvedWarURL = FileLocator.toFileURL(warURL);
+ // We need to use the 3-arg constructor of URI in order to properly escape file system chars
+ URI resolvedURI = new URI(resolvedWarURL.getProtocol(), resolvedWarURL.getPath(), null);
+ warFile = new File(resolvedURI);
+ System.out.println("war url : " + warFile.getAbsolutePath());
+
+ if(warFile == null || !warFile.exists()) {
+ throw new CDMEmbeddedServerException("Cdmlib War file does not exist");
+ }
+ } catch (URISyntaxException use) {
+ throw new CDMEmbeddedServerException(use);
+ } catch (IOException ioe) {
+ throw new CDMEmbeddedServerException(ioe);
+ }
+
+ System.setProperty("spring.profiles.active", "remoting");
+ System.setProperty("cdm.beanDefinitionFile", dataSourcesFile.getAbsolutePath());
+ System.setProperty("cdm.datasource", dataSourceName);
+
+ httpPort = findFreePort();
+
+ logger.warn("Starting server on port : " + httpPort);
+
+ server = new Server(httpPort);
+
+ server.addBean(new AppContextLeakPreventer());
+
+ WebAppContext webapp = new WebAppContext();
+ webapp.setContextPath(contextPath);
+ webapp.setWar(warFile.getAbsolutePath());
+
+ server.setHandler(webapp);
+ }
+
+ public String getDataSourceName() {
+ return dataSourceName;
+ }
+ public String getHost() {
+ return host;
+ }
+
+ public int getPort() {
+ return httpPort;
+ }
+
+ public String getContextPath() {
+ return contextPath;
+ }
+
+ private static int findFreePort() throws CDMEmbeddedServerException {
+ ServerSocket socket = null;
+ try {
+ socket = new ServerSocket(0);
+ socket.setReuseAddress(true);
+ int port = socket.getLocalPort();
+ try {
+ socket.close();
+ } catch (IOException e) {
+
+ }
+ return port;
+ } catch (IOException e) {
+ } finally {
+ if (socket != null) {
+ try {
+ socket.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ throw new CDMEmbeddedServerException("Could not find a free TCP/IP port to start embedded Jetty HTTP Server on");
+ }
+
+ public void start(ICDMServerError cdmServerError) throws CDMEmbeddedServerException {
+ start(true, cdmServerError);
+ }
+
+ public void start(boolean wait, final ICDMServerError cdmServerError) throws CDMEmbeddedServerException {
+
+ if(server == null) {
+ throw new CDMEmbeddedServerException("Server is already disposed");
+ }
+
+ if(server.isStarting()) {
+ throw new CDMEmbeddedServerException("Server is starting");
+ }
+
+ if(server.isStarted()) {
+ throw new CDMEmbeddedServerException("Server has started");
+ }
+
+ if(server.isRunning()) {
+ throw new CDMEmbeddedServerException("Server is running");
+ }
+
+ if(server.isStopping()) {
+ throw new CDMEmbeddedServerException("Server is currently stopping. Please re-try in about 10 seconds");
+ }
+
+ Thread serverThread = new Thread() {
+
+ @Override
+ public void run() {
+ try {
+ server.start();
+ server.join();
+ } catch (Throwable t) {
+ cdmServerError.handleError(t);
+ }
+ }
+ };
+
+ serverThread.start();
+
+ if(wait) {
+ while(!server.isStarted()) {}
+
+ }
+ }
+
+ public boolean isAlive() {
+ return server.isRunning() || server.isStarting() || server.isStarted();
+ }
+
+ public boolean isStarted() {
+ return server.isStarted();
+ }
+
+ public void stop() throws Exception {
+ server.stop();
+ server.destroy();
+ server = null;
+ }
+
+
+
+
+ public static void stopServerViaJMX(int jmxPort) throws CDMEmbeddedServerException {
+ String JMX_URL = "service:jmx:rmi:///jndi/rmi://localhost:" + jmxPort + "/jmxrmi";
+ logger.warn("Shutting down Jetty instance ... ");
+
+ try {
+ JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(JMX_URL), null);
+ connector.connect(null);
+ MBeanServerConnection connection = connector.getMBeanServerConnection();
+ ObjectName objectName = new ObjectName("org.eclipse.jetty.server:type=server,id=0");
+ connection.invoke(objectName, "stop", null, null);
+ logger.warn("Shutdown command sent");
+ } catch (InstanceNotFoundException e) {
+ throw new CDMEmbeddedServerException(e);
+ } catch (MBeanException e) {
+ throw new CDMEmbeddedServerException(e);
+ } catch (ReflectionException e) {
+ throw new CDMEmbeddedServerException(e);
+ } catch (IOException e) {
+ throw new CDMEmbeddedServerException(e);
+ } catch (MalformedObjectNameException e) {
+ throw new CDMEmbeddedServerException(e);
+ }
+ }
+
+
+}
--- /dev/null
+// $Id$
+/**
+* Copyright (C) 2015 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* 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.webapp;
+
+/**
+ * @author cmathew
+ * @date 16 Nov 2015
+ *
+ */
+public interface ICDMServerError {
+
+ public void handleError(Throwable t);
+
+}
--- /dev/null
+package eu.etaxonomy.taxeditor.webapp;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ *
+ * @author n.hoffmann
+ * @version $Id: $
+ */
+public class TaxeditorWebappPlugin extends AbstractUIPlugin {
+
+ // The plug-in ID
+ /** Constant <code>PLUGIN_ID="eu.etaxonomy.taxeditor.editor"</code> */
+ public static final String PLUGIN_ID = "eu.etaxonomy.taxeditor.editor";
+
+ // The shared instance
+ private static TaxeditorWebappPlugin plugin;
+
+ /**
+ * The constructor
+ */
+ public TaxeditorWebappPlugin() {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ /** {@inheritDoc} */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ /** {@inheritDoc} */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static TaxeditorWebappPlugin getDefault() {
+ return plugin;
+ }
+
+ /**
+ * Returns an image descriptor for the image file at the given
+ * plug-in relative path
+ *
+ * @param path the path
+ * @return the image descriptor
+ */
+ public static ImageDescriptor getImageDescriptor(String path) {
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
+
+
+ /**
+ * Exposes this normally protected method.
+ *
+ * @return a {@link org.eclipse.jface.resource.ImageRegistry} object.
+ */
+ @Override
+ public ImageRegistry createImageRegistry(){
+ return super.createImageRegistry();
+ }
+}
-<?xml version="1.0" encoding="UTF-8"?>\r
-<classpath>\r
- <classpathentry kind="src" path="/eu.etaxonomy.taxeditor.application"/>\r
- <classpathentry kind="src" path="/eu.etaxonomy.taxeditor.bulkeditor"/>\r
- <classpathentry kind="src" path="/eu.etaxonomy.taxeditor.cdmlib"/>\r
- <classpathentry kind="src" path="/eu.etaxonomy.taxeditor.editor"/>\r
- <classpathentry kind="src" path="/eu.etaxonomy.taxeditor.navigation"/>\r
- <classpathentry kind="src" path="/eu.etaxonomy.taxeditor.printpublisher"/>\r
- <classpathentry kind="src" path="/eu.etaxonomy.taxeditor.store"/>\r
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>\r
- <classpathentry kind="output" path="target/classes"/>\r
-</classpath>\r
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
+ <classpathentry kind="src" path="/eu.etaxonomy.taxeditor.application"/>
+ <classpathentry kind="src" path="/eu.etaxonomy.taxeditor.bulkeditor"/>
+ <classpathentry kind="src" path="/eu.etaxonomy.taxeditor.cdmlib"/>
+ <classpathentry kind="src" path="/eu.etaxonomy.taxeditor.editor"/>
+ <classpathentry kind="src" path="/eu.etaxonomy.taxeditor.navigation"/>
+ <classpathentry kind="src" path="/eu.etaxonomy.taxeditor.printpublisher"/>
+ <classpathentry kind="src" path="/eu.etaxonomy.taxeditor.store"/>
+ <classpathentry kind="output" path="target/classes"/>
+</classpath>
<module>eu.etaxonomy.taxeditor.help</module>
<module>eu.etaxonomy.taxeditor.molecular</module>
<module>eu.etaxonomy.taxeditor.molecular.lib</module>
+ <module>eu.etaxonomy.taxeditor.webapp</module>
<module>eu.etaxonomy.taxeditor.application</module>
<module>eu.etaxonomy.taxeditor.feature.platform</module>
<module>eu.etaxonomy.taxeditor.feature</module>