eu.etaxonomy.taxeditor.cdmlib/lib/xstream-1.4.4.jar -text
eu.etaxonomy.taxeditor.cdmlib/lib/yjp-controller-api-redist-9.0.8.jar -text
eu.etaxonomy.taxeditor.cdmlib/pom.xml -text
-eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/application/CdmApplicationRemoteConfiguration.java -text
-eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/application/CdmApplicationRemoteController.java -text
-eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmServiceCacher.java -text
-eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/lazyloading/CdmLazyLoader.java -text
-eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/remote/CdmPersistentRemoteSource.java -text
-eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/remote/CdmRemoteSource.java -text
-eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/remote/CdmRemoteSourceBase.java -text
-eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/remote/CdmRemoteSourceException.java -text
-eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/remote/ICdmRemoteSource.java -text
-eu.etaxonomy.taxeditor.cdmlib/src/main/java/org/hibernate/collection/internal/AbstractPersistentCollection.java -text
-eu.etaxonomy.taxeditor.cdmlib/src/main/java/org/hibernate/proxy/AbstractLazyInitializer.java -text
eu.etaxonomy.taxeditor.cdmlib/src/main/resources/eu/etaxonomy/cdm/config.properties -text
eu.etaxonomy.taxeditor.cdmlib/src/main/resources/eu/etaxonomy/cdm/httpInvokerServiceClients.xml -text
eu.etaxonomy.taxeditor.cdmlib/src/main/resources/eu/etaxonomy/cdm/localApplicationContext.xml -text
com.google.api.detect,
com.google.api.translate,
eu.etaxonomy.cdm.api.application,
+ eu.etaxonomy.cdm.api.cache,
eu.etaxonomy.cdm.api.conversation,
eu.etaxonomy.cdm.api.facade,
- eu.etaxonomy.cdm.api.lazyloading,
eu.etaxonomy.cdm.api.service,
eu.etaxonomy.cdm.api.service.config,
eu.etaxonomy.cdm.api.service.description,
eu.etaxonomy.cdm.print.out.pdf,
eu.etaxonomy.cdm.print.out.taxpub,
eu.etaxonomy.cdm.print.out.xml,
- eu.etaxonomy.cdm.remote,
eu.etaxonomy.cdm.remote.config,
eu.etaxonomy.cdm.remote.controller,
eu.etaxonomy.cdm.remote.controller.dto,
eu.etaxonomy.cdm.validation.annotation,
eu.etaxonomy.cdm.validation.constraint,
eu.etaxonomy.remote.dto.rdf,
+ javassist.util.proxy,
javax.persistence,
junit.framework;uses:="org.junit.runner.manipulation,org.junit.runner,org.junit.runner.notification",
+ net.sf.ehcache,
+ net.sf.ehcache.config,
+ net.sf.ehcache.store,
net.sf.json;uses:="net.sf.json.processors,net.sf.json.util,org.apache.commons.lang.exception",
org.apache.commons.collections;uses:="org.apache.commons.collections.keyvalue,new org.apache.commons.collections",
org.apache.commons.io;uses:="org.apache.commons.io.filefilter",
org.hibernate,
org.hibernate.annotations.common.reflection,
org.hibernate.cache.internal,
+ org.hibernate.cfg,
org.hibernate.classic,
org.hibernate.collection.internal,
+ org.hibernate.collection.spi,
org.hibernate.criterion,
+ org.hibernate.engine.internal,
+ org.hibernate.engine.spi,
+ org.hibernate.engine.transaction.spi,
org.hibernate.envers.query.criteria,
+ org.hibernate.internal,
+ org.hibernate.internal.util,
+ org.hibernate.internal.util.collections,
+ org.hibernate.mapping,
+ org.hibernate.persister.collection,
+ org.hibernate.persister.entity,
+ org.hibernate.pretty,
+ org.hibernate.property,
org.hibernate.proxy,
+ org.hibernate.proxy.pojo.javassist,
org.hibernate.search,
org.hibernate.search.spatial.impl,
+ org.hibernate.type,
org.jadira.usertype.dateandtime.joda,
org.jadira.usertype.dateandtime.shared.spi,
org.jboss.logging,
org.odftoolkit.odfdom.dom.element,
org.odftoolkit.odfdom.dom.element.style,
org.odftoolkit.odfdom.dom.style,
+ org.springframework.beans,
org.springframework.beans.factory,
org.springframework.beans.factory.annotation;
uses:="org.apache.commons.logging,
org.springframework.beans.factory.wiring,
org.springframework.core.type,
org.springframework.beans.factory",
+ org.springframework.beans.factory.config,
+ org.springframework.beans.factory.support,
+ org.springframework.beans.factory.xml,
org.springframework.cache.ehcache,
org.springframework.context;
uses:="org.springframework.core.io,
org.aopalliance.intercept,
org.springframework.context,
org.springframework.beans.factory",
+ org.springframework.context.support,
org.springframework.core;uses:="org.springframework.util",
+ org.springframework.core.env,
org.springframework.core.io;uses:="org.jboss.virtual",
+ org.springframework.core.io.support,
org.springframework.core.type.classreading,
org.springframework.orm.hibernate3;
uses:="org.apache.commons.logging,
org.springframework.dao,
org.springframework.transaction.support",
org.springframework.orm.hibernate4,
+ org.springframework.remoting,
+ org.springframework.remoting.httpinvoker,
+ org.springframework.remoting.support,
org.springframework.security.access,
org.springframework.security.authentication,
org.springframework.security.authentication.event,
org.springframework.transaction,
org.apache.commons.logging,
org.springframework.beans.factory",
+ org.springframework.util,
org.springframework.web.servlet;
uses:="org.springframework.web.multipart,
org.apache.commons.logging,
org.springframework.context.event,
javax.servlet,
org.springframework.ui,
- javax.servlet.http"
+ javax.servlet.http",
+ org.unitils,
+ org.unitils.database,
+ org.unitils.database.annotations,
+ org.unitils.database.util,
+ org.unitils.dbunit.annotation,
+ org.unitils.spring.annotation
Bundle-Vendor: EDIT
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Require-Bundle: org.eclipse.osgi,
+++ /dev/null
-/**\r
-* Copyright (C) 2014 EDIT\r
-* European Distributed Institute of Taxonomy \r
-* http://www.e-taxonomy.eu\r
-* \r
-* The contents of this file are subject to the Mozilla Public License Version 1.1\r
-* See LICENSE.TXT at the top of this package for the full license terms.\r
-*/\r
-\r
-package eu.etaxonomy.cdm.api.application;\r
-\r
-import javax.sql.DataSource;\r
-\r
-import org.hibernate.SessionFactory;\r
-\r
-import org.apache.log4j.Logger;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-import org.springframework.transaction.PlatformTransactionManager;\r
-import org.springframework.transaction.TransactionStatus;\r
-\r
-import eu.etaxonomy.cdm.api.conversation.ConversationHolder;\r
-import eu.etaxonomy.cdm.api.conversation.ConversationHolderMock;\r
-import eu.etaxonomy.cdm.api.service.IDatabaseService;\r
-import eu.etaxonomy.cdm.ext.geo.IEditGeoService;\r
-\r
-\r
-/**\r
- * CDM Application Configuration class which manages the configuration for remoting\r
- * clients\r
- *\r
- */\r
-@Component\r
-public class CdmApplicationRemoteConfiguration extends CdmApplicationDefaultConfiguration {\r
- \r
- @SuppressWarnings("unused")\r
- private static final Logger logger = Logger.getLogger(CdmApplicationRemoteConfiguration.class);\r
-\r
- @Autowired\r
- IEditGeoService editGeoService;\r
- \r
- public CdmApplicationRemoteConfiguration() {\r
- }\r
- \r
- /* (non-Javadoc)\r
- * @see eu.etaxonomy.cdm.api.application.CdmApplicationDefaultConfiguration#getTransactionManager()\r
- */\r
- @Override\r
- public PlatformTransactionManager getTransactionManager() throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("getTransactionManager is not implemented for CdmApplicationRemoteConfiguration");\r
- }\r
-\r
-\r
- /* (non-Javadoc)\r
- * @see eu.etaxonomy.cdm.api.application.ICdmApplicationConfiguration#startTransaction()\r
- */\r
- @Override\r
- public TransactionStatus startTransaction() throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("startTransaction is not implemented for CdmApplicationRemoteConfiguration");\r
- }\r
-\r
-\r
- /* (non-Javadoc)\r
- * @see eu.etaxonomy.cdm.api.application.ICdmApplicationConfiguration#startTransaction()\r
- */\r
- @Override\r
- public TransactionStatus startTransaction(Boolean readOnly) throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("startTransaction is not implemented for CdmApplicationRemoteConfiguration");\r
- }\r
-\r
-\r
- /* (non-Javadoc)\r
- * @see eu.etaxonomy.cdm.api.application.CdmApplicationDefaultConfiguration#commitTransaction(org.springframework.transaction.TransactionStatus)\r
- */\r
- @Override\r
- public void commitTransaction(TransactionStatus txStatus) throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("commitTransaction is not implemented for CdmApplicationRemoteConfiguration");\r
- }\r
- \r
- /* (non-Javadoc)\r
- * @see eu.etaxonomy.cdm.api.application.CdmApplicationDefaultConfiguration#NewConversation()\r
- */\r
- @Override\r
- public ConversationHolder NewConversation() { \r
- return new ConversationHolderMock();\r
- }\r
- \r
- /**\r
- * @return\r
- */\r
- public IEditGeoService getEditGeoService() {\r
- return this.editGeoService;\r
- }\r
- \r
- /* (non-Javadoc)\r
- * @see eu.etaxonomy.cdm.api.application.CdmApplicationDefaultConfiguration#setDataSource(javax.sql.DataSource)\r
- */\r
- @Override\r
- public void setDataSource(DataSource dataSource) { \r
- }\r
- \r
- /* (non-Javadoc)\r
- * @see eu.etaxonomy.cdm.api.application.CdmApplicationDefaultConfiguration#setTransactionManager(org.springframework.transaction.PlatformTransactionManager)\r
- */\r
- @Override\r
- public void setTransactionManager(PlatformTransactionManager transactionManager) { \r
- }\r
- \r
- /* (non-Javadoc)\r
- * @see eu.etaxonomy.cdm.api.application.CdmApplicationDefaultConfiguration#setSessionFactory(org.hibernate.SessionFactory)\r
- */\r
- @Override\r
- public void setSessionFactory(SessionFactory sessionFactory) { \r
- }\r
-}\r
+++ /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.cdm.api.application;
-
-import java.util.List;
-import java.util.Properties;
-
-import org.apache.log4j.Logger;
-import org.hibernate.collection.internal.AbstractPersistentCollection;
-import org.hibernate.proxy.AbstractLazyInitializer;
-import org.springframework.beans.MutablePropertyValues;
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
-import org.springframework.context.ApplicationListener;
-import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.core.io.Resource;
-
-import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
-import eu.etaxonomy.cdm.common.monitor.NullProgressMonitor;
-import eu.etaxonomy.cdm.common.monitor.SubProgressMonitor;
-import eu.etaxonomy.cdm.remote.ICdmRemoteSource;
-
-/**
- * CDM Application Controller class for remoting clients
- *
- * FIXME:Remoting extending {@link CdmApplicationController} is a temporary workaround.
- * The {@link CdmApplicationController} should be split into a CdmApplicationControllerBase
- * class with {@link CdmApplicationController} and this class as subclasses
- *
- */
-public class CdmApplicationRemoteController extends CdmApplicationController {
-
- private static final Logger logger = Logger.getLogger(CdmApplicationRemoteController.class);
-
- public static final Resource DEFAULT_REMOTE_APPLICATION_CONTEXT_RESOURCE =
- new ClassPathResource("/eu/etaxonomy/cdm/remotingApplicationContext.xml");
- private final Resource applicationContextResource;
- private final IProgressMonitor progressMonitor;
-
- /**
- * Creates new instance of CdmApplicationRemoteController
- *
- * @param applicationContextResource
- * @param remoteSource
- * @param omitTermLoading
- * @param progressMonitor
- * @param listeners
- * @return
- */
- public static CdmApplicationRemoteController NewInstance(Resource applicationContextResource,
- ICdmRemoteSource remoteSource,
- boolean omitTermLoading,
- IProgressMonitor progressMonitor,
- List<ApplicationListener> listeners) {
- return new CdmApplicationRemoteController(applicationContextResource,
- remoteSource,
- omitTermLoading,
- progressMonitor,
- listeners);
-
- }
- /**
- * Creates new instance of CdmApplicationRemoteController
- *
- * @param applicationContextResource
- * @param remoteSource
- * @param omitTermLoading
- * @param progressMonitor
- * @param listeners
- * @return
- */
- public static CdmApplicationRemoteController NewInstance(ICdmRemoteSource remoteSource,
- boolean omitTermLoading,
- IProgressMonitor progressMonitor,
- List<ApplicationListener> listeners) {
-
- return new CdmApplicationRemoteController(DEFAULT_REMOTE_APPLICATION_CONTEXT_RESOURCE,
- remoteSource,
- omitTermLoading,
- progressMonitor,
- listeners);
-
- }
-
- /**
- * Constructs CdmApplicationRemoteController
- *
- * @param applicationContextResource
- * @param remoteSource
- * @param omitTermLoading
- * @param progressMonitor
- * @param listeners
- */
- private CdmApplicationRemoteController(Resource applicationContextResource,
- ICdmRemoteSource remoteSource,
- boolean omitTermLoading,
- IProgressMonitor progressMonitor,
- List<ApplicationListener> listeners){
- logger.info("Start CdmApplicationRemoteController with remote source: " + remoteSource.getName());
- this.applicationContextResource =
- applicationContextResource != null ? applicationContextResource : DEFAULT_REMOTE_APPLICATION_CONTEXT_RESOURCE;
- this.progressMonitor = progressMonitor != null ? progressMonitor : new NullProgressMonitor();
-
- setNewRemoteSource(remoteSource, omitTermLoading, listeners);
-
- }
-
-
-
-
- /**
- * Creates and starts a new spring application context
- *
- * @param remoteSource object for connecting to an http-invoker server
- * @param omitTermLoading
- * @param listeners
- * @return
- */
- protected boolean setNewRemoteSource(ICdmRemoteSource remoteSource,
- boolean omitTermLoading,
- List<ApplicationListener> listeners){
-
- logger.info("Connecting to '" + remoteSource.getName() + "'");
-
- MonitoredGenericApplicationContext applicationContext = new MonitoredGenericApplicationContext();
- int refreshTasks = 45;
- int nTasks = 5 + refreshTasks;
-
- progressMonitor.beginTask("Connecting to '" + remoteSource.getName() + "'", nTasks);
-
- progressMonitor.subTask("Registering remote source.");
- PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
- Properties properties = new Properties();
- properties.setProperty("remoteServer", remoteSource.getServer());
- properties.setProperty("remotePort", String.valueOf(remoteSource.getPort()));
- properties.setProperty("remoteContext", remoteSource.getContextPath());
- pspc.setProperties(properties);
- applicationContext.addBeanFactoryPostProcessor(pspc);
- progressMonitor.worked(1);
-
- XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);
- //xmlReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
- progressMonitor.subTask("Registering resources.");
- xmlReader.loadBeanDefinitions(applicationContextResource);
- progressMonitor.worked(1);
-
- //omitTerms
- if (omitTermLoading == true){
- String initializerName = "persistentTermInitializer";
- BeanDefinition beanDef = applicationContext.getBeanDefinition(initializerName);
- MutablePropertyValues values = beanDef.getPropertyValues();
- values.addPropertyValue("omit", omitTermLoading);
- }
-
- if (listeners != null){
- for(ApplicationListener listener : listeners){
- applicationContext.addApplicationListener(listener);
- }
- }
-
-
- applicationContext.refresh(new SubProgressMonitor(progressMonitor, refreshTasks));
- applicationContext.start();
-
- progressMonitor.subTask("Cleaning up.");
- setApplicationContext(applicationContext);
- progressMonitor.worked(1);
-
- progressMonitor.done();
- return true;
- }
-
- /* (non-Javadoc)
- * @see eu.etaxonomy.cdm.api.application.CdmApplicationController#init()
- */
- @Override
- protected void init(){
- configuration = (ICdmApplicationConfiguration)applicationContext.getBean("cdmApplicationRemoteConfiguration");
- AbstractLazyInitializer.setConfiguration(this);
- AbstractPersistentCollection.setConfiguration(this);
-
- }
-
-}
+++ /dev/null
-package eu.etaxonomy.cdm.api.cache;
-
-import java.util.UUID;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import eu.etaxonomy.cdm.api.service.ITermService;
-import eu.etaxonomy.cdm.model.common.CdmBase;
-
-/**
- * Class which uses CDM services to cache cdm entities
- *
- * FIXME: Currently only handles terms entities. It would be
- * interesting to have a generic method which finds the
- * correct service to load / cache the entity.
- *
- * @author cmathew
- *
- * @param <T>
- */
-@Component
-public class CdmServiceCacher<T extends CdmBase> extends CdmCacher<T> {
-
- @Autowired
- ITermService termService;
-
- @Override
- protected T findByUuid(UUID uuid) {
- return (T)termService.findWithoutFlush(uuid);
- }
-
- /* (non-Javadoc)
- * @see eu.etaxonomy.cdm.api.cache.CdmCacher#setup()
- */
- @Override
- protected void setup() {
- // TODO Auto-generated method stub
-
- }
-
-}
+++ /dev/null
-package eu.etaxonomy.cdm.api.lazyloading;
-
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.TreeSet;
-
-import org.aspectj.lang.ProceedingJoinPoint;
-import org.aspectj.lang.annotation.Around;
-import org.aspectj.lang.annotation.Aspect;
-import org.aspectj.lang.annotation.Pointcut;
-import org.hibernate.collection.internal.PersistentList;
-import org.hibernate.collection.internal.PersistentMap;
-import org.hibernate.collection.internal.PersistentSet;
-import org.hibernate.collection.internal.PersistentSortedMap;
-import org.hibernate.collection.internal.PersistentSortedSet;
-import org.hibernate.collection.spi.PersistentCollection;
-import org.hibernate.proxy.LazyInitializer;
-import org.springframework.beans.factory.annotation.Autowire;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Configurable;
-import org.springframework.stereotype.Component;
-
-import eu.etaxonomy.cdm.api.service.ICommonService;
-import eu.etaxonomy.cdm.model.common.CdmBase;
-import eu.etaxonomy.cdm.model.common.PersistentMultiLanguageText;
-
-
-@Aspect
-@Component
-@Configurable(autowire = Autowire.BY_TYPE)
-public class CdmLazyLoader {
-
-
- private Set classes = new HashSet();
-
- public static boolean enableWeaving = true;
- private static Set<String> classesToIgnore = new HashSet<String>();
-
-
- @Autowired
- private ICommonService commonService;
-
- public CdmLazyLoader() {
- //classesToIgnore.add("eu.etaxonomy.cdm.model.common.TermVocabulary");
- //classesToIgnore.add("eu.etaxonomy.cdm.model.common.OrderedTermVocabulary");
-
- }
-
- /**
- * Point cut for the 'initialize' method of the AbstractLazyInitializer.
- *
- */
- @Pointcut("execution(* org.hibernate.proxy.AbstractLazyInitializer.initialize())")
- public void possibleEntityLazyInitializationException() {
- }
-
-
- /**
- * 'Around' advice for the initialization of CDM Entity Objects
- *
- */
- @Around(value = "possibleEntityLazyInitializationException()")
- public Object preloadEntityOnDemand(ProceedingJoinPoint pjp) throws Throwable {
- if(enableWeaving) {
- LazyInitializer ll = (LazyInitializer)pjp.getTarget();
- if(ll.isUninitialized()) {
- int classid = ((Integer)ll.getIdentifier()).intValue();
- System.out.print("--> AspectJ Compile-Time Weaving " + ll.getEntityName() + " with id " + classid);
- Class clazz = (Class<? extends CdmBase>) Class.forName(ll.getEntityName());
- CdmBase cdmBase = CdmBase.deproxy(commonService.find(clazz,classid),clazz);
- ll.setImplementation(cdmBase);
- System.out.println("....Done");
- }
- }
- return pjp.proceed();
- }
-
-
- /**
- * Point cut for the 'initialize' method of the AbstractPersistentCollection.
- *
- */
- @Pointcut("execution(protected final void org.hibernate.collection.internal.AbstractPersistentCollection.initialize(..))")
- public void possibleCollectionLazyInitializationException() {
- }
-
- /**
- * 'Around' advice for the initialization of Collection objects
- *
- */
- @Around(value = "possibleCollectionLazyInitializationException()")
- public Object preloadCollectionOnDemand(ProceedingJoinPoint pjp) throws Throwable {
- if(enableWeaving) {
- PersistentCollection ps = (PersistentCollection) pjp.getTarget();
- if (ps.getOwner() != null && !classesToIgnore.contains(ps.getOwner().getClass().getName()) && !ps.wasInitialized() && !classes.contains(ps.getKey())) {
- System.out.print("--> AspectJCompile-Time Weaving " + ps.getRole());
- classes.add(ps.getKey());
- try {
- String role = ps.getRole();
- String fieldName = role.substring(role.lastIndexOf(".") + 1);
- System.out.print(", field : " + fieldName);
- Object owner = ps.getOwner();
-
- PersistentCollection col = commonService.initializeCollection(ps);
- ps.afterInitialize();
-
- Class<?> clazz = ps.getClass();
- if (clazz != null) {
- CollectionField cf = getCollectionField(col);
- Field field = clazz.getDeclaredField(cf.getFieldName());
- field.setAccessible(true);
- field.set(ps, cf.getCollection());
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- System.out.println("Error in ReattachSessionAspect : " + ex.getMessage());
- } finally {
- classes.remove(ps.getKey());
- System.out.println("....Done");
- }
- }
- }
- return pjp.proceed();
-
- }
-
- private CollectionField getCollectionField(PersistentCollection pc) {
- if(pc != null) {
- if(pc instanceof PersistentSet) {
- return new CollectionField(new HashSet((Set)pc), "set");
- }
- if(pc instanceof PersistentSortedSet) {
- return new CollectionField(new TreeSet((Set)pc), "set");
- }
- if(pc instanceof PersistentList) {
- return new CollectionField(new ArrayList((List)pc), "list");
- }
- if(pc instanceof PersistentMap || pc instanceof PersistentMultiLanguageText) {
- return new CollectionField(new HashMap((Map)pc), "map");
- }
- if(pc instanceof PersistentSortedMap) {
- return new CollectionField(new TreeMap((Map)pc), "map");
- }
- }
- return null;
- }
-
- private String getCollectionFieldName(PersistentCollection pc) {
- if(pc != null) {
- if(pc instanceof PersistentSet || pc instanceof PersistentSortedSet) {
- return "set";
- }
- if(pc instanceof PersistentList) {
- return "list";
- }
- if(pc instanceof PersistentMap || pc instanceof PersistentMultiLanguageText) {
- return "map";
- }
- }
- return null;
- }
-
- private class CollectionField {
- private Object col;
- private String fieldName;
- public CollectionField(Object col, String fieldName) {
- this.col = col;
- this.fieldName = fieldName;
- }
-
- public Object getCollection() {
- return this.col;
- }
-
- public String getFieldName() {
- return this.fieldName;
- }
- }
-
-}
+++ /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.cdm.remote;
-
-import static eu.etaxonomy.cdm.common.XmlHelp.getBeansRoot;
-import static eu.etaxonomy.cdm.common.XmlHelp.insertXmlBean;
-import static eu.etaxonomy.cdm.common.XmlHelp.insertXmlValueProperty;
-import static eu.etaxonomy.cdm.common.XmlHelp.saveToXml;
-
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.Properties;
-
-import org.apache.log4j.Logger;
-import org.jdom.Attribute;
-import org.jdom.Element;
-
-import eu.etaxonomy.cdm.common.CdmUtils;
-import eu.etaxonomy.cdm.common.XmlHelp;
-import eu.etaxonomy.cdm.config.CdmPersistentSourceUtils;
-import eu.etaxonomy.cdm.config.CdmPersistentXMLSource;
-import eu.etaxonomy.cdm.config.CdmSourceException;
-import eu.etaxonomy.cdm.config.ICdmPersistentSource;
-import eu.etaxonomy.cdm.config.CdmPersistentXMLSource.CdmSourceProperties;
-import eu.etaxonomy.cdm.database.CdmDataSource;
-import eu.etaxonomy.cdm.database.CdmPersistentDataSource;
-import eu.etaxonomy.cdm.database.DataSourceNotFoundException;
-import eu.etaxonomy.cdm.database.DatabaseTypeEnum;
-import eu.etaxonomy.cdm.database.ICdmDataSource;
-import eu.etaxonomy.cdm.database.types.IDatabaseType;
-import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
-
-/**
- * Class representing a CDM remote source which can be persisted to a source config file
- *
- */
-public class CdmPersistentRemoteSource extends CdmRemoteSourceBase implements ICdmPersistentSource{
- private static final Logger logger = Logger.getLogger(CdmPersistentRemoteSource.class);
-
- public static final String REMOTESOURCE_BEAN_POSTFIX = "RemoteSource";
- private String beanName;
- private Properties cdmSourceProperties;
- private List<Attribute> cdmSourceAttributes;
-
- /**
- * Creates a new instance of CdmPersistentRemoteSource
- *
- * @param name
- * @param server
- * @param port
- * @param contextPath
- * @param nomenclaturalCode
- * @return
- * @throws CdmRemoteSourceException
- */
- public static CdmPersistentRemoteSource NewInstance(String remoteSource) throws CdmRemoteSourceException {
- if(exists(remoteSource)) {
- return new CdmPersistentRemoteSource(remoteSource);
- } else {
- throw new CdmRemoteSourceException("Remote source '" + remoteSource + "' does not exist in sources setting file");
- }
-
- }
-
- /**S
- * Creates a new CdmPersistentRemoteSource
- *
- * @param name
- * @param server
- * @param port
- * @param contextPath
- * @param nomenclaturalCode
- * @throws CdmRemoteSourceException
- */
- private CdmPersistentRemoteSource(String remoteSource) throws CdmRemoteSourceException {
-
- CdmPersistentXMLSource cdmPersistentXMLSource = CdmPersistentXMLSource.NewInstance(remoteSource, REMOTESOURCE_BEAN_POSTFIX);
- if(cdmPersistentXMLSource.getElement() != null) {
- beanName = cdmPersistentXMLSource.getBeanName();
- // properties from the persistent xml file
- cdmSourceProperties = cdmPersistentXMLSource.getCdmSourceProperties();
- cdmSourceAttributes = cdmPersistentXMLSource.getCdmSourceAttributes();
- checkProperties(cdmSourceProperties);
- } else {
- throw new CdmRemoteSourceException("Remote source '" + remoteSource + "' does not exist in settings file");
- }
- initDatabaseConnection();
- }
-
- private static void checkProperties(Properties cdmSourceProperties) throws CdmRemoteSourceException {
- if(!cdmSourceProperties.containsKey(CdmSourceProperties.SERVER.toString())) {
- throw new CdmRemoteSourceException("Could not initialise remote source. Required property '" + CdmSourceProperties.SERVER.toString() + "' is missing");
- }
- String port = (String)cdmSourceProperties.get(CdmSourceProperties.PORT.toString());
- if(port == null || port.isEmpty()) {
- throw new CdmRemoteSourceException("Could not initialise remote source. Required property '" + CdmSourceProperties.SERVER.toString() + "' is missing");
- }
- if(!cdmSourceProperties.containsKey(CdmSourceProperties.CONTEXTPATH.toString())) {
- throw new CdmRemoteSourceException("Could not initialise remote source. Required property '" + CdmSourceProperties.SERVER.toString() + "' is missing");
- }
- // default NomenclaturalCode is always ICNAFP
- if(!cdmSourceProperties.containsKey(CdmSourceProperties.NOMENCLATURAL_CODE.toString())) {
- cdmSourceProperties.put(CdmSourceProperties.NOMENCLATURAL_CODE.toString(), NomenclaturalCode.ICNAFP.name());
- }
- }
-
- /* (non-Javadoc)
- * @see eu.etaxonomy.cdm.config.ICdmPersistentSource#getBeanName()
- */
- @Override
- public String getBeanName() {
- return beanName;
- }
-
- @Override
- public String getServer() {
- return cdmSourceProperties.getProperty(CdmSourceProperties.SERVER.toString());
- }
-
- @Override
- public int getPort() {
- String port = CdmUtils.Nz(cdmSourceProperties.getProperty(CdmSourceProperties.PORT.toString()));
- if (port == null || "".equals(port)){
- return -1;
- }else{
- //TODO exception if non integer
- return Integer.valueOf(port);
- }
- }
-
- @Override
- public String getContextPath() {
- return cdmSourceProperties.getProperty(CdmSourceProperties.CONTEXTPATH.toString());
- }
-
- @Override
- public NomenclaturalCode getNomenclaturalCode() {
- return NomenclaturalCode.fromString(cdmSourceProperties.getProperty(CdmSourceProperties.NOMENCLATURAL_CODE.toString()));
- }
-
- public static CdmPersistentRemoteSource save(String strRemoteSourceName, ICdmRemoteSource remoteSource) throws CdmRemoteSourceException {
- Properties cdmSourceProperties = new Properties();
- cdmSourceProperties.put(CdmSourceProperties.SERVER.toString(), remoteSource.getServer());
- cdmSourceProperties.put(CdmSourceProperties.PORT.toString(), String.valueOf(remoteSource.getPort()));
- cdmSourceProperties.put(CdmSourceProperties.CONTEXTPATH.toString(), remoteSource.getContextPath());
- cdmSourceProperties.put(CdmSourceProperties.NOMENCLATURAL_CODE.toString(), remoteSource.getNomenclaturalCode().name());
- checkProperties(cdmSourceProperties);
- return save(strRemoteSourceName, cdmSourceProperties);
- }
-
- private static CdmPersistentRemoteSource save(String strRemoteSourceName,Properties cdmSourceProperties) throws CdmRemoteSourceException {
-
- //root
- Element root = getBeansRoot(CdmPersistentSourceUtils.getCdmSourceInputStream());
- if (root == null){
- return null;
- }
- //bean
- Element bean = XmlHelp.getFirstAttributedChild(root, "bean", "id", CdmPersistentSourceUtils.getBeanName(strRemoteSourceName, REMOTESOURCE_BEAN_POSTFIX));
- if (bean != null){
- bean.detach(); //delete old version if necessary
- }
- bean = insertXmlBean(root, CdmPersistentSourceUtils.getBeanName(strRemoteSourceName, REMOTESOURCE_BEAN_POSTFIX), CdmPersistentRemoteSource.class.getName());
-
-
- Properties props = cdmSourceProperties;
- Enumeration e = props.propertyNames();
-
- while (e.hasMoreElements()) {
- String key = (String) e.nextElement();
- insertXmlValueProperty(bean, key, props.getProperty(key));
- }
-
- //save
- saveToXml(root.getDocument(),
- CdmPersistentSourceUtils.getResourceDirectory(),
- CdmPersistentXMLSource.CDMSOURCE_FILE_NAME,
- XmlHelp.prettyFormat );
-
- return NewInstance(strRemoteSourceName) ;
-
- }
-
- /**
- * @param strDataSourceName
- * @param dataSource
- * @param code
- * @return
- * the updated dataSource, null if not succesful
- */
- public static CdmPersistentRemoteSource update(String strRemoteSourceName,
- ICdmRemoteSource remoteSource) throws CdmRemoteSourceException {
- CdmPersistentSourceUtils.delete(CdmPersistentSourceUtils.getBeanName(strRemoteSourceName,REMOTESOURCE_BEAN_POSTFIX));
- return save(strRemoteSourceName, remoteSource);
- }
-
- /**
- * Tests existing of the datsource in the according config file.
- * @return true if a datasource with the given name exists in the according datasource config file.
- */
- public static boolean exists(String strRemoteSourceName){
- Element bean = CdmPersistentSourceUtils.getCdmSourceBeanXml(strRemoteSourceName, REMOTESOURCE_BEAN_POSTFIX);
- return (bean != null);
- }
-
- /**
- * Returns a list of all datasources stored in the datasource config file
- * @return all existing data sources
- * @throws CdmRemoteSourceException
- */
- @SuppressWarnings("unchecked")
- static public List<CdmPersistentRemoteSource> getAllRemoteSources() throws CdmRemoteSourceException{
- List<CdmPersistentRemoteSource> remoteSources = new ArrayList<CdmPersistentRemoteSource>();
-
- Element root = getBeansRoot(CdmPersistentSourceUtils.getCdmSourceInputStream());
- if (root == null){
- return null;
- }else{
- List<Element> lsChildren = root.getChildren("bean", root.getNamespace());
-
- for (Element elBean : lsChildren){
- String strId = elBean.getAttributeValue("id");
- if (strId != null && strId.endsWith(REMOTESOURCE_BEAN_POSTFIX)){
- strId = strId.replace(REMOTESOURCE_BEAN_POSTFIX, "");
- remoteSources.add(new CdmPersistentRemoteSource(strId));
- }
- }
- }
- return remoteSources;
- }
-
- @Override
- public String toString(){
- if (getName() != null){
- return getName();
- }else{
- return null;
- }
- }
-
-}
+++ /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.cdm.remote;
-
-import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
-
-/**
- * Class representing a CDM remote source
- *
- */
-public class CdmRemoteSource extends CdmRemoteSourceBase {
-
- /**
- * Creates a new instance of CdmRemoteSource
- *
- * @param name
- * @param server
- * @param port
- * @param contextPath
- * @param nomenclaturalCode
- * @return
- */
- public static CdmRemoteSource NewInstance() {
- return new CdmRemoteSource(DEFAULT_NAME, DEFAULT_SERVER, DEFAULT_PORT, DEFAULT_CONTEXT_PATH, DEFAULT_NOMENCLATURAL_CODE);
- }
-
- /**
- * Creates a new instance of CdmRemoteSource
- *
- * @param name
- * @param server
- * @param port
- * @param contextPath
- * @param nomenclaturalCode
- * @return
- */
- public static CdmRemoteSource NewInstance(String name, String server, int port, String contextPath, NomenclaturalCode nomenclaturalCode) {
- return new CdmRemoteSource(name, server, port, contextPath, nomenclaturalCode);
- }
-
- /**
- * Creates a new CdmRemoteSource
- *
- * @param name
- * @param server
- * @param port
- * @param contextPath
- * @param nomenclaturalCode
- */
- private CdmRemoteSource(String name, String server, int port, String contextPath, NomenclaturalCode nomenclaturalCode) {
- super(name, server, port, contextPath, nomenclaturalCode);
-
- }
-
-
-}
+++ /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.cdm.remote;
-
-import java.util.Map;
-
-import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean;
-
-import eu.etaxonomy.cdm.api.service.IDatabaseService;
-import eu.etaxonomy.cdm.config.CdmSource;
-import eu.etaxonomy.cdm.config.CdmSourceException;
-import eu.etaxonomy.cdm.database.DatabaseTypeEnum;
-import eu.etaxonomy.cdm.model.metadata.CdmMetaData.MetaDataPropertyName;
-import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
-
-/**
- * Base class representing a CDM remote source.
- * This class handles all the configuration relating to the remoting aspect of
- * a CDM source.
- *
- */
-public class CdmRemoteSourceBase extends CdmSource implements ICdmRemoteSource {
-
- protected static final String DEFAULT_NAME = "default";
- protected static final String DEFAULT_SERVER = "127.0.0.1";
- protected static final int DEFAULT_PORT = 8080;
- protected static final String DEFAULT_CONTEXT_PATH = "";
- protected static final NomenclaturalCode DEFAULT_NOMENCLATURAL_CODE = NomenclaturalCode.ICNAFP;
- private String contextPath;
- private String baseUrl;
-
- private IDatabaseService databaseService;
-
- /**
- * Constructs a CdmRemoteSourceBase object with default values.
- *
- */
- protected CdmRemoteSourceBase() {
- setName(DEFAULT_NAME);
- setServer(DEFAULT_SERVER);
- setPort(DEFAULT_PORT);
- setContextPath(DEFAULT_CONTEXT_PATH);
- setNomenclaturalCode(DEFAULT_NOMENCLATURAL_CODE);
- }
-
- /**
- * Constructs a CdmRemoteSourceBase
- *
- * @param name
- * @param server
- * @param port
- * @param contextPath
- * @param nomenclaturalCode
- */
- protected CdmRemoteSourceBase(String name, String server, int port, String contextPath, NomenclaturalCode nomenclaturalCode) {
- setName(name);
- setServer(server);
- setPort(port);
- setContextPath(contextPath);
- setNomenclaturalCode(nomenclaturalCode);
- initDatabaseConnection();
- }
-
- protected void initDatabaseConnection() {
- if(getContextPath() == null || getContextPath().equals("")) {
- setBaseUrl("http://" + getServer() + ":" + String.valueOf(getPort()));
- } else {
- setBaseUrl("http://" + getServer() + ":" + String.valueOf(getPort()) + "/" + getContextPath());
- }
- // the database service needs to be initialised (before the spring
- // application context initialsation) since it is required to
- // to make queries related to the source database
- HttpInvokerProxyFactoryBean proxy = new HttpInvokerProxyFactoryBean();
- proxy.setServiceInterface(IDatabaseService.class);
- proxy.setServiceUrl(baseUrl + "/remoting/database.service");
- proxy.afterPropertiesSet();
- databaseService = (IDatabaseService) proxy.getObject();
-
- }
-
- /* (non-Javadoc)
- * @see eu.etaxonomy.cdm.remote.ICdmRemoteSource#getBaseUrl()
- */
- @Override
- public String getBaseUrl() {
- return baseUrl;
- }
-
- /**
- * Sets the base url for the http-invoker services as listed in
- * httpInvokerServicesClients.xml.
- * e.g. for 'http://127.0.0.1:8080/col/remoting/common.service', the
- * base url would be 'http://127.0.0.1:8080/col'
- *
- * @param baseUrl
- */
- public void setBaseUrl(String baseUrl) {
- this.baseUrl = baseUrl;
- }
-
- /* (non-Javadoc)
- * @see eu.etaxonomy.cdm.remote.ICdmRemoteSource#getContextPath()
- */
- @Override
- public String getContextPath() {
- return contextPath;
- }
-
- /**
- * Sets the context path.
- * e.g. for 'http://127.0.0.1:8080/col/remoting/common.service', the
- * context path would be 'col'
- *
- * @param contextPath
- */
- public void setContextPath(String contextPath) {
- this.contextPath = contextPath;
- }
-
- /* (non-Javadoc)
- * @see eu.etaxonomy.cdm.config.CdmSource#getDbSchemaVersion()
- */
- @Override
- public String getDbSchemaVersion() throws CdmSourceException {
- return databaseService.getDbSchemaVersion();
-
- }
-
- /* (non-Javadoc)
- * @see eu.etaxonomy.cdm.config.CdmSource#isDbEmpty()
- */
- @Override
- public boolean isDbEmpty() throws CdmSourceException {
- return databaseService.isDbEmpty();
-
- }
-
- /* (non-Javadoc)
- * @see eu.etaxonomy.cdm.config.CdmSource#checkConnection()
- */
- @Override
- public boolean checkConnection() throws CdmSourceException {
- // assuming that database service works implies
- // the connection is up
- // if no exception is thrown then we assume that the
- // connection is up
- // FIXME:Remoting is this really correct?
- databaseService.getDbSchemaVersion();
-
- return true;
- }
-
- /* (non-Javadoc)
- * @see eu.etaxonomy.cdm.config.CdmSource#getConnectionMessage()
- */
- @Override
- public String getConnectionMessage() {
- return "Conncting to Remote CDM Server " + getName();
- }
-
-
- @Override
- public Map<MetaDataPropertyName, String> getMetaDataMap() throws CdmSourceException {
- return databaseService.getCdmMetadataMap();
- }
-
-
-}
+++ /dev/null
-/**
- *
- */
-package eu.etaxonomy.cdm.remote;
-
-/**
- *
- *
- */
-public class CdmRemoteSourceException extends Exception {
-
- public CdmRemoteSourceException(String message) {
- super(message);
- }
-
- public CdmRemoteSourceException(Exception e) {
- super(e);
- }
-}
+++ /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.cdm.remote;
-
-import eu.etaxonomy.cdm.config.ICdmSource;
-
-/**
- * Interface representing a CDM remote source
- *
- */
-public interface ICdmRemoteSource extends ICdmSource {
-
- /**
- * Gets the context path.
- * e.g. for 'http://127.0.0.1:8080/col/remoting/common.service', the
- * context path would be 'col'
- */
- public String getContextPath();
-
- /**
- * Gets the base url for the http-invoker services as listed in
- * httpInvokerServicesClients.xml.
- * e.g. for 'http://127.0.0.1:8080/col/remoting/common.service', the
- * base url would be 'http://127.0.0.1:8080/col'
- */
- public String getBaseUrl();
-
-}
+++ /dev/null
-
-
-/*
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
- * indicated by the @author tags or express copyright attribution
- * statements applied by the authors. All third-party contributions are
- * distributed under license by Red Hat Inc.
- *
- * This copyrighted material is made available to anyone wishing to use, modify,
- * copy, or redistribute it subject to the terms and conditions of the GNU
- * Lesser General Public License, as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
- * for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this distribution; if not, write to:
- * Free Software Foundation, Inc.
- * 51 Franklin Street, Fifth Floor
- * Boston, MA 02110-1301 USA
- */
-package org.hibernate.collection.internal;
-
-import java.io.Serializable;
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.TreeSet;
-
-import javax.naming.NamingException;
-
-import org.hibernate.AssertionFailure;
-import org.hibernate.HibernateException;
-import org.hibernate.LazyInitializationException;
-import org.hibernate.Session;
-import org.hibernate.collection.spi.PersistentCollection;
-import org.hibernate.engine.internal.ForeignKeys;
-import org.hibernate.engine.spi.CollectionEntry;
-import org.hibernate.engine.spi.EntityEntry;
-import org.hibernate.engine.spi.SessionFactoryImplementor;
-import org.hibernate.engine.spi.SessionImplementor;
-import org.hibernate.engine.spi.Status;
-import org.hibernate.engine.spi.TypedValue;
-import org.hibernate.internal.SessionFactoryRegistry;
-import org.hibernate.internal.util.MarkerObject;
-import org.hibernate.internal.util.collections.EmptyIterator;
-import org.hibernate.internal.util.collections.IdentitySet;
-import org.hibernate.persister.collection.CollectionPersister;
-import org.hibernate.persister.entity.EntityPersister;
-import org.hibernate.pretty.MessageHelper;
-import org.hibernate.type.Type;
-import org.jboss.logging.Logger;
-
-import eu.etaxonomy.cdm.api.application.CdmApplicationRemoteController;
-import eu.etaxonomy.cdm.api.application.ICdmApplicationConfiguration;
-import eu.etaxonomy.cdm.api.service.ICommonService;
-import eu.etaxonomy.cdm.model.common.PersistentMultiLanguageText;
-
-/**
- * Base class implementing {@link org.hibernate.collection.spi.PersistentCollection}
- *
- * @author Gavin King
- */
-public abstract class AbstractPersistentCollection implements Serializable, PersistentCollection {
- private static final Logger log = Logger.getLogger( AbstractPersistentCollection.class );
-
- private static final long serialVersionUID = -7238232378593030571L;
-
- private transient SessionImplementor session;
- private boolean initialized;
- private transient List<DelayedOperation> operationQueue;
- private transient boolean directlyAccessible;
- private transient boolean initializing;
- private Object owner;
- private int cachedSize = -1;
-
- private String role;
- private Serializable key;
- // collections detect changes made via their public interface and mark
- // themselves as dirty as a performance optimization
- private boolean dirty;
- private Serializable storedSnapshot;
-
- private String sessionFactoryUuid;
- private boolean specjLazyLoad = false;
-
- public final String getRole() {
- return role;
- }
-
- public final Serializable getKey() {
- return key;
- }
-
- public final boolean isUnreferenced() {
- return role == null;
- }
-
- public final boolean isDirty() {
- return dirty;
- }
-
- public final void clearDirty() {
- dirty = false;
- }
-
- public final void dirty() {
- dirty = true;
- }
-
- public final Serializable getStoredSnapshot() {
- return storedSnapshot;
- }
-
- //Careful: these methods do not initialize the collection.
-
- /**
- * Is the initialized collection empty?
- */
- public abstract boolean empty();
-
- /**
- * Called by any read-only method of the collection interface
- */
- protected final void read() {
- initialize( false );
- }
-
- /**
- * Called by the {@link Collection#size} method
- */
- @SuppressWarnings({"JavaDoc"})
- protected boolean readSize() {
- if ( !initialized ) {
- if ( cachedSize != -1 && !hasQueuedOperations() ) {
- return true;
- }
- else {
- // In remoting we are sure that session is null
- // both when using property paths and switching off conversations
- if(session == null && remoting) {
- log.info("--> readSize, of " + getRole() + " with key " + getKey());
- read();
- } else {
- boolean isExtraLazy = withTemporarySessionIfNeeded(
- new LazyInitializationWork<Boolean>() {
- @Override
- public Boolean doWork() {
- CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
-
- if ( entry != null ) {
- CollectionPersister persister = entry.getLoadedPersister();
- if ( persister.isExtraLazy() ) {
- if ( hasQueuedOperations() ) {
- session.flush();
- }
- cachedSize = persister.getSize( entry.getLoadedKey(), session );
- return true;
- }
- else {
- read();
- }
- }
- else{
- throwLazyInitializationExceptionIfNotConnected();
- }
- return false;
- }
- }
- );
- if ( isExtraLazy ) {
- return true;
- }
- }
- }
- }
- return false;
- }
-
- public static interface LazyInitializationWork<T> {
- public T doWork();
- }
-
- private <T> T withTemporarySessionIfNeeded(LazyInitializationWork<T> lazyInitializationWork) {
- SessionImplementor originalSession = null;
- boolean isTempSession = false;
- boolean isJTA = false;
-
- if ( session == null ) {
- if ( specjLazyLoad ) {
- session = openTemporarySessionForLoading();
- isTempSession = true;
- }
- else {
- throwLazyInitializationException( "could not initialize proxy - no Session" );
- }
- }
- else if ( !session.isOpen() ) {
- if ( specjLazyLoad ) {
- originalSession = session;
- session = openTemporarySessionForLoading();
- isTempSession = true;
- }
- else {
- throwLazyInitializationException( "could not initialize proxy - the owning Session was closed" );
- }
- }
- else if ( !session.isConnected() ) {
- if ( specjLazyLoad ) {
- originalSession = session;
- session = openTemporarySessionForLoading();
- isTempSession = true;
- }
- else {
- throwLazyInitializationException( "could not initialize proxy - the owning Session is disconnected" );
- }
- }
-
- if ( isTempSession ) {
- // TODO: On the next major release, add an
- // 'isJTA' or 'getTransactionFactory' method to Session.
- isJTA = session.getTransactionCoordinator()
- .getTransactionContext().getTransactionEnvironment()
- .getTransactionFactory()
- .compatibleWithJtaSynchronization();
-
- if ( !isJTA ) {
- // Explicitly handle the transactions only if we're not in
- // a JTA environment. A lazy loading temporary session can
- // be created even if a current session and transaction are
- // open (ex: session.clear() was used). We must prevent
- // multiple transactions.
- ( ( Session) session ).beginTransaction();
- }
-
- session.getPersistenceContext().addUninitializedDetachedCollection(
- session.getFactory().getCollectionPersister( getRole() ),
- this
- );
- }
-
- try {
- return lazyInitializationWork.doWork();
- }
- finally {
- if ( isTempSession ) {
- // make sure the just opened temp session gets closed!
- try {
- if ( !isJTA ) {
- ( ( Session) session ).getTransaction().commit();
- }
- ( (Session) session ).close();
- }
- catch (Exception e) {
- log.warn( "Unable to close temporary session used to load lazy collection associated to no session" );
- }
- session = originalSession;
- }
- }
- }
-
- private SessionImplementor openTemporarySessionForLoading() {
- if ( sessionFactoryUuid == null ) {
- throwLazyInitializationException( "SessionFactory UUID not known to create temporary Session for loading" );
- }
-
- SessionFactoryImplementor sf = (SessionFactoryImplementor)
- SessionFactoryRegistry.INSTANCE.getSessionFactory( sessionFactoryUuid );
- return (SessionImplementor) sf.openSession();
- }
-
- protected Boolean readIndexExistence(final Object index) {
- if ( !initialized ) {
- // In remoting we are sure that session is null
- // both when using property paths and switching off conversations
- if(session == null && remoting) {
- log.info("--> readIndexExistence, of " + getRole() + " with key " + getKey());
- read();
- } else {
- Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded(
- new LazyInitializationWork<Boolean>() {
- @Override
- public Boolean doWork() {
- CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
- CollectionPersister persister = entry.getLoadedPersister();
- if ( persister.isExtraLazy() ) {
- if ( hasQueuedOperations() ) {
- session.flush();
- }
- return persister.indexExists( entry.getLoadedKey(), index, session );
- }
- else {
- read();
- }
- return null;
- }
- }
- );
- if ( extraLazyExistenceCheck != null ) {
- return extraLazyExistenceCheck;
- }
- }
- }
- return null;
- }
-
- protected Boolean readElementExistence(final Object element) {
- if ( !initialized ) {
- // In remoting we are sure that session is null
- // both when using property paths and switching off conversations
- if(session == null && remoting) {
- log.info("--> readElementExistence, of " + getRole() + " with key " + getKey());
- read();
-
- } else {
- Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded(
- new LazyInitializationWork<Boolean>() {
- @Override
- public Boolean doWork() {
- CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
- CollectionPersister persister = entry.getLoadedPersister();
- if ( persister.isExtraLazy() ) {
- if ( hasQueuedOperations() ) {
- session.flush();
- }
- return persister.elementExists( entry.getLoadedKey(), element, session );
- }
- else {
- read();
- }
- return null;
- }
- }
- );
- if ( extraLazyExistenceCheck != null ) {
- return extraLazyExistenceCheck;
- }
- }
- }
- return null;
- }
-
- protected static final Object UNKNOWN = new MarkerObject( "UNKNOWN" );
-
- protected Object readElementByIndex(final Object index) {
- if ( !initialized ) {
- // In remoting we are sure that session is null
- // both when using property paths and switching off conversations
- if(session == null && remoting) {
- log.info("--> readElementByIndex, of " + getRole() + " with key " + getKey());
- read();
-
- } else {
- class ExtraLazyElementByIndexReader implements LazyInitializationWork {
- private boolean isExtraLazy;
- private Object element;
-
- @Override
- public Object doWork() {
- CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
- CollectionPersister persister = entry.getLoadedPersister();
- isExtraLazy = persister.isExtraLazy();
- if ( isExtraLazy ) {
- if ( hasQueuedOperations() ) {
- session.flush();
- }
- element = persister.getElementByIndex( entry.getLoadedKey(), index, session, owner );
- }
- else {
- read();
- }
- return null;
- }
- }
-
- ExtraLazyElementByIndexReader reader = new ExtraLazyElementByIndexReader();
- //noinspection unchecked
- withTemporarySessionIfNeeded( reader );
- if ( reader.isExtraLazy ) {
- return reader.element;
- }
- }
- }
- return UNKNOWN;
-
- }
-
- protected int getCachedSize() {
- return cachedSize;
- }
-
- private boolean isConnectedToSession() {
- return session != null &&
- session.isOpen() &&
- session.getPersistenceContext().containsCollection( this );
- }
-
- /**
- * Called by any writer method of the collection interface
- */
- protected final void write() {
- initialize( true );
- dirty();
- }
-
- /**
- * Is this collection in a state that would allow us to
- * "queue" operations?
- */
- @SuppressWarnings({"JavaDoc"})
- protected boolean isOperationQueueEnabled() {
- return !initialized &&
- isConnectedToSession() &&
- isInverseCollection();
- }
-
- /**
- * Is this collection in a state that would allow us to
- * "queue" puts? This is a special case, because of orphan
- * delete.
- */
- @SuppressWarnings({"JavaDoc"})
- protected boolean isPutQueueEnabled() {
- return !initialized &&
- isConnectedToSession() &&
- isInverseOneToManyOrNoOrphanDelete();
- }
-
- /**
- * Is this collection in a state that would allow us to
- * "queue" clear? This is a special case, because of orphan
- * delete.
- */
- @SuppressWarnings({"JavaDoc"})
- protected boolean isClearQueueEnabled() {
- return !initialized &&
- isConnectedToSession() &&
- isInverseCollectionNoOrphanDelete();
- }
-
- /**
- * Is this the "inverse" end of a bidirectional association?
- */
- @SuppressWarnings({"JavaDoc"})
- private boolean isInverseCollection() {
- CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
- return ce != null && ce.getLoadedPersister().isInverse();
- }
-
- /**
- * Is this the "inverse" end of a bidirectional association with
- * no orphan delete enabled?
- */
- @SuppressWarnings({"JavaDoc"})
- private boolean isInverseCollectionNoOrphanDelete() {
- CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
- return ce != null &&
- ce.getLoadedPersister().isInverse() &&
- !ce.getLoadedPersister().hasOrphanDelete();
- }
-
- /**
- * Is this the "inverse" end of a bidirectional one-to-many, or
- * of a collection with no orphan delete?
- */
- @SuppressWarnings({"JavaDoc"})
- private boolean isInverseOneToManyOrNoOrphanDelete() {
- CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
- return ce != null && ce.getLoadedPersister().isInverse() && (
- ce.getLoadedPersister().isOneToMany() ||
- !ce.getLoadedPersister().hasOrphanDelete()
- );
- }
-
- /**
- * Queue an addition
- */
- @SuppressWarnings({"JavaDoc"})
- protected final void queueOperation(DelayedOperation operation) {
- if ( operationQueue == null ) {
- operationQueue = new ArrayList<DelayedOperation>( 10 );
- }
- operationQueue.add( operation );
- dirty = true; //needed so that we remove this collection from the second-level cache
- }
-
- /**
- * After reading all existing elements from the database,
- * add the queued elements to the underlying collection.
- */
- protected final void performQueuedOperations() {
- for ( DelayedOperation operation : operationQueue ) {
- operation.operate();
- }
- }
-
- /**
- * After flushing, re-init snapshot state.
- */
- public void setSnapshot(Serializable key, String role, Serializable snapshot) {
- this.key = key;
- this.role = role;
- this.storedSnapshot = snapshot;
- }
-
- /**
- * After flushing, clear any "queued" additions, since the
- * database state is now synchronized with the memory state.
- */
- public void postAction() {
- operationQueue = null;
- cachedSize = -1;
- clearDirty();
- }
-
- /**
- * Not called by Hibernate, but used by non-JDK serialization,
- * eg. SOAP libraries.
- */
- public AbstractPersistentCollection() {
- }
-
- protected AbstractPersistentCollection(SessionImplementor session) {
- this.session = session;
- }
-
- /**
- * return the user-visible collection (or array) instance
- */
- public Object getValue() {
- return this;
- }
-
- /**
- * Called just before reading any rows from the JDBC result set
- */
- public void beginRead() {
- // override on some subclasses
- initializing = true;
- }
-
- /**
- * Called after reading all rows from the JDBC result set
- */
- public boolean endRead() {
- //override on some subclasses
- return afterInitialize();
- }
-
- public boolean afterInitialize() {
- setInitialized();
- //do this bit after setting initialized to true or it will recurse
- if ( operationQueue != null ) {
- performQueuedOperations();
- operationQueue = null;
- cachedSize = -1;
- return false;
- }
- else {
- return true;
- }
- }
-
- /**
- * Initialize the collection, if possible, wrapping any exceptions
- * in a runtime exception
- *
- * @param writing currently obsolete
- *
- * @throws LazyInitializationException if we cannot initialize
- */
- protected final void initialize(final boolean writing) {
- // In remoting we are sure that session is null
- // both when using property paths and switching off conversations
- if(session == null && remoting) {
- remoteInitialize();
- }
-
- if ( initialized ) {
- return;
- }
-
-
- withTemporarySessionIfNeeded(
- new LazyInitializationWork<Object>() {
- @Override
- public Object doWork() {
- session.initializeCollection( AbstractPersistentCollection.this, writing );
- return null;
- }
- }
- );
- }
-
- private void throwLazyInitializationExceptionIfNotConnected() {
- if ( !isConnectedToSession() ) {
- throwLazyInitializationException( "no session or session was closed" );
- }
- if ( !session.isConnected() ) {
- throwLazyInitializationException( "session is disconnected" );
- }
- }
-
- private void throwLazyInitializationException(String message) {
- throw new LazyInitializationException(
- "failed to lazily initialize a collection" +
- (role == null ? "" : " of role: " + role) +
- ", " + message
- );
- }
-
- protected final void setInitialized() {
- this.initializing = false;
- this.initialized = true;
- }
-
- protected final void setDirectlyAccessible(boolean directlyAccessible) {
- this.directlyAccessible = directlyAccessible;
- }
-
- /**
- * Could the application possibly have a direct reference to
- * the underlying collection implementation?
- */
- public boolean isDirectlyAccessible() {
- return directlyAccessible;
- }
-
- /**
- * Disassociate this collection from the given session.
- *
- * @return true if this was currently associated with the given session
- */
- public final boolean unsetSession(SessionImplementor currentSession) {
- prepareForPossibleSpecialSpecjInitialization();
- if ( currentSession == this.session ) {
- this.session = null;
- return true;
- }
- else {
- return false;
- }
- }
-
- protected void prepareForPossibleSpecialSpecjInitialization() {
- if ( session != null ) {
- specjLazyLoad = session.getFactory().getSettings().isInitializeLazyStateOutsideTransactionsEnabled();
-
- if ( specjLazyLoad && sessionFactoryUuid == null ) {
- try {
- sessionFactoryUuid = (String) session.getFactory().getReference().get( "uuid" ).getContent();
- }
- catch (NamingException e) {
- //not much we can do if this fails...
- }
- }
- }
- }
-
-
- /**
- * Associate the collection with the given session.
- *
- * @return false if the collection was already associated with the session
- *
- * @throws HibernateException if the collection was already associated
- * with another open session
- */
- public final boolean setCurrentSession(SessionImplementor session) throws HibernateException {
- if ( session == this.session ) {
- return false;
- }
- else {
- if ( isConnectedToSession() ) {
- CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
- if ( ce == null ) {
- throw new HibernateException(
- "Illegal attempt to associate a collection with two open sessions"
- );
- }
- else {
- throw new HibernateException(
- "Illegal attempt to associate a collection with two open sessions: " +
- MessageHelper.collectionInfoString(
- ce.getLoadedPersister(), this,
- ce.getLoadedKey(), session
- )
- );
- }
- }
- else {
- this.session = session;
- return true;
- }
- }
- }
-
- /**
- * Do we need to completely recreate this collection when it changes?
- */
- public boolean needsRecreate(CollectionPersister persister) {
- return false;
- }
-
- /**
- * To be called internally by the session, forcing
- * immediate initialization.
- */
- public final void forceInitialization() throws HibernateException {
- if ( !initialized ) {
- if ( initializing ) {
- throw new AssertionFailure( "force initialize loading collection" );
- }
- if ( session == null ) {
- throw new HibernateException( "collection is not associated with any session" );
- }
- if ( !session.isConnected() ) {
- throw new HibernateException( "disconnected session" );
- }
- session.initializeCollection( this, false );
- }
- }
-
-
- /**
- * Get the current snapshot from the session
- */
- @SuppressWarnings({"JavaDoc"})
- protected final Serializable getSnapshot() {
- return session.getPersistenceContext().getSnapshot( this );
- }
-
- /**
- * Is this instance initialized?
- */
- public final boolean wasInitialized() {
- return initialized;
- }
-
- public boolean isRowUpdatePossible() {
- return true;
- }
-
- /**
- * Does this instance have any "queued" additions?
- */
- public final boolean hasQueuedOperations() {
- return operationQueue != null;
- }
-
- /**
- * Iterate the "queued" additions
- */
- public final Iterator queuedAdditionIterator() {
- if ( hasQueuedOperations() ) {
- return new Iterator() {
- int i = 0;
-
- public Object next() {
- return operationQueue.get( i++ ).getAddedInstance();
- }
-
- public boolean hasNext() {
- return i < operationQueue.size();
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
- };
- }
- else {
- return EmptyIterator.INSTANCE;
- }
- }
-
- /**
- * Iterate the "queued" additions
- */
- @SuppressWarnings({"unchecked"})
- public final Collection getQueuedOrphans(String entityName) {
- if ( hasQueuedOperations() ) {
- Collection additions = new ArrayList( operationQueue.size() );
- Collection removals = new ArrayList( operationQueue.size() );
- for ( DelayedOperation operation : operationQueue ) {
- additions.add( operation.getAddedInstance() );
- removals.add( operation.getOrphan() );
- }
- return getOrphans( removals, additions, entityName, session );
- }
- else {
- return Collections.EMPTY_LIST;
- }
- }
-
- /**
- * Called before inserting rows, to ensure that any surrogate keys
- * are fully generated
- */
- public void preInsert(CollectionPersister persister) throws HibernateException {
- }
-
- /**
- * Called after inserting a row, to fetch the natively generated id
- */
- public void afterRowInsert(CollectionPersister persister, Object entry, int i) throws HibernateException {
- }
-
- /**
- * get all "orphaned" elements
- */
- public abstract Collection getOrphans(Serializable snapshot, String entityName) throws HibernateException;
-
- /**
- * Get the current session
- */
- @SuppressWarnings({"JavaDoc"})
- public final SessionImplementor getSession() {
- return session;
- }
-
- protected final class IteratorProxy implements Iterator {
- protected final Iterator itr;
-
- public IteratorProxy(Iterator itr) {
- this.itr = itr;
- }
-
- public boolean hasNext() {
- return itr.hasNext();
- }
-
- public Object next() {
- return itr.next();
- }
-
- public void remove() {
- write();
- itr.remove();
- }
-
- }
-
- protected final class ListIteratorProxy implements ListIterator {
- protected final ListIterator itr;
-
- public ListIteratorProxy(ListIterator itr) {
- this.itr = itr;
- }
-
- @SuppressWarnings({"unchecked"})
- public void add(Object o) {
- write();
- itr.add( o );
- }
-
- public boolean hasNext() {
- return itr.hasNext();
- }
-
- public boolean hasPrevious() {
- return itr.hasPrevious();
- }
-
- public Object next() {
- return itr.next();
- }
-
- public int nextIndex() {
- return itr.nextIndex();
- }
-
- public Object previous() {
- return itr.previous();
- }
-
- public int previousIndex() {
- return itr.previousIndex();
- }
-
- public void remove() {
- write();
- itr.remove();
- }
-
- @SuppressWarnings({"unchecked"})
- public void set(Object o) {
- write();
- itr.set( o );
- }
-
- }
-
- protected class SetProxy implements java.util.Set {
- protected final Collection set;
-
- public SetProxy(Collection set) {
- this.set = set;
- }
-
- @SuppressWarnings({"unchecked"})
- public boolean add(Object o) {
- write();
- return set.add( o );
- }
-
- @SuppressWarnings({"unchecked"})
- public boolean addAll(Collection c) {
- write();
- return set.addAll( c );
- }
-
- public void clear() {
- write();
- set.clear();
- }
-
- public boolean contains(Object o) {
- return set.contains( o );
- }
-
- public boolean containsAll(Collection c) {
- return set.containsAll( c );
- }
-
- public boolean isEmpty() {
- return set.isEmpty();
- }
-
- public Iterator iterator() {
- return new IteratorProxy( set.iterator() );
- }
-
- public boolean remove(Object o) {
- write();
- return set.remove( o );
- }
-
- public boolean removeAll(Collection c) {
- write();
- return set.removeAll( c );
- }
-
- public boolean retainAll(Collection c) {
- write();
- return set.retainAll( c );
- }
-
- public int size() {
- return set.size();
- }
-
- public Object[] toArray() {
- return set.toArray();
- }
-
- @SuppressWarnings({"unchecked"})
- public Object[] toArray(Object[] array) {
- return set.toArray( array );
- }
-
- }
-
- protected final class ListProxy implements java.util.List {
- protected final List list;
-
- public ListProxy(List list) {
- this.list = list;
- }
-
- @Override
- @SuppressWarnings({"unchecked"})
- public void add(int index, Object value) {
- write();
- list.add( index, value );
- }
-
- @Override
- @SuppressWarnings({"unchecked"})
- public boolean add(Object o) {
- write();
- return list.add( o );
- }
-
- @Override
- @SuppressWarnings({"unchecked"})
- public boolean addAll(Collection c) {
- write();
- return list.addAll( c );
- }
-
- @Override
- @SuppressWarnings({"unchecked"})
- public boolean addAll(int i, Collection c) {
- write();
- return list.addAll( i, c );
- }
-
- @Override
- public void clear() {
- write();
- list.clear();
- }
-
- @Override
- public boolean contains(Object o) {
- return list.contains( o );
- }
-
- @Override
- public boolean containsAll(Collection c) {
- return list.containsAll( c );
- }
-
- @Override
- public Object get(int i) {
- return list.get( i );
- }
-
- @Override
- public int indexOf(Object o) {
- return list.indexOf( o );
- }
-
- @Override
- public boolean isEmpty() {
- return list.isEmpty();
- }
-
- @Override
- public Iterator iterator() {
- return new IteratorProxy( list.iterator() );
- }
-
- @Override
- public int lastIndexOf(Object o) {
- return list.lastIndexOf( o );
- }
-
- @Override
- public ListIterator listIterator() {
- return new ListIteratorProxy( list.listIterator() );
- }
-
- @Override
- public ListIterator listIterator(int i) {
- return new ListIteratorProxy( list.listIterator( i ) );
- }
-
- @Override
- public Object remove(int i) {
- write();
- return list.remove( i );
- }
-
- @Override
- public boolean remove(Object o) {
- write();
- return list.remove( o );
- }
-
- @Override
- public boolean removeAll(Collection c) {
- write();
- return list.removeAll( c );
- }
-
- @Override
- public boolean retainAll(Collection c) {
- write();
- return list.retainAll( c );
- }
-
- @Override
- @SuppressWarnings({"unchecked"})
- public Object set(int i, Object o) {
- write();
- return list.set( i, o );
- }
-
- @Override
- public int size() {
- return list.size();
- }
-
- @Override
- public List subList(int i, int j) {
- return list.subList( i, j );
- }
-
- @Override
- public Object[] toArray() {
- return list.toArray();
- }
-
- @Override
- @SuppressWarnings({"unchecked"})
- public Object[] toArray(Object[] array) {
- return list.toArray( array );
- }
-
- }
-
- /**
- * Contract for operations which are part of a collection's operation queue.
- */
- protected interface DelayedOperation {
- public void operate();
-
- public Object getAddedInstance();
-
- public Object getOrphan();
- }
-
- /**
- * Given a collection of entity instances that used to
- * belong to the collection, and a collection of instances
- * that currently belong, return a collection of orphans
- */
- @SuppressWarnings({"JavaDoc", "unchecked"})
- protected static Collection getOrphans(
- Collection oldElements,
- Collection currentElements,
- String entityName,
- SessionImplementor session) throws HibernateException {
-
- // short-circuit(s)
- if ( currentElements.size() == 0 ) {
- return oldElements; // no new elements, the old list contains only Orphans
- }
- if ( oldElements.size() == 0 ) {
- return oldElements; // no old elements, so no Orphans neither
- }
-
- final EntityPersister entityPersister = session.getFactory().getEntityPersister( entityName );
- final Type idType = entityPersister.getIdentifierType();
-
- // create the collection holding the Orphans
- Collection res = new ArrayList();
-
- // collect EntityIdentifier(s) of the *current* elements - add them into a HashSet for fast access
- java.util.Set currentIds = new HashSet();
- java.util.Set currentSaving = new IdentitySet();
- for ( Object current : currentElements ) {
- if ( current != null && ForeignKeys.isNotTransient( entityName, current, null, session ) ) {
- EntityEntry ee = session.getPersistenceContext().getEntry( current );
- if ( ee != null && ee.getStatus() == Status.SAVING ) {
- currentSaving.add( current );
- }
- else {
- Serializable currentId = ForeignKeys.getEntityIdentifierIfNotUnsaved(
- entityName,
- current,
- session
- );
- currentIds.add( new TypedValue( idType, currentId, entityPersister.getEntityMode() ) );
- }
- }
- }
-
- // iterate over the *old* list
- for ( Object old : oldElements ) {
- if ( !currentSaving.contains( old ) ) {
- Serializable oldId = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, old, session );
- if ( !currentIds.contains( new TypedValue( idType, oldId, entityPersister.getEntityMode() ) ) ) {
- res.add( old );
- }
- }
- }
-
- return res;
- }
-
- public static void identityRemove(
- Collection list,
- Object object,
- String entityName,
- SessionImplementor session) throws HibernateException {
-
- if ( object != null && ForeignKeys.isNotTransient( entityName, object, null, session ) ) {
- final EntityPersister entityPersister = session.getFactory().getEntityPersister( entityName );
- Type idType = entityPersister.getIdentifierType();
-
- Serializable idOfCurrent = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, object, session );
- Iterator itr = list.iterator();
- while ( itr.hasNext() ) {
- Serializable idOfOld = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, itr.next(), session );
- if ( idType.isEqual( idOfCurrent, idOfOld, session.getFactory() ) ) {
- itr.remove();
- break;
- }
- }
-
- }
- }
-
- public Object getIdentifier(Object entry, int i) {
- throw new UnsupportedOperationException();
- }
-
- public Object getOwner() {
- return owner;
- }
-
- public void setOwner(Object owner) {
- this.owner = owner;
- }
-
- /** ------ Below is section of code which makes remote service calls ----- */
- // The affected methods are :
- // initialize(final boolean writing)
- // readSize()
- // readIndexExistence(final Object index)
- // readElementExistence(final Object element)
- // readElementByIndex(final Object index)
-
- private static ICdmApplicationConfiguration configuration;
- private static boolean remoting = false;
-
- public static void setConfiguration(ICdmApplicationConfiguration conf) {
- configuration = conf;
-
- if(conf instanceof CdmApplicationRemoteController) {
- remoting = true;
- } else {
- remoting = false;
- }
- }
-
-
- private void remoteInitialize() {
-
- if (getOwner() != null && !initialized) {
-
- try {
- String role = getRole();
- String fieldName = role.substring(role.lastIndexOf(".") + 1);
- log.info("--> Remote Lazy Initializing " + getRole() + " , key : " + getKey() + " , field : " + fieldName);
- Object owner = getOwner();
-
- if(configuration == null) {
- throw new HibernateException("CdmApplicationRemoteConfiguration not initialized (null)");
- }
- ICommonService commonService = configuration.getCommonService();
- if(commonService == null) {
- throw new HibernateException("commonService not initialized (null)");
- }
-
- PersistentCollection col = commonService.initializeCollection(this);
- afterInitialize();
-
- Class<?> clazz = getClass();
- if (clazz != null) {
- CollectionField cf = getCollectionField(col);
- Field field = clazz.getDeclaredField(cf.getFieldName());
- field.setAccessible(true);
- field.set(this, cf.getCollection());
- }
- } catch (Exception ex) {
- log.warn(ex.getMessage());
- }
- }
- }
-
-
- private CollectionField getCollectionField(PersistentCollection pc) {
- if(pc != null) {
- if(pc instanceof PersistentSet) {
- return new CollectionField(new HashSet((Set)pc), "set");
- }
- if(pc instanceof PersistentSortedSet) {
- return new CollectionField(new TreeSet((Set)pc), "set");
- }
- if(pc instanceof PersistentList) {
- return new CollectionField(new ArrayList((List)pc), "list");
- }
- if(pc instanceof PersistentMap || pc instanceof PersistentMultiLanguageText) {
- return new CollectionField(new HashMap((Map)pc), "map");
- }
- if(pc instanceof PersistentSortedMap) {
- return new CollectionField(new TreeMap((Map)pc), "map");
- }
- }
- return null;
- }
-
- private String getCollectionFieldName(PersistentCollection pc) {
- if(pc != null) {
- if(pc instanceof PersistentSet || pc instanceof PersistentSortedSet) {
- return "set";
- }
- if(pc instanceof PersistentList) {
- return "list";
- }
- if(pc instanceof PersistentMap || pc instanceof PersistentMultiLanguageText) {
- return "map";
- }
- }
- return null;
- }
-
- private class CollectionField {
- private Object col;
- private String fieldName;
- public CollectionField(Object col, String fieldName) {
- this.col = col;
- this.fieldName = fieldName;
- }
-
- public Object getCollection() {
- return this.col;
- }
-
- public String getFieldName() {
- return this.fieldName;
- }
- }
-
- public static boolean isInitialized(List list) {
- return ((AbstractPersistentCollection)list).initialized;
- }
-
- public static boolean isInitialized(Map map) {
- return ((AbstractPersistentCollection)map).initialized;
- }
-
- public static boolean isInitialized(Set set) {
- return ((AbstractPersistentCollection)set).initialized;
- }
-
- //FIXME:Remoting These methods may no longer be required since we are
- // initialising collections as default behaviour
- private int remoteSize() {
- int size = configuration.getCommonService().size(this);
- log.debug("--> Remote Lazy Initializing size of " + getRole() + " to " + size);
- if(size == -1) {
- throw new HibernateException("size of " + getClass() + " could not be retrieved from remote service");
- }
- return size;
- }
-
- private Object remoteReadElementByIndex(int index) {
- Object element = configuration.getCommonService().get(this,index);
- log.debug("--> Remote Lazy Initializing element from " + getRole() + " at index " + index);
- return element;
- }
-
- private boolean remoteReadElementExistence(Object element) {
- return configuration.getCommonService().contains(this,element);
- }
-
- private boolean remoteReadIndexExistence(Object index) {
- return false;
- }
-}
-
+++ /dev/null
-/*
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
- * indicated by the @author tags or express copyright attribution
- * statements applied by the authors. All third-party contributions are
- * distributed under license by Red Hat Inc.
- *
- * This copyrighted material is made available to anyone wishing to use, modify,
- * copy, or redistribute it subject to the terms and conditions of the GNU
- * Lesser General Public License, as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
- * for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this distribution; if not, write to:
- * Free Software Foundation, Inc.
- * 51 Franklin Street, Fifth Floor
- * Boston, MA 02110-1301 USA
- */
-package org.hibernate.proxy;
-
-import java.io.Serializable;
-import java.util.Set;
-
-import javax.naming.NamingException;
-
-import org.hibernate.HibernateException;
-import org.hibernate.LazyInitializationException;
-import org.hibernate.Session;
-import org.hibernate.SessionException;
-import org.hibernate.TransientObjectException;
-import org.hibernate.collection.internal.AbstractPersistentCollection;
-import org.hibernate.engine.spi.EntityKey;
-import org.hibernate.engine.spi.SessionFactoryImplementor;
-import org.hibernate.engine.spi.SessionImplementor;
-import org.hibernate.internal.SessionFactoryRegistry;
-import org.hibernate.persister.entity.EntityPersister;
-import org.jboss.logging.Logger;
-import org.springframework.beans.factory.annotation.Autowire;
-import org.springframework.beans.factory.annotation.Configurable;
-import org.springframework.stereotype.Component;
-
-import eu.etaxonomy.cdm.api.application.CdmApplicationRemoteController;
-import eu.etaxonomy.cdm.api.application.ICdmApplicationConfiguration;
-import eu.etaxonomy.cdm.api.service.ICommonService;
-import eu.etaxonomy.cdm.model.common.CdmBase;
-
-/**
- * Convenience base class for lazy initialization handlers. Centralizes the basic plumbing of doing lazy
- * initialization freeing subclasses to acts as essentially adapters to their intended entity mode and/or
- * proxy generation strategy.
- *
- * @author Gavin King
- */
-@Component
-@Configurable(dependencyCheck = true,autowire = Autowire.BY_TYPE)
-public abstract class AbstractLazyInitializer implements LazyInitializer {
- private static final Logger log = Logger.getLogger( AbstractLazyInitializer.class );
-
- private String entityName;
- private Serializable id;
- private Object target;
- private boolean initialized;
- private boolean readOnly;
- private boolean unwrap;
- private transient SessionImplementor session;
- private Boolean readOnlyBeforeAttachedToSession;
-
- private String sessionFactoryUuid;
- private boolean specjLazyLoad = false;
-
- /**
- * For serialization from the non-pojo initializers (HHH-3309)
- */
- protected AbstractLazyInitializer() {
- }
-
- /**
- * Main constructor.
- *
- * @param entityName The name of the entity being proxied.
- * @param id The identifier of the entity being proxied.
- * @param session The session owning the proxy.
- */
- protected AbstractLazyInitializer(String entityName, Serializable id, SessionImplementor session) {
- this.entityName = entityName;
- this.id = id;
- // initialize other fields depending on session state
- if ( session == null ) {
- unsetSession();
- }
- else {
- setSession( session );
- }
- }
-
- @Override
- public final String getEntityName() {
- return entityName;
- }
-
- @Override
- public final Serializable getIdentifier() {
- return id;
- }
-
- @Override
- public final void setIdentifier(Serializable id) {
- this.id = id;
- }
-
- @Override
- public final boolean isUninitialized() {
- return !initialized;
- }
-
- @Override
- public final SessionImplementor getSession() {
- return session;
- }
-
- @Override
- public final void setSession(SessionImplementor s) throws HibernateException {
- if ( s != session ) {
- // check for s == null first, since it is least expensive
- if ( s == null ) {
- unsetSession();
- }
- else if ( isConnectedToSession() ) {
- //TODO: perhaps this should be some other RuntimeException...
- throw new HibernateException( "illegally attempted to associate a proxy with two open Sessions" );
- }
- else {
- // s != null
- session = s;
- if ( readOnlyBeforeAttachedToSession == null ) {
- // use the default read-only/modifiable setting
- final EntityPersister persister = s.getFactory().getEntityPersister( entityName );
- setReadOnly( s.getPersistenceContext().isDefaultReadOnly() || !persister.isMutable() );
- }
- else {
- // use the read-only/modifiable setting indicated during deserialization
- setReadOnly( readOnlyBeforeAttachedToSession.booleanValue() );
- readOnlyBeforeAttachedToSession = null;
- }
- }
- }
- }
-
- private static EntityKey generateEntityKeyOrNull(Serializable id, SessionImplementor s, String entityName) {
- if ( id == null || s == null || entityName == null ) {
- return null;
- }
- return s.generateEntityKey( id, s.getFactory().getEntityPersister( entityName ) );
- }
-
- @Override
- public final void unsetSession() {
- prepareForPossibleSpecialSpecjInitialization();
- session = null;
- readOnly = false;
- readOnlyBeforeAttachedToSession = null;
- }
-
- @Override
- public final void initialize() throws HibernateException {
- // In remoting we are sure that session is null
- // both when using property paths and switching off conversations
- if(session == null && remoting) {
- remoteInitialize();
- }
- if ( !initialized ) {
- if ( specjLazyLoad ) {
- specialSpecjInitialization();
- }
- else if ( session == null ) {
- throw new LazyInitializationException( "could not initialize proxy - no Session" );
- }
- else if ( !session.isOpen() ) {
- throw new LazyInitializationException( "could not initialize proxy - the owning Session was closed" );
- }
- else if ( !session.isConnected() ) {
- throw new LazyInitializationException( "could not initialize proxy - the owning Session is disconnected" );
- }
- else {
- target = session.immediateLoad( entityName, id );
- initialized = true;
- checkTargetState();
- }
- }
- else {
- checkTargetState();
- }
- }
-
- protected void specialSpecjInitialization() {
- if ( session == null ) {
- //we have a detached collection thats set to null, reattach
- if ( sessionFactoryUuid == null ) {
- throw new LazyInitializationException( "could not initialize proxy - no Session" );
- }
- try {
- SessionFactoryImplementor sf = (SessionFactoryImplementor)
- SessionFactoryRegistry.INSTANCE.getSessionFactory( sessionFactoryUuid );
- SessionImplementor session = (SessionImplementor) sf.openSession();
-
- // TODO: On the next major release, add an
- // 'isJTA' or 'getTransactionFactory' method to Session.
- boolean isJTA = session.getTransactionCoordinator()
- .getTransactionContext().getTransactionEnvironment()
- .getTransactionFactory()
- .compatibleWithJtaSynchronization();
-
- if ( !isJTA ) {
- // Explicitly handle the transactions only if we're not in
- // a JTA environment. A lazy loading temporary session can
- // be created even if a current session and transaction are
- // open (ex: session.clear() was used). We must prevent
- // multiple transactions.
- ( ( Session) session ).beginTransaction();
- }
-
- try {
- target = session.immediateLoad( entityName, id );
- }
- finally {
- // make sure the just opened temp session gets closed!
- try {
- if ( !isJTA ) {
- ( ( Session) session ).getTransaction().commit();
- }
- ( (Session) session ).close();
- }
- catch (Exception e) {
- log.warn( "Unable to close temporary session used to load lazy proxy associated to no session" );
- }
- }
- initialized = true;
- checkTargetState();
- }
- catch (Exception e) {
- e.printStackTrace();
- throw new LazyInitializationException( e.getMessage() );
- }
- }
- else if ( session.isOpen() && session.isConnected() ) {
- target = session.immediateLoad( entityName, id );
- initialized = true;
- checkTargetState();
- }
- else {
- throw new LazyInitializationException( "could not initialize proxy - Session was closed or disced" );
- }
- }
-
- protected void prepareForPossibleSpecialSpecjInitialization() {
- if ( session != null ) {
- specjLazyLoad = session.getFactory().getSettings().isInitializeLazyStateOutsideTransactionsEnabled();
-
- if ( specjLazyLoad && sessionFactoryUuid == null ) {
- try {
- sessionFactoryUuid = (String) session.getFactory().getReference().get( "uuid" ).getContent();
- }
- catch (NamingException e) {
- //not much we can do if this fails...
- }
- }
- }
- }
-
- private void checkTargetState() {
- if ( !unwrap ) {
- if ( target == null ) {
- getSession().getFactory().getEntityNotFoundDelegate().handleEntityNotFound( entityName, id );
- }
- }
- }
-
- /**
- * Getter for property 'connectedToSession'.
- *
- * @return Value for property 'connectedToSession'.
- */
- protected final boolean isConnectedToSession() {
- return getProxyOrNull() != null;
- }
-
- private Object getProxyOrNull() {
- final EntityKey entityKey = generateEntityKeyOrNull( getIdentifier(), session, getEntityName() );
- if ( entityKey != null && session != null && session.isOpen() ) {
- return session.getPersistenceContext().getProxy( entityKey );
- }
- return null;
- }
-
- @Override
- public final Object getImplementation() {
- initialize();
- return target;
- }
-
- @Override
- public final void setImplementation(Object target) {
- this.target = target;
- initialized = true;
- }
-
- @Override
- public final Object getImplementation(SessionImplementor s) throws HibernateException {
- final EntityKey entityKey = generateEntityKeyOrNull( getIdentifier(), s, getEntityName() );
- return (entityKey == null ? null : s.getPersistenceContext().getEntity( entityKey ));
- }
-
- /**
- * Getter for property 'target'.
- * <p/>
- * Same as {@link #getImplementation()} except that this method will not force initialization.
- *
- * @return Value for property 'target'.
- */
- protected final Object getTarget() {
- return target;
- }
-
- @Override
- public final boolean isReadOnlySettingAvailable() {
- return (session != null && !session.isClosed());
- }
-
- private void errorIfReadOnlySettingNotAvailable() {
- if ( session == null ) {
- throw new TransientObjectException(
- "Proxy is detached (i.e, session is null). The read-only/modifiable setting is only accessible when the proxy is associated with an open session."
- );
- }
- if ( session.isClosed() ) {
- throw new SessionException(
- "Session is closed. The read-only/modifiable setting is only accessible when the proxy is associated with an open session."
- );
- }
- }
-
- @Override
- public final boolean isReadOnly() {
- errorIfReadOnlySettingNotAvailable();
- return readOnly;
- }
-
- @Override
- public final void setReadOnly(boolean readOnly) {
- errorIfReadOnlySettingNotAvailable();
- // only update if readOnly is different from current setting
- if ( this.readOnly != readOnly ) {
- final EntityPersister persister = session.getFactory().getEntityPersister( entityName );
- if ( !persister.isMutable() && !readOnly ) {
- throw new IllegalStateException( "cannot make proxies for immutable entities modifiable" );
- }
- this.readOnly = readOnly;
- if ( initialized ) {
- EntityKey key = generateEntityKeyOrNull( getIdentifier(), session, getEntityName() );
- if ( key != null && session.getPersistenceContext().containsEntity( key ) ) {
- session.getPersistenceContext().setReadOnly( target, readOnly );
- }
- }
- }
- }
-
- /**
- * Get the read-only/modifiable setting that should be put in affect when it is
- * attached to a session.
- * <p/>
- * This method should only be called during serialization when read-only/modifiable setting
- * is not available (i.e., isReadOnlySettingAvailable() == false)
- *
- * @return null, if the default setting should be used;
- * true, for read-only;
- * false, for modifiable
- *
- * @throws IllegalStateException if isReadOnlySettingAvailable() == true
- */
- protected final Boolean isReadOnlyBeforeAttachedToSession() {
- if ( isReadOnlySettingAvailable() ) {
- throw new IllegalStateException(
- "Cannot call isReadOnlyBeforeAttachedToSession when isReadOnlySettingAvailable == true"
- );
- }
- return readOnlyBeforeAttachedToSession;
- }
-
- /**
- * Set the read-only/modifiable setting that should be put in affect when it is
- * attached to a session.
- * <p/>
- * This method should only be called during deserialization, before associating
- * the proxy with a session.
- *
- * @param readOnlyBeforeAttachedToSession, the read-only/modifiable setting to use when
- * associated with a session; null indicates that the default should be used.
- *
- * @throws IllegalStateException if isReadOnlySettingAvailable() == true
- */
- /* package-private */
- final void setReadOnlyBeforeAttachedToSession(Boolean readOnlyBeforeAttachedToSession) {
- if ( isReadOnlySettingAvailable() ) {
- throw new IllegalStateException(
- "Cannot call setReadOnlyBeforeAttachedToSession when isReadOnlySettingAvailable == true"
- );
- }
- this.readOnlyBeforeAttachedToSession = readOnlyBeforeAttachedToSession;
- }
-
- @Override
- public boolean isUnwrap() {
- return unwrap;
- }
-
- @Override
- public void setUnwrap(boolean unwrap) {
- this.unwrap = unwrap;
- }
-
- /** Below is section of code which makes remote service calls */
-
- private static ICdmApplicationConfiguration configuration;
- private static boolean remoting = false;
-
- public static void setConfiguration(ICdmApplicationConfiguration conf) {
- configuration = conf;
-
- if(conf instanceof CdmApplicationRemoteController) {
- remoting = true;
- } else {
- remoting = false;
- }
- }
-
-
- private void remoteInitialize() {
-
- if(!initialized) {
- int classid = ((Integer)getIdentifier()).intValue();
- log.debug("--> Remote Lazy Initializing" + getEntityName() + " with id " + classid);
- Class clazz;
- try {
- clazz = (Class<? extends CdmBase>) Class.forName(getEntityName());
- } catch (ClassNotFoundException e) {
- throw new HibernateException("Class for " + getEntityName() + " not found", e);
- }
- if(configuration == null) {
- throw new HibernateException("CdmApplicationRemoteConfiguration not initialized (null)");
- }
- ICommonService commonService = configuration.getCommonService();
- if(commonService == null) {
- throw new HibernateException("commonService not initialized (null)");
- }
-
- CdmBase cdmBase = CdmBase.deproxy(commonService.find(clazz,classid),clazz);
- setImplementation(cdmBase);
-
- }
- }
-
- public static boolean isInitialized(AbstractLazyInitializer obj) {
- return obj.initialized;
- }
-}