Project

General

Profile

Revision 3dd6c00e

ID3dd6c00ee97df6d2976e0bb597c8d0e986002f91
Parent b2639c6c
Child 53c8f824

Added by Andreas Müller almost 4 years ago

Upgrade to hibernate 5 with persistence tests running #4716

View differences:

cdmlib-ext/src/test/resources/log4j.properties
41 41
	### *** SPRING ************ ###
42 42
log4j.logger.org.springframework.transaction = warn
43 43
log4j.logger.org.hibernate.engine.LoadContexts = warn
44
log4j.logger.org.springframework.orm.hibernate4.SessionFactoryUtils = warn
45
log4j.logger.org.springframework.orm.hibernate4 = warn
44
log4j.logger.org.springframework.orm.hibernate5.SessionFactoryUtils = warn
45
log4j.logger.org.springframework.orm.hibernate5 = warn
46 46
log4j.logger.org.springframework.FileSystemXmlApplicationContext = warn;
47 47
log4j.logger.org.springframework.core.io.support = warn
48 48

  
cdmlib-io/src/main/java/eu/etaxonomy/cdm/io/common/CdmIoBase.java
1
/**
2
* Copyright (C) 2007 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9

  
10
package eu.etaxonomy.cdm.io.common;
11

  
12
import java.lang.reflect.Constructor;
13
import java.lang.reflect.InvocationTargetException;
14
import java.util.HashSet;
15
import java.util.Set;
16

  
17
import org.apache.commons.lang.StringUtils;
18
import org.apache.log4j.Logger;
19
import org.hibernate.SessionFactory;
20
import org.springframework.beans.factory.annotation.Autowired;
21
import org.springframework.transaction.PlatformTransactionManager;
22
import org.springframework.transaction.TransactionDefinition;
23
import org.springframework.transaction.TransactionStatus;
24
import org.springframework.transaction.support.DefaultTransactionDefinition;
25

  
26
import eu.etaxonomy.cdm.api.application.CdmApplicationDefaultConfiguration;
27
import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
28
import eu.etaxonomy.cdm.io.common.events.IIoEvent;
29
import eu.etaxonomy.cdm.io.common.events.IIoObserver;
30
import eu.etaxonomy.cdm.io.common.events.IoProblemEvent;
31
import eu.etaxonomy.cdm.io.common.events.IoProgressEvent;
32
import eu.etaxonomy.cdm.model.common.CdmBase;
33

  
34
/**
35
 * @author a.mueller
36
 * @created 01.07.2008
37
 */
38
public abstract class CdmIoBase<STATE extends IoStateBase> extends CdmApplicationDefaultConfiguration
39
        implements ICdmIO<STATE>, IIoObservable {
40
    private static final Logger logger = Logger.getLogger(CdmIoBase.class);
41

  
42
    private final Set<IIoObserver> observers = new HashSet<IIoObserver>();
43
    protected String ioName = null;
44

  
45

  
46
    /**
47
     *
48
     */
49
    public CdmIoBase() {
50
        super();
51
        this.ioName = this.getClass().getSimpleName();
52
    }
53

  
54
//******************** Observers *********************************************************
55

  
56
    @Override
57
    public boolean addObserver(IIoObserver observer){
58
        return observers.add(observer);
59
    }
60

  
61
    @Override
62
    public Set<IIoObserver> getObservers() {
63
        return observers;
64
    }
65

  
66
    @Override
67
    public void addObservers(Set<IIoObserver> newObservers) {
68
        for (IIoObserver observer : newObservers){
69
            this.observers.add(observer);
70
        }
71
    }
72

  
73
    @Override
74
    public int countObservers(){
75
        return observers.size();
76
    }
77

  
78
    @Override
79
    public boolean removeObserver(IIoObserver observer){
80
        return observers.remove(observer);
81
    }
82

  
83
    @Override
84
    public void removeObservers(){
85
        observers.removeAll(observers);
86
    }
87

  
88
    @Override
89
    public void fire(IIoEvent event){
90
        for (IIoObserver observer: observers){
91
            observer.handleEvent(event);
92
        }
93
    }
94

  
95
//******************** End Observers *********************************************************
96

  
97

  
98
    public int countSteps(){
99
        return 1;
100
    }
101

  
102
    @Override
103
    public boolean invoke(STATE state) {
104
        if (isIgnore( state)){
105
            logger.info("No invoke for " + ioName + " (ignored)");
106
            return true;
107
        }else{
108
            updateProgress(state, "Invoking " + ioName);
109
            doInvoke(state);
110
            return state.isSuccess();
111
        }
112
    }
113

  
114
    /**
115
     * invoke method to be implemented by implementing classes
116
     * @param state
117
     * @return
118
     */
119
    protected abstract void doInvoke(STATE state);
120

  
121
    @Autowired
122
    private SessionFactory sessionFactory;
123

  
124
    /**
125
     * flush the current session
126
     */
127
    //TODO move into super class CdmApplicationDefaultConfiguration#flush() ?
128
    public void flush() {
129
        sessionFactory.getCurrentSession().flush();
130
    }
131

  
132
    @Override
133
    //TODO seems to be exact duplicate of CdmApplicationDefaultConfiguration#startTransaction(), remove duplicate
134
    public TransactionStatus startTransaction() {
135
        return startTransaction(false);
136
    }
137

  
138
    @Override
139
    //TODO seems to be exact duplicate of CdmApplicationDefaultConfiguration#startTransaction(java.lang.Boolean)
140
    public TransactionStatus startTransaction(Boolean readOnly) {
141

  
142
        DefaultTransactionDefinition defaultTxDef = new DefaultTransactionDefinition();
143
        defaultTxDef.setReadOnly(readOnly);
144
        TransactionDefinition txDef = defaultTxDef;
145

  
146
        // Log some transaction-related debug information.
147
        if (logger.isDebugEnabled()) {
148
            logger.debug("Transaction name = " + txDef.getName());
149
            logger.debug("Transaction facets:");
150
            logger.debug("Propagation behavior = " + txDef.getPropagationBehavior());
151
            logger.debug("Isolation level = " + txDef.getIsolationLevel());
152
            logger.debug("Timeout = " + txDef.getTimeout());
153
            logger.debug("Read Only = " + txDef.isReadOnly());
154
            // org.springframework.orm.hibernate4.HibernateTransactionManager
155
            // provides more transaction/session-related debug information.
156
        }
157

  
158
        TransactionStatus txStatus = super.getTransactionManager().getTransaction(txDef);
159
        return txStatus;
160
    }
161

  
162
    @Override
163
    //TODO seems to be exact duplicate of CdmApplicationDefaultConfiguration#startTransaction(java.lang.Boolean), remove duplicate?
164
    public void commitTransaction(TransactionStatus txStatus){
165
        PlatformTransactionManager txManager = super.getTransactionManager();
166
        txManager.commit(txStatus);
167
        return;
168
    }
169

  
170
    //TODO move into super class CdmApplicationDefaultConfiguration#startTransaction(java.lang.Boolean)
171
    //==> no 
172
    public void rollbackTransaction(TransactionStatus txStatus){
173
        PlatformTransactionManager txManager = super.getTransactionManager();
174
        txManager.rollback(txStatus);
175
        return;
176
    }
177

  
178
    @Override
179
    public boolean check(STATE state) {
180
        if (isIgnore(state)){
181
            logger.info("No check for " + ioName + " (ignored)");
182
            return true;
183
        }else{
184
            return doCheck(state);
185
        }
186
    }
187

  
188
    protected abstract boolean doCheck(STATE state);
189

  
190

  
191
    /**
192
     * Returns true if this (IO-)class should be ignored during the import/export process.
193
     * This information is usually stored in the configuration
194
     * @param config
195
     * @return
196
     */
197
    protected abstract boolean isIgnore(STATE state);
198

  
199
    protected <T extends CdmBase> T getInstance(Class<? extends T> clazz){
200
        T result = null;
201
        try {
202
            Constructor<? extends T> constructor = clazz.getDeclaredConstructor();
203
            constructor.setAccessible(true);
204
            result = constructor.newInstance();
205
        } catch (InstantiationException e) {
206
            logger.error("Class " + clazz.getSimpleName()+" could not be instantiated. Class = " );
207
            e.printStackTrace();
208
        } catch (IllegalAccessException e) {
209
            logger.error("Constructor of class "+clazz.getSimpleName()+" could not be accessed." );
210
            e.printStackTrace();
211
        } catch (SecurityException e) {
212
            e.printStackTrace();
213
        } catch (NoSuchMethodException e) {
214
            logger.error("SecurityException for Constructor of class "+clazz.getSimpleName()+"." );
215
            e.printStackTrace();
216
        } catch (IllegalArgumentException e) {
217
            logger.error("Empty Constructor does not exist for class "+clazz.getSimpleName()+"." );
218
            e.printStackTrace();
219
        } catch (InvocationTargetException e) {
220
            logger.error("Empty Constructor could not be invoked for class "+clazz.getSimpleName()+"." );
221
            e.printStackTrace();
222
        }
223
        return result;
224
    }
225

  
226

  
227
    protected String getSuccessString(boolean success){
228
        if (success){
229
            return "with success";
230
        }else{
231
            return "with errors";
232
        }
233
    }
234

  
235
    @Override
236
    public void updateProgress(STATE state, String message) {
237
        updateProgress(state, message, 1);
238
    }
239

  
240
    @Override
241
    public void updateProgress(STATE state, String message, int worked) {
242
        IProgressMonitor progressMonitor = state.getConfig().getProgressMonitor();
243
        if(progressMonitor != null){
244
            progressMonitor.worked(worked);
245
            progressMonitor.subTask(message);
246
        }
247
    }
248

  
249
    @Override
250
    public void warnProgress(STATE state, String message, Throwable e) {
251
        if(state.getConfig().getProgressMonitor() != null){
252
            IProgressMonitor monitor = state.getConfig().getProgressMonitor();
253
            if (e == null) {
254
                monitor.warning(message);
255
            }else{
256
                monitor.warning(message, e);
257
            }
258
        }
259
    }
260

  
261
    protected void fireProgressEvent(String message, String location) {
262
        IoProgressEvent event = new IoProgressEvent();
263
        event.setThrowingClass(this.getClass());
264
        event.setMessage(message);
265
        event.setLocation(location);
266
//		int linenumber = new Exception().getStackTrace()[0].getLineNumber();
267
        fire(event);
268
    }
269

  
270

  
271
    protected void fireWarningEvent(String message, String dataLocation, Integer severity) {
272
        fireWarningEvent(message, dataLocation, severity, 1);
273
    }
274

  
275
    protected void fireWarningEvent(String message, String dataLocation, Integer severity, int stackDepth) {
276
        stackDepth++;
277
        StackTraceElement[] stackTrace = new Exception().getStackTrace();
278
        int lineNumber = stackTrace[stackDepth].getLineNumber();
279
        String methodName = stackTrace[stackDepth].getMethodName();
280
        String className = stackTrace[stackDepth].getClassName();
281
		Class<?> declaringClass;
282
		try {
283
			declaringClass = Class.forName(className);
284
		} catch (ClassNotFoundException e) {
285
			declaringClass = this.getClass();
286
		}
287
		
288
        IoProblemEvent event = IoProblemEvent.NewInstance(declaringClass, message, dataLocation,
289
                lineNumber, severity, methodName);
290

  
291
        //for performance improvement one may read:
292
        //http://stackoverflow.com/questions/421280/in-java-how-do-i-find-the-caller-of-a-method-using-stacktrace-or-reflection
293
//		Object o = new SecurityManager().getSecurityContext();
294

  
295

  
296
        fire(event);
297
    }
298

  
299
    protected boolean isBlank(String str){
300
        return StringUtils.isBlank(str);
301
    }
302

  
303
    protected boolean isNotBlank(String str){
304
        return StringUtils.isNotBlank(str);
305
    }
306

  
307
}
1
/**
2
* Copyright (C) 2007 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9

  
10
package eu.etaxonomy.cdm.io.common;
11

  
12
import java.lang.reflect.Constructor;
13
import java.lang.reflect.InvocationTargetException;
14
import java.util.HashSet;
15
import java.util.Set;
16

  
17
import org.apache.commons.lang.StringUtils;
18
import org.apache.log4j.Logger;
19
import org.hibernate.SessionFactory;
20
import org.springframework.beans.factory.annotation.Autowired;
21
import org.springframework.transaction.PlatformTransactionManager;
22
import org.springframework.transaction.TransactionDefinition;
23
import org.springframework.transaction.TransactionStatus;
24
import org.springframework.transaction.support.DefaultTransactionDefinition;
25

  
26
import eu.etaxonomy.cdm.api.application.CdmApplicationDefaultConfiguration;
27
import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
28
import eu.etaxonomy.cdm.io.common.events.IIoEvent;
29
import eu.etaxonomy.cdm.io.common.events.IIoObserver;
30
import eu.etaxonomy.cdm.io.common.events.IoProblemEvent;
31
import eu.etaxonomy.cdm.io.common.events.IoProgressEvent;
32
import eu.etaxonomy.cdm.model.common.CdmBase;
33

  
34
/**
35
 * @author a.mueller
36
 * @created 01.07.2008
37
 */
38
public abstract class CdmIoBase<STATE extends IoStateBase> extends CdmApplicationDefaultConfiguration
39
        implements ICdmIO<STATE>, IIoObservable {
40
    private static final Logger logger = Logger.getLogger(CdmIoBase.class);
41

  
42
    private final Set<IIoObserver> observers = new HashSet<IIoObserver>();
43
    protected String ioName = null;
44

  
45

  
46
    /**
47
     *
48
     */
49
    public CdmIoBase() {
50
        super();
51
        this.ioName = this.getClass().getSimpleName();
52
    }
53

  
54
//******************** Observers *********************************************************
55

  
56
    @Override
57
    public boolean addObserver(IIoObserver observer){
58
        return observers.add(observer);
59
    }
60

  
61
    @Override
62
    public Set<IIoObserver> getObservers() {
63
        return observers;
64
    }
65

  
66
    @Override
67
    public void addObservers(Set<IIoObserver> newObservers) {
68
        for (IIoObserver observer : newObservers){
69
            this.observers.add(observer);
70
        }
71
    }
72

  
73
    @Override
74
    public int countObservers(){
75
        return observers.size();
76
    }
77

  
78
    @Override
79
    public boolean removeObserver(IIoObserver observer){
80
        return observers.remove(observer);
81
    }
82

  
83
    @Override
84
    public void removeObservers(){
85
        observers.removeAll(observers);
86
    }
87

  
88
    @Override
89
    public void fire(IIoEvent event){
90
        for (IIoObserver observer: observers){
91
            observer.handleEvent(event);
92
        }
93
    }
94

  
95
//******************** End Observers *********************************************************
96

  
97

  
98
    public int countSteps(){
99
        return 1;
100
    }
101

  
102
    @Override
103
    public boolean invoke(STATE state) {
104
        if (isIgnore( state)){
105
            logger.info("No invoke for " + ioName + " (ignored)");
106
            return true;
107
        }else{
108
            updateProgress(state, "Invoking " + ioName);
109
            doInvoke(state);
110
            return state.isSuccess();
111
        }
112
    }
113

  
114
    /**
115
     * invoke method to be implemented by implementing classes
116
     * @param state
117
     * @return
118
     */
119
    protected abstract void doInvoke(STATE state);
120

  
121
    @Autowired
122
    private SessionFactory sessionFactory;
123

  
124
    /**
125
     * flush the current session
126
     */
127
    //TODO move into super class CdmApplicationDefaultConfiguration#flush() ?
128
    public void flush() {
129
        sessionFactory.getCurrentSession().flush();
130
    }
131

  
132
    @Override
133
    //TODO seems to be exact duplicate of CdmApplicationDefaultConfiguration#startTransaction(), remove duplicate
134
    public TransactionStatus startTransaction() {
135
        return startTransaction(false);
136
    }
137

  
138
    @Override
139
    //TODO seems to be exact duplicate of CdmApplicationDefaultConfiguration#startTransaction(java.lang.Boolean)
140
    public TransactionStatus startTransaction(Boolean readOnly) {
141

  
142
        DefaultTransactionDefinition defaultTxDef = new DefaultTransactionDefinition();
143
        defaultTxDef.setReadOnly(readOnly);
144
        TransactionDefinition txDef = defaultTxDef;
145

  
146
        // Log some transaction-related debug information.
147
        if (logger.isDebugEnabled()) {
148
            logger.debug("Transaction name = " + txDef.getName());
149
            logger.debug("Transaction facets:");
150
            logger.debug("Propagation behavior = " + txDef.getPropagationBehavior());
151
            logger.debug("Isolation level = " + txDef.getIsolationLevel());
152
            logger.debug("Timeout = " + txDef.getTimeout());
153
            logger.debug("Read Only = " + txDef.isReadOnly());
154
            // org.springframework.orm.hibernate5.HibernateTransactionManager
155
            // provides more transaction/session-related debug information.
156
        }
157

  
158
        TransactionStatus txStatus = super.getTransactionManager().getTransaction(txDef);
159
        return txStatus;
160
    }
161

  
162
    @Override
163
    //TODO seems to be exact duplicate of CdmApplicationDefaultConfiguration#startTransaction(java.lang.Boolean), remove duplicate?
164
    public void commitTransaction(TransactionStatus txStatus){
165
        PlatformTransactionManager txManager = super.getTransactionManager();
166
        txManager.commit(txStatus);
167
        return;
168
    }
169

  
170
    //TODO move into super class CdmApplicationDefaultConfiguration#startTransaction(java.lang.Boolean)
171
    //==> no
172
    public void rollbackTransaction(TransactionStatus txStatus){
173
        PlatformTransactionManager txManager = super.getTransactionManager();
174
        txManager.rollback(txStatus);
175
        return;
176
    }
177

  
178
    @Override
179
    public boolean check(STATE state) {
180
        if (isIgnore(state)){
181
            logger.info("No check for " + ioName + " (ignored)");
182
            return true;
183
        }else{
184
            return doCheck(state);
185
        }
186
    }
187

  
188
    protected abstract boolean doCheck(STATE state);
189

  
190

  
191
    /**
192
     * Returns true if this (IO-)class should be ignored during the import/export process.
193
     * This information is usually stored in the configuration
194
     * @param config
195
     * @return
196
     */
197
    protected abstract boolean isIgnore(STATE state);
198

  
199
    protected <T extends CdmBase> T getInstance(Class<? extends T> clazz){
200
        T result = null;
201
        try {
202
            Constructor<? extends T> constructor = clazz.getDeclaredConstructor();
203
            constructor.setAccessible(true);
204
            result = constructor.newInstance();
205
        } catch (InstantiationException e) {
206
            logger.error("Class " + clazz.getSimpleName()+" could not be instantiated. Class = " );
207
            e.printStackTrace();
208
        } catch (IllegalAccessException e) {
209
            logger.error("Constructor of class "+clazz.getSimpleName()+" could not be accessed." );
210
            e.printStackTrace();
211
        } catch (SecurityException e) {
212
            e.printStackTrace();
213
        } catch (NoSuchMethodException e) {
214
            logger.error("SecurityException for Constructor of class "+clazz.getSimpleName()+"." );
215
            e.printStackTrace();
216
        } catch (IllegalArgumentException e) {
217
            logger.error("Empty Constructor does not exist for class "+clazz.getSimpleName()+"." );
218
            e.printStackTrace();
219
        } catch (InvocationTargetException e) {
220
            logger.error("Empty Constructor could not be invoked for class "+clazz.getSimpleName()+"." );
221
            e.printStackTrace();
222
        }
223
        return result;
224
    }
225

  
226

  
227
    protected String getSuccessString(boolean success){
228
        if (success){
229
            return "with success";
230
        }else{
231
            return "with errors";
232
        }
233
    }
234

  
235
    @Override
236
    public void updateProgress(STATE state, String message) {
237
        updateProgress(state, message, 1);
238
    }
239

  
240
    @Override
241
    public void updateProgress(STATE state, String message, int worked) {
242
        IProgressMonitor progressMonitor = state.getConfig().getProgressMonitor();
243
        if(progressMonitor != null){
244
            progressMonitor.worked(worked);
245
            progressMonitor.subTask(message);
246
        }
247
    }
248

  
249
    @Override
250
    public void warnProgress(STATE state, String message, Throwable e) {
251
        if(state.getConfig().getProgressMonitor() != null){
252
            IProgressMonitor monitor = state.getConfig().getProgressMonitor();
253
            if (e == null) {
254
                monitor.warning(message);
255
            }else{
256
                monitor.warning(message, e);
257
            }
258
        }
259
    }
260

  
261
    protected void fireProgressEvent(String message, String location) {
262
        IoProgressEvent event = new IoProgressEvent();
263
        event.setThrowingClass(this.getClass());
264
        event.setMessage(message);
265
        event.setLocation(location);
266
//		int linenumber = new Exception().getStackTrace()[0].getLineNumber();
267
        fire(event);
268
    }
269

  
270

  
271
    protected void fireWarningEvent(String message, String dataLocation, Integer severity) {
272
        fireWarningEvent(message, dataLocation, severity, 1);
273
    }
274

  
275
    protected void fireWarningEvent(String message, String dataLocation, Integer severity, int stackDepth) {
276
        stackDepth++;
277
        StackTraceElement[] stackTrace = new Exception().getStackTrace();
278
        int lineNumber = stackTrace[stackDepth].getLineNumber();
279
        String methodName = stackTrace[stackDepth].getMethodName();
280
        String className = stackTrace[stackDepth].getClassName();
281
		Class<?> declaringClass;
282
		try {
283
			declaringClass = Class.forName(className);
284
		} catch (ClassNotFoundException e) {
285
			declaringClass = this.getClass();
286
		}
287

  
288
        IoProblemEvent event = IoProblemEvent.NewInstance(declaringClass, message, dataLocation,
289
                lineNumber, severity, methodName);
290

  
291
        //for performance improvement one may read:
292
        //http://stackoverflow.com/questions/421280/in-java-how-do-i-find-the-caller-of-a-method-using-stacktrace-or-reflection
293
//		Object o = new SecurityManager().getSecurityContext();
294

  
295

  
296
        fire(event);
297
    }
298

  
299
    protected boolean isBlank(String str){
300
        return StringUtils.isBlank(str);
301
    }
302

  
303
    protected boolean isNotBlank(String str){
304
        return StringUtils.isNotBlank(str);
305
    }
306

  
307
}
cdmlib-io/src/main/resources/log4j.properties
1
### ************ APPENDER ***********************************###
2

  
3
### direct log messages to stdout ###
4
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
5
log4j.appender.stdout.Target=System.out
6
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
7
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
8

  
9
### direct messages to file hibernate.log ###
10
log4j.appender.file=org.apache.log4j.FileAppender
11
log4j.appender.file.File=hibernate.log
12
log4j.appender.file.layout=org.apache.log4j.PatternLayout
13
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
14

  
15

  
16
### ************* LOG LEVELS *********************************###
17

  
18
### set log levels - for more verbose logging change 'info' to 'debug' ###
19

  
20
log4j.rootLogger=info, stdout
21

  
22
	### *** CDM *** ###
23

  
24
log4j.logger.eu.etaxonomy.cdm = warn 
25
log4j.logger.eu.etaxonomy.cdm.api.application.eclipse = warn
26
log4j.logger.eu.etaxonomy.cdm.io.berlinModel = info
27
log4j.logger.eu.etaxonomy.cdm.io.berlinModel.BerlinModelTaxonIO = info
28
log4j.logger.eu.etaxonomy.cdm.model.common.init = warn
29
log4j.logger.eu.etaxonomy.cdm.io.taxonx2013 = info
30

  
31
	### *** SPRING ************ ###
32
log4j.logger.org.springframework.transaction = warn
33
log4j.logger.org.hibernate.engine.LoadContexts = error
34
log4j.logger.org.springframework.orm.hibernate4.SessionFactoryUtils = info
35
log4j.logger.org.springframework.orm.hibernate4 = info
36
log4j.logger.org.springframework.FileSystemXmlApplicationContext = warn;
37
log4j.logger.org.springframework.core.io.support = info
38

  
39

  
40
	### ***HIBERNATE ************ ###
41

  
42
log4j.logger.org.hibernate=warn
43

  
44
### No warnings as thrown by SQLServer
45
log4j.logger.org.hibernate.cfg = warn
46

  
47
### No warnings as thrown by SQLServer
48
log4j.logger.org.hibernate.util.JDBCExceptionReporter = error
49

  
50
### log HQL query parser activity
51
#log4j.logger.org.hibernate.hql.ast.AST=debug
52

  
53
### log just the SQL
54
log4j.logger.org.hibernate.SQL=warn
55

  
56
### log JDBC bind parameters ###
57
log4j.logger.org.hibernate.type=warn
58

  
59
### log schema export/update ###
60
log4j.logger.org.hibernate.tool.hbm2ddl=warn
61

  
62
### log HQL parse trees
63
#log4j.logger.org.hibernate.hql=debug
64

  
65
### log cache activity ###
66
#log4j.logger.org.hibernate.cache=debug
67

  
68
### log transaction activity
69
#log4j.logger.org.hibernate.transaction=debug
70

  
71
### log JDBC resource acquisition
72
log4j.logger.org.hibernate.jdbc=info
73

  
74
### enable the following line if you want to track down connection ###
75
### leakages when using DriverManagerConnectionProvider ###
76
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
1
### ************ APPENDER ***********************************###
2

  
3
### direct log messages to stdout ###
4
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
5
log4j.appender.stdout.Target=System.out
6
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
7
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
8

  
9
### direct messages to file hibernate.log ###
10
log4j.appender.file=org.apache.log4j.FileAppender
11
log4j.appender.file.File=hibernate.log
12
log4j.appender.file.layout=org.apache.log4j.PatternLayout
13
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
14

  
15

  
16
### ************* LOG LEVELS *********************************###
17

  
18
### set log levels - for more verbose logging change 'info' to 'debug' ###
19

  
20
log4j.rootLogger=info, stdout
21

  
22
	### *** CDM *** ###
23

  
24
log4j.logger.eu.etaxonomy.cdm = warn 
25
log4j.logger.eu.etaxonomy.cdm.api.application.eclipse = warn
26
log4j.logger.eu.etaxonomy.cdm.io.berlinModel = info
27
log4j.logger.eu.etaxonomy.cdm.io.berlinModel.BerlinModelTaxonIO = info
28
log4j.logger.eu.etaxonomy.cdm.model.common.init = warn
29
log4j.logger.eu.etaxonomy.cdm.io.taxonx2013 = info
30

  
31
	### *** SPRING ************ ###
32
log4j.logger.org.springframework.transaction = warn
33
log4j.logger.org.hibernate.engine.LoadContexts = error
34
log4j.logger.org.springframework.orm.hibernate5.SessionFactoryUtils = info
35
log4j.logger.org.springframework.orm.hibernate5 = info
36
log4j.logger.org.springframework.FileSystemXmlApplicationContext = warn;
37
log4j.logger.org.springframework.core.io.support = info
38

  
39

  
40
	### ***HIBERNATE ************ ###
41

  
42
log4j.logger.org.hibernate=warn
43

  
44
### No warnings as thrown by SQLServer
45
log4j.logger.org.hibernate.cfg = warn
46

  
47
### No warnings as thrown by SQLServer
48
log4j.logger.org.hibernate.util.JDBCExceptionReporter = error
49

  
50
### log HQL query parser activity
51
#log4j.logger.org.hibernate.hql.ast.AST=debug
52

  
53
### log just the SQL
54
log4j.logger.org.hibernate.SQL=warn
55

  
56
### log JDBC bind parameters ###
57
log4j.logger.org.hibernate.type=warn
58

  
59
### log schema export/update ###
60
log4j.logger.org.hibernate.tool.hbm2ddl=warn
61

  
62
### log HQL parse trees
63
#log4j.logger.org.hibernate.hql=debug
64

  
65
### log cache activity ###
66
#log4j.logger.org.hibernate.cache=debug
67

  
68
### log transaction activity
69
#log4j.logger.org.hibernate.transaction=debug
70

  
71
### log JDBC resource acquisition
72
log4j.logger.org.hibernate.jdbc=info
73

  
74
### enable the following line if you want to track down connection ###
75
### leakages when using DriverManagerConnectionProvider ###
76
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
cdmlib-model/src/main/java/eu/etaxonomy/cdm/hibernate/URIUserType.java
67 67
		}
68 68
    }
69 69

  
70

  
71

  
72 70
	@Override
73 71
	public void nullSafeSet(PreparedStatement statement, Object value, int index, SessionImplementor session)
74 72
			throws HibernateException, SQLException {
cdmlib-model/src/main/java/eu/etaxonomy/cdm/model/agent/Institution.java
15 15

  
16 16
import javax.persistence.Entity;
17 17
import javax.persistence.FetchType;
18
import javax.persistence.JoinColumn;
19
import javax.persistence.JoinTable;
18 20
import javax.persistence.ManyToMany;
19 21
import javax.persistence.ManyToOne;
20 22
import javax.validation.constraints.Size;
......
89 91
    @XmlIDREF
90 92
    @XmlSchemaType(name = "IDREF")
91 93
    @ManyToMany(fetch = FetchType.LAZY)
94
    //preliminary  #5369
95
    @JoinTable(joinColumns = @JoinColumn( name="AgentBase_id"))
92 96
	private Set<DefinedTerm> types;  //InstitutionTypes
93 97

  
94 98
    @XmlElement(name = "IsPartOf")
cdmlib-model/src/main/java/eu/etaxonomy/cdm/model/agent/Team.java
16 16

  
17 17
import javax.persistence.Entity;
18 18
import javax.persistence.FetchType;
19
import javax.persistence.JoinColumn;
20
import javax.persistence.JoinTable;
19 21
import javax.persistence.ManyToMany;
22
import javax.persistence.OrderColumn;
20 23
import javax.persistence.Transient;
21 24
import javax.xml.bind.annotation.XmlAccessType;
22 25
import javax.xml.bind.annotation.XmlAccessorType;
......
30 33
import org.apache.log4j.Logger;
31 34
import org.hibernate.annotations.Cascade;
32 35
import org.hibernate.annotations.CascadeType;
33
import org.hibernate.annotations.IndexColumn;
36
import org.hibernate.annotations.ListIndexBase;
34 37
import org.hibernate.envers.Audited;
35 38
import org.hibernate.search.annotations.Indexed;
36 39
import org.springframework.beans.factory.annotation.Configurable;
......
79 82

  
80 83
    //under construction #4311
81 84
    @XmlElement(name = "ProtectedCollectorTitleCache")
82
	private boolean protectedCollectorTitleCache = false;
83
    
84
	//An abbreviated name for the team (e. g. in case of nomenclatural authorteams). 
85
	private final boolean protectedCollectorTitleCache = false;
86

  
87
	//An abbreviated name for the team (e. g. in case of nomenclatural authorteams).
85 88
    //A non abbreviated name for the team (e. g.
86 89
	//in case of some bibliographical references)
87 90
    @XmlElementWrapper(name = "TeamMembers", nillable = true)
88 91
    @XmlElement(name = "TeamMember")
89 92
    @XmlIDREF
90 93
    @XmlSchemaType(name = "IDREF")
91
    @IndexColumn(name="sortIndex", base = 0)
94
    @OrderColumn(name="sortIndex")
95
    @ListIndexBase(value=0)  //not really needed as this is the default
92 96
	@ManyToMany(fetch = FetchType.LAZY)
93
	@Cascade({CascadeType.SAVE_UPDATE,CascadeType.MERGE})
97
    @Cascade({CascadeType.SAVE_UPDATE,CascadeType.MERGE})
94 98
	@Match(MatchMode.MATCH)
99
    //preliminary  #5369
100
    @JoinTable(joinColumns = @JoinColumn( name="AgentBase_id"))
95 101
	private List<Person> teamMembers;
96
    
102

  
97 103
    @XmlElement(name = "hasMoreMembers")
98 104
	private boolean hasMoreMembers;
99 105

  
......
304 310
	/**
305 311
	 * Protected nomenclatural title cache flag should be set to true, if
306 312
	 * the title cache is to be preferred against the atomized data.
307
	 * This may be the case if no atomized data exists or if atomization 
313
	 * This may be the case if no atomized data exists or if atomization
308 314
	 * was incomplete for whatever reason.
309 315
	 * @return
310 316
	 */
......
316 322
			boolean protectedNomenclaturalTitleCache) {
317 323
		this.protectedNomenclaturalTitleCache = protectedNomenclaturalTitleCache;
318 324
	}
319
	
325

  
320 326

  
321 327
	/**
322 328
	 * The hasMoreMembers flag is true if this team has more members than
cdmlib-model/src/main/java/eu/etaxonomy/cdm/model/common/CdmBase.java
99 99
    //@XmlAttribute(name = "id", required = true)
100 100
    @XmlTransient
101 101
    @Id
102
//	@GeneratedValue(generator = "system-increment")
102
//	@GeneratedValue(generator = "system-increment")  //see also AuditEvent.revisionNumber
103 103
//	@GeneratedValue(generator = "enhanced-table")
104 104
    @GeneratedValue(generator = "custom-enhanced-table")
105 105
    @DocumentId
cdmlib-model/src/main/java/eu/etaxonomy/cdm/model/common/DefaultTermInitializer.java
1
/**
2
* Copyright (C) 2007 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.model.common;
10

  
11
import java.lang.reflect.Constructor;
12
import java.util.HashMap;
13
import java.util.Map;
14
import java.util.UUID;
15

  
16
import org.apache.log4j.Logger;
17

  
18
import eu.etaxonomy.cdm.model.common.init.ITermInitializer;
19
import eu.etaxonomy.cdm.model.common.init.ITermLoader;
20
import eu.etaxonomy.cdm.model.common.init.TermLoader;
21

  
22
/**
23
 * @author a.mueller
24
 *
25
 */
26
public class DefaultTermInitializer implements ITermInitializer {
27
	@SuppressWarnings("unused")
28
	private static final Logger logger = Logger.getLogger(DefaultTermInitializer.class);
29
	protected ITermLoader termLoader = new TermLoader();
30

  
31
	@Override
32
    public void initialize() {
33
		termLoader.unloadAllTerms();
34
		doInitialize();
35
	}
36

  
37
	protected void doInitialize(){
38
		Map<UUID,DefinedTermBase> terms = new HashMap<UUID,DefinedTermBase>();
39

  
40
//		for(Class<? extends DefinedTermBase<?>> clazz : classesToInitialize) {
41
		for(VocabularyEnum vocabularyEnum : VocabularyEnum.values()) {
42
//			Class<? extends DefinedTermBase<?>> clazz = vocabularyEnum.getClazz();
43
			TermVocabulary<?> voc  = termLoader.loadTerms(vocabularyEnum, terms);
44
			setDefinedTerms(vocabularyEnum.getClazz(),voc);
45
		}
46

  
47
	}
48

  
49
	protected void setDefinedTerms(Class<? extends DefinedTermBase<?>> clazz, TermVocabulary<?> vocabulary) {
50
		DefinedTermBase newInstance;
51
		newInstance = getInstance(clazz);
52
		newInstance.setDefaultTerms(vocabulary);
53
	}
54

  
55
	private  <T extends DefinedTermBase> T getInstance(Class<? extends DefinedTermBase> termClass) {
56
		try {
57
			Constructor<T> c = ((Class<T>)termClass).getDeclaredConstructor();
58
			c.setAccessible(true);
59
			T termInstance = c.newInstance();
60
			return termInstance;
61
		} catch (Exception e) {
62
			throw new RuntimeException(e);
63
		}
64
	}
65

  
66

  
67
}
1
/**
2
* Copyright (C) 2007 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.model.common;
10

  
11
import java.lang.reflect.Constructor;
12
import java.util.HashMap;
13
import java.util.Map;
14
import java.util.UUID;
15

  
16
import org.apache.log4j.Logger;
17

  
18
import eu.etaxonomy.cdm.model.common.init.ITermInitializer;
19
import eu.etaxonomy.cdm.model.common.init.ITermLoader;
20
import eu.etaxonomy.cdm.model.common.init.TermLoader;
21

  
22
/**
23
 * @author a.mueller
24
 *
25
 */
26
public class DefaultTermInitializer implements ITermInitializer {
27
	@SuppressWarnings("unused")
28
	private static final Logger logger = Logger.getLogger(DefaultTermInitializer.class);
29
	protected ITermLoader termLoader = new TermLoader();
30

  
31
	private boolean omit = false;
32

  
33
	@Override
34
    public void initialize() {
35
		termLoader.unloadAllTerms();
36
		doInitialize();
37
	}
38

  
39
	protected void doInitialize(){
40
		Map<UUID,DefinedTermBase> terms = new HashMap<UUID,DefinedTermBase>();
41

  
42
//		for(Class<? extends DefinedTermBase<?>> clazz : classesToInitialize) {
43
		for(VocabularyEnum vocabularyEnum : VocabularyEnum.values()) {
44
//			Class<? extends DefinedTermBase<?>> clazz = vocabularyEnum.getClazz();
45
			TermVocabulary<?> voc  = termLoader.loadTerms(vocabularyEnum, terms);
46
			setDefinedTerms(vocabularyEnum.getClazz(),voc);
47
		}
48

  
49
	}
50

  
51
	protected void setDefinedTerms(Class<? extends DefinedTermBase<?>> clazz, TermVocabulary<?> vocabulary) {
52
		DefinedTermBase newInstance;
53
		newInstance = getInstance(clazz);
54
		newInstance.setDefaultTerms(vocabulary);
55
	}
56

  
57
	private  <T extends DefinedTermBase> T getInstance(Class<? extends DefinedTermBase> termClass) {
58
		try {
59
			Constructor<T> c = ((Class<T>)termClass).getDeclaredConstructor();
60
			c.setAccessible(true);
61
			T termInstance = c.newInstance();
62
			return termInstance;
63
		} catch (Exception e) {
64
			throw new RuntimeException(e);
65
		}
66
	}
67

  
68

  
69
    public void setOmit(boolean omit) {
70
        this.omit = omit;
71
    }
72

  
73
    public boolean isOmit() {
74
        return omit;
75
    }
76

  
77

  
78
}
cdmlib-model/src/main/java/eu/etaxonomy/cdm/model/common/Group.java
1
/**
2
* Copyright (C) 2007 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.model.common;
10

  
11
import java.util.HashSet;
12
import java.util.Set;
13
import java.util.UUID;
14

  
15
import javax.persistence.Column;
16
import javax.persistence.Entity;
17
import javax.persistence.FetchType;
18
import javax.persistence.ManyToMany;
19
import javax.persistence.Table;
20
import javax.validation.constraints.NotNull;
21
import javax.xml.bind.annotation.XmlAccessType;
22
import javax.xml.bind.annotation.XmlAccessorType;
23
import javax.xml.bind.annotation.XmlElement;
24
import javax.xml.bind.annotation.XmlElementWrapper;
25
import javax.xml.bind.annotation.XmlIDREF;
26
import javax.xml.bind.annotation.XmlRootElement;
27
import javax.xml.bind.annotation.XmlSchemaType;
28
import javax.xml.bind.annotation.XmlType;
29

  
30
import org.apache.log4j.Logger;
31
import org.hibernate.annotations.Cascade;
32
import org.hibernate.annotations.CascadeType;
33
import org.hibernate.search.annotations.Field;
34
import org.hibernate.search.annotations.Indexed;
35
import org.springframework.security.core.GrantedAuthority;
36

  
37
@XmlAccessorType(XmlAccessType.FIELD)
38
@XmlType(name = "Group", propOrder = {
39
    "name",
40
    "members",
41
    "grantedAuthorities"
42
})
43
@XmlRootElement(name = "Group")
44
@Entity
45
@Indexed(index = "eu.etaxonomy.cdm.model.common.Group")
46
@Table(name = "PermissionGroup")
47
public class Group extends CdmBase {
48
    private static final long serialVersionUID = 7216686200093054648L;
49
    private static final Logger logger = Logger.getLogger(Group.class);
50

  
51
    public final static UUID groupEditorUuid = UUID.fromString("22e5e8af-b99c-4884-a92f-71978efd3770");
52
    public final static UUID groupProjectManagerUuid = UUID.fromString("645191ae-32a4-4d4e-9b86-c90e0d41944a");
53
    public final static UUID groupPublisherUuid = UUID.fromString("c1f20ad8-1782-40a7-b06b-ce4773acb5ea");
54

  
55
//*********************** FACTORY *********************/
56

  
57
    public static Group NewInstance(){
58
        return new Group();
59
    }
60

  
61
    public static Group NewInstance(String name){
62
        Group group = Group.NewInstance();
63
        group.setName(name);
64
        return group;
65
    }
66

  
67
//**************** FIELDS ******************************/
68

  
69
    @XmlElement(name = "Name")
70
    @Column(unique = true)
71
    @Field
72
    @NotNull
73
    protected String name;
74

  
75
    @XmlElementWrapper(name = "Members")
76
    @XmlElement(name = "Member")
77
    @XmlIDREF
78
    @XmlSchemaType(name = "IDREF")
79
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "groups")
80
    @Cascade({CascadeType.REFRESH, CascadeType.MERGE}) // see #2414 (Group updating doesn't work)
81
    protected Set<User> members = new HashSet<User>();
82

  
83
    @XmlElementWrapper(name = "GrantedAuthorities")
84
    @XmlElement(name = "GrantedAuthority", type = GrantedAuthorityImpl.class)
85
    @XmlIDREF
86
    @XmlSchemaType(name = "IDREF")
87
    @ManyToMany(fetch = FetchType.LAZY, targetEntity = GrantedAuthorityImpl.class)
88
    @Cascade({CascadeType.SAVE_UPDATE,CascadeType.MERGE})
89
    protected Set <GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();
90

  
91
// ********************* CONSTRUCTOR ************************/
92

  
93
    protected Group(){
94
        super();
95
    }
96

  
97
// *************** METHODS ***********************************/
98

  
99
    public Set<GrantedAuthority> getGrantedAuthorities() {
100
        return grantedAuthorities;
101
    }
102

  
103
    public boolean addGrantedAuthority(GrantedAuthority grantedAuthority){
104
        return grantedAuthorities.add(grantedAuthority);
105
    }
106

  
107
    public boolean removeGrantedAuthority(GrantedAuthority grantedAuthority){
108
        return grantedAuthorities.remove(grantedAuthority);
109
    }
110

  
111
    public void setName(String name) {
112
        this.name = name;
113
    }
114

  
115
    public String getName() {
116
        return name;
117
    }
118

  
119
    public Set<User> getMembers() {
120
        return members;
121
    }
122

  
123
    public boolean addMember(User user) {
124
        user.getGroups().add(this);
125
        return this.members.add(user);
126
    }
127

  
128
    public boolean removeMember(User user) {
129
        if(members.contains(user)) {
130
            user.getGroups().remove(this);
131
            return this.members.remove(user);
132
        } else {
133
            return false;
134
        }
135
    }
136
//*********************** CLONE ********************************************************/
137

  
138
    /**
139
     * Clones <i>this</i> Group. This is a shortcut that enables to create
140
     * a new instance that differs only slightly from <i>this</i> group by
141
     * modifying only some of the attributes.
142
     *
143
     * @see eu.etaxonomy.cdm.model.common.TermBase#clone()
144
     * @see java.lang.Object#clone()
145
     */
146
    @Override
147
    public Object clone() {
148
        Group result;
149
        try{
150
            result = (Group)super.clone();
151
            result.grantedAuthorities = new HashSet<GrantedAuthority>();
152
            for (GrantedAuthority grantedauthority: this.grantedAuthorities){
153
                result.addGrantedAuthority(grantedauthority);
154
            }
155

  
156
            result.members = new HashSet<User>();
157
            for (User member: this.members){
158
                result.addMember(member);
159
            }
160

  
161
            //no changes to name
162
            return result;
163
        } catch (CloneNotSupportedException e) {
164
            logger.warn("Object does not implement cloneable");
165
            e.printStackTrace();
166
            return null;
167

  
168
        }
169

  
170

  
171
    }
172

  
173
}
1
/**
2
* Copyright (C) 2007 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.model.common;
10

  
11
import java.util.HashSet;
12
import java.util.Set;
13
import java.util.UUID;
14

  
15
import javax.persistence.Column;
16
import javax.persistence.Entity;
17
import javax.persistence.FetchType;
18
import javax.persistence.JoinColumn;
19
import javax.persistence.JoinTable;
20
import javax.persistence.ManyToMany;
21
import javax.persistence.Table;
22
import javax.validation.constraints.NotNull;
23
import javax.xml.bind.annotation.XmlAccessType;
24
import javax.xml.bind.annotation.XmlAccessorType;
25
import javax.xml.bind.annotation.XmlElement;
26
import javax.xml.bind.annotation.XmlElementWrapper;
27
import javax.xml.bind.annotation.XmlIDREF;
28
import javax.xml.bind.annotation.XmlRootElement;
29
import javax.xml.bind.annotation.XmlSchemaType;
30
import javax.xml.bind.annotation.XmlType;
31

  
32
import org.apache.log4j.Logger;
33
import org.hibernate.annotations.Cascade;
34
import org.hibernate.annotations.CascadeType;
35
import org.hibernate.search.annotations.Field;
36
import org.hibernate.search.annotations.Indexed;
37
import org.springframework.security.core.GrantedAuthority;
38

  
39
@XmlAccessorType(XmlAccessType.FIELD)
40
@XmlType(name = "Group", propOrder = {
41
    "name",
42
    "members",
43
    "grantedAuthorities"
44
})
45
@XmlRootElement(name = "Group")
46
@Entity
47
@Indexed(index = "eu.etaxonomy.cdm.model.common.Group")
48
@Table(name = "PermissionGroup")
49
public class Group extends CdmBase {
50
    private static final long serialVersionUID = 7216686200093054648L;
51
    private static final Logger logger = Logger.getLogger(Group.class);
52

  
53
    public final static UUID groupEditorUuid = UUID.fromString("22e5e8af-b99c-4884-a92f-71978efd3770");
54
    public final static UUID groupProjectManagerUuid = UUID.fromString("645191ae-32a4-4d4e-9b86-c90e0d41944a");
55
    public final static UUID groupPublisherUuid = UUID.fromString("c1f20ad8-1782-40a7-b06b-ce4773acb5ea");
56

  
57
//*********************** FACTORY *********************/
58

  
59
    public static Group NewInstance(){
60
        return new Group();
61
    }
62

  
63
    public static Group NewInstance(String name){
64
        Group group = Group.NewInstance();
65
        group.setName(name);
66
        return group;
67
    }
68

  
69
//**************** FIELDS ******************************/
70

  
71
    @XmlElement(name = "Name")
72
    @Column(unique = true)
73
    @Field
74
    @NotNull
75
    protected String name;
76

  
77
    @XmlElementWrapper(name = "Members")
78
    @XmlElement(name = "Member")
79
    @XmlIDREF
80
    @XmlSchemaType(name = "IDREF")
81
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "groups")
82
    @Cascade({CascadeType.REFRESH, CascadeType.MERGE}) // see #2414 (Group updating doesn't work)
83
    protected Set<User> members = new HashSet<User>();
84

  
85
    @XmlElementWrapper(name = "GrantedAuthorities")
86
    @XmlElement(name = "GrantedAuthority", type = GrantedAuthorityImpl.class)
87
    @XmlIDREF
88
    @XmlSchemaType(name = "IDREF")
89
    @ManyToMany(fetch = FetchType.LAZY, targetEntity = GrantedAuthorityImpl.class)
90
    //preliminary  #5369
91
    @JoinTable(joinColumns = @JoinColumn( name="PermissionGroup_id"))
92
    @Cascade({CascadeType.SAVE_UPDATE,CascadeType.MERGE})
93
    protected Set <GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();
94

  
95
// ********************* CONSTRUCTOR ************************/
96

  
97
    protected Group(){
98
        super();
99
    }
100

  
101
// *************** METHODS ***********************************/
102

  
103
    public Set<GrantedAuthority> getGrantedAuthorities() {
104
        return grantedAuthorities;
105
    }
106

  
107
    public boolean addGrantedAuthority(GrantedAuthority grantedAuthority){
108
        return grantedAuthorities.add(grantedAuthority);
109
    }
110

  
111
    public boolean removeGrantedAuthority(GrantedAuthority grantedAuthority){
112
        return grantedAuthorities.remove(grantedAuthority);
113
    }
114

  
115
    public void setName(String name) {
116
        this.name = name;
117
    }
118

  
119
    public String getName() {
120
        return name;
121
    }
122

  
123
    public Set<User> getMembers() {
124
        return members;
125
    }
126

  
127
    public boolean addMember(User user) {
128
        user.getGroups().add(this);
129
        return this.members.add(user);
130
    }
131

  
132
    public boolean removeMember(User user) {
133
        if(members.contains(user)) {
134
            user.getGroups().remove(this);
135
            return this.members.remove(user);
136
        } else {
137
            return false;
138
        }
139
    }
140
//*********************** CLONE ********************************************************/
141

  
142
    /**
143
     * Clones <i>this</i> Group. This is a shortcut that enables to create
144
     * a new instance that differs only slightly from <i>this</i> group by
145
     * modifying only some of the attributes.
146
     *
147
     * @see eu.etaxonomy.cdm.model.common.TermBase#clone()
148
     * @see java.lang.Object#clone()
149
     */
150
    @Override
151
    public Object clone() {
152
        Group result;
153
        try{
154
            result = (Group)super.clone();
155
            result.grantedAuthorities = new HashSet<GrantedAuthority>();
156
            for (GrantedAuthority grantedauthority: this.grantedAuthorities){
157
                result.addGrantedAuthority(grantedauthority);
158
            }
159

  
160
            result.members = new HashSet<User>();
161
            for (User member: this.members){
162
                result.addMember(member);
163
            }
164

  
165
            //no changes to name
166
            return result;
167
        } catch (CloneNotSupportedException e) {
168
            logger.warn("Object does not implement cloneable");
169
            e.printStackTrace();
170
            return null;
171
        }
172
    }
173
}
cdmlib-model/src/main/java/eu/etaxonomy/cdm/model/common/User.java
1
/**
2
* Copyright (C) 2007 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9

  
10
package eu.etaxonomy.cdm.model.common;
11

  
12
import java.util.Collection;
13
import java.util.HashSet;
14
import java.util.Set;
15

  
16
import javax.persistence.Column;
17
import javax.persistence.Entity;
18
import javax.persistence.FetchType;
19
import javax.persistence.ManyToMany;
20
import javax.persistence.OneToOne;
21
import javax.persistence.Table;
22
import javax.persistence.Transient;
23
import javax.validation.constraints.NotNull;
24
import javax.xml.bind.annotation.XmlAccessType;
25
import javax.xml.bind.annotation.XmlAccessorType;
26
import javax.xml.bind.annotation.XmlElement;
27
import javax.xml.bind.annotation.XmlElementWrapper;
28
import javax.xml.bind.annotation.XmlIDREF;
29
import javax.xml.bind.annotation.XmlRootElement;
30
import javax.xml.bind.annotation.XmlSchemaType;
31
import javax.xml.bind.annotation.XmlTransient;
32
import javax.xml.bind.annotation.XmlType;
33

  
34
import org.apache.log4j.Logger;
35
import org.hibernate.annotations.Cascade;
36
import org.hibernate.annotations.CascadeType;
37
import org.hibernate.envers.Audited;
38
import org.hibernate.envers.NotAudited;
39
import org.hibernate.search.annotations.Analyze;
40
import org.hibernate.search.annotations.Field;
41
import org.hibernate.search.annotations.Indexed;
42
import org.hibernate.search.annotations.IndexedEmbedded;
43
import org.springframework.security.core.Authentication;
44
import org.springframework.security.core.GrantedAuthority;
45
import org.springframework.security.core.context.SecurityContextHolder;
46
import org.springframework.security.core.userdetails.UserDetails;
47

  
48
import eu.etaxonomy.cdm.model.agent.Person;
49

  
50
@XmlAccessorType(XmlAccessType.FIELD)
51
@XmlType(name = "User", propOrder = {
52
    "username",
53
    "password",
54
    "emailAddress",
55
    "grantedAuthorities",
56
    "groups",
57
    "enabled",
58
    "accountNonExpired",
59
    "credentialsNonExpired",
60
    "accountNonLocked",
61
    "person"
62
})
63
@XmlRootElement(name = "User")
64
@Entity
65
@Indexed(index = "eu.etaxonomy.cdm.model.common.User")
66
@Audited
67
@Table(name = "UserAccount")
68
public class User extends CdmBase implements UserDetails {
69
    private static final long serialVersionUID = 6582191171369439163L;
70
    private static final Logger logger = Logger.getLogger(User.class);
71

  
72
 // **************************** FACTORY *****************************************/
73

  
74
    public static User NewInstance(String username, String pwd){
75
        User user = new User();
76
        user.setUsername(username);
77
        user.setPassword(pwd);
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff

Add picture from clipboard (Maximum size: 40 MB)