From 0966fa407bca1b6aef964dfd6f865c95a0ccd8e2 Mon Sep 17 00:00:00 2001 From: Rick Herrick <jrherrick@wustl.edu> Date: Thu, 28 Apr 2016 17:47:11 -0500 Subject: [PATCH] Now having functioning site managed with preferences classes. --- .../java/org/nrg/dcm/DicomSCPManager.java | 61 +- .../org/nrg/schedule/TriggerTaskProxy.java | 36 - src/main/java/org/nrg/user/daos/UserDAO.java | 33 - src/main/java/org/nrg/user/entities/User.java | 44 - .../org/nrg/user/services/UserService.java | 18 - .../impl/hibernate/HibernateUserService.java | 31 - .../nrg/xapi/rest/event/EventHandlerApi.java | 24 +- .../xnat/configuration/ApplicationConfig.java | 106 +++ .../xnat/configuration/ConfigResolver.java | 41 - .../xnat/configuration/FeaturesConfig.java | 12 +- .../org/nrg/xnat/configuration/MqConfig.java | 9 + .../configuration/NotificationsConfig.java | 2 +- .../org/nrg/xnat/configuration/OrmConfig.java | 120 +++ .../xnat/configuration/PrearchiveConfig.java | 15 - .../xnat/configuration/PreferencesConfig.java | 2 +- .../nrg/xnat/configuration/ReactorConfig.java | 35 +- .../xnat/configuration/SchedulerConfig.java | 43 +- .../configuration/SiteConfigPreferences.java | 881 ------------------ .../AutomationEventScriptHandler.java | 524 ++++++----- .../DatabaseConfig.java | 69 +- .../InitializerSiteConfiguration.java | 154 --- .../xnat/initialization/InitializingTask.java | 15 + .../InitializingTasksExecutor.java | 38 + .../PropertiesConfig.java | 2 +- .../nrg/xnat/initialization/RootConfig.java | 112 +-- .../initialization/XnatWebAppInitializer.java | 22 +- .../tasks/AbstractInitializingTask.java | 35 + .../tasks/EncryptXnatPasswords.java | 86 ++ .../tasks/GetSiteWideAnonScript.java | 48 + .../tasks/GetSiteWidePETTracerList.java | 53 ++ .../tasks/UpdateNewSecureDefinitions.java | 36 + .../tasks/UpdateUserAuthTable.java | 62 ++ .../restlet/services/SettingsRestlet.java | 17 +- .../restlet/servlet/XNATRestletServlet.java | 94 -- ...rSecurityInterceptorBeanPostProcessor.java | 23 +- .../nrg/xnat/security/ResetFailedLogins.java | 24 +- .../security/XnatExpiredPasswordFilter.java | 71 +- .../security/XnatLdapUserDetailsMapper.java | 29 +- .../xnat/security/XnatPasswordEncrypter.java | 71 -- .../xnat/security/XnatProviderManager.java | 68 +- .../AliasTokenAuthenticationProvider.java | 8 +- .../alias/ClearExpiredAliasTokens.java | 12 +- ...aseAuthenticationProviderConfigurator.java | 18 +- ...dapAuthenticationProviderConfigurator.java | 14 +- .../XnatDatabaseAuthenticationProvider.java | 18 +- .../XnatDatabaseUserDetailsService.java | 35 +- .../org/nrg/xnat/utils/XnatUserProvider.java | 6 +- .../xnat/entities/xnat-entity-packages.txt | 12 + .../WEB-INF/conf/TurbineResources.properties | 6 +- src/main/webapp/WEB-INF/conf/mq-context.xml | 11 +- .../webapp/WEB-INF/conf/xnat-conf.properties | 6 +- 51 files changed, 1244 insertions(+), 2068 deletions(-) delete mode 100644 src/main/java/org/nrg/schedule/TriggerTaskProxy.java delete mode 100644 src/main/java/org/nrg/user/daos/UserDAO.java delete mode 100644 src/main/java/org/nrg/user/entities/User.java delete mode 100644 src/main/java/org/nrg/user/services/UserService.java delete mode 100644 src/main/java/org/nrg/user/services/impl/hibernate/HibernateUserService.java create mode 100644 src/main/java/org/nrg/xnat/configuration/ApplicationConfig.java delete mode 100644 src/main/java/org/nrg/xnat/configuration/ConfigResolver.java create mode 100644 src/main/java/org/nrg/xnat/configuration/MqConfig.java create mode 100644 src/main/java/org/nrg/xnat/configuration/OrmConfig.java delete mode 100644 src/main/java/org/nrg/xnat/configuration/PrearchiveConfig.java delete mode 100644 src/main/java/org/nrg/xnat/configuration/SiteConfigPreferences.java rename src/main/java/org/nrg/xnat/{configuration => initialization}/DatabaseConfig.java (60%) delete mode 100644 src/main/java/org/nrg/xnat/initialization/InitializerSiteConfiguration.java create mode 100644 src/main/java/org/nrg/xnat/initialization/InitializingTask.java create mode 100644 src/main/java/org/nrg/xnat/initialization/InitializingTasksExecutor.java rename src/main/java/org/nrg/xnat/{configuration => initialization}/PropertiesConfig.java (99%) create mode 100644 src/main/java/org/nrg/xnat/initialization/tasks/AbstractInitializingTask.java create mode 100644 src/main/java/org/nrg/xnat/initialization/tasks/EncryptXnatPasswords.java create mode 100644 src/main/java/org/nrg/xnat/initialization/tasks/GetSiteWideAnonScript.java create mode 100644 src/main/java/org/nrg/xnat/initialization/tasks/GetSiteWidePETTracerList.java create mode 100644 src/main/java/org/nrg/xnat/initialization/tasks/UpdateNewSecureDefinitions.java create mode 100644 src/main/java/org/nrg/xnat/initialization/tasks/UpdateUserAuthTable.java delete mode 100644 src/main/java/org/nrg/xnat/security/XnatPasswordEncrypter.java create mode 100644 src/main/resources/META-INF/xnat/entities/xnat-entity-packages.txt diff --git a/src/main/java/org/nrg/dcm/DicomSCPManager.java b/src/main/java/org/nrg/dcm/DicomSCPManager.java index dc51a81a..8b7b3e3f 100644 --- a/src/main/java/org/nrg/dcm/DicomSCPManager.java +++ b/src/main/java/org/nrg/dcm/DicomSCPManager.java @@ -10,17 +10,18 @@ */ package org.nrg.dcm; -import org.nrg.config.services.SiteConfigurationService; import org.nrg.dcm.preferences.DicomSCPInstance; import org.nrg.dcm.preferences.DicomSCPPreference; import org.nrg.framework.exceptions.NrgServiceError; import org.nrg.framework.exceptions.NrgServiceException; import org.nrg.framework.exceptions.NrgServiceRuntimeException; +import org.nrg.xdat.preferences.SiteConfigPreferences; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; import javax.annotation.PreDestroy; -import javax.inject.Inject; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -37,44 +38,44 @@ public class DicomSCPManager { public DicomSCP create(final DicomSCPInstance instance) throws NrgServiceException { final String scpId = instance.getScpId(); - if (_preferences.hasDicomSCPInstance(scpId)) { + if (_dicomScpPreferences.hasDicomSCPInstance(scpId)) { throw new NrgServiceException(NrgServiceError.ConfigurationError, "There is already a DICOM SCP instance with the ID " + scpId); } try { - _preferences.setDicomSCPInstance(instance); - return _preferences.getDicomSCP(scpId); + _dicomScpPreferences.setDicomSCPInstance(instance); + return _dicomScpPreferences.getDicomSCP(scpId); } catch (IOException e) { throw new NrgServiceRuntimeException(NrgServiceError.Unknown, "Unable to create DICOM SCP: " + instance.getAeTitle() + ":" + instance.getPort(), e); } } public void delete(final String scpId) throws NrgServiceException { - if (!_preferences.hasDicomSCPInstance(scpId)) { + if (!_dicomScpPreferences.hasDicomSCPInstance(scpId)) { throw new NrgServiceException(NrgServiceError.UnknownEntity, "There is no DICOM SCP instance with the ID " + scpId); } - _preferences.deleteDicomSCPInstance(scpId); + _dicomScpPreferences.deleteDicomSCPInstance(scpId); } public List<DicomSCPInstance> getDicomSCPInstances() { - return new ArrayList<>(_preferences.getDicomSCPInstances().values()); + return new ArrayList<>(_dicomScpPreferences.getDicomSCPInstances().values()); } public void setDicomSCPInstance(final DicomSCPInstance instance) { try { - _preferences.setDicomSCPInstance(instance); + _dicomScpPreferences.setDicomSCPInstance(instance); } catch (IOException e) { throw new NrgServiceRuntimeException(NrgServiceError.Unknown, "Unable to update DICOM SCP: " + instance.getAeTitle() + ":" + instance.getPort(), e); } } public List<String> startOrStopDicomSCPAsDictatedByConfiguration() { - final boolean enableDicomReceiver = _siteConfigurationService.getBoolSiteConfigurationProperty("enableDicomReceiver", true); + final boolean enableDicomReceiver = _siteConfigPreferences.isEnableDicomReceiver(); return enableDicomReceiver ? startDicomSCPs() : stopDicomSCPs(); } public List<String> startDicomSCPs() { final List<String> started = new ArrayList<>(); - for (final DicomSCPInstance instance : _preferences.getDicomSCPInstances().values()) { + for (final DicomSCPInstance instance : _dicomScpPreferences.getDicomSCPInstances().values()) { if (instance.isEnabled()) { startDicomSCP(instance); started.add(instance.getScpId()); @@ -84,12 +85,12 @@ public class DicomSCPManager { } public void startDicomSCP(final String scpId) { - startDicomSCP(_preferences.getDicomSCPInstance(scpId)); + startDicomSCP(_dicomScpPreferences.getDicomSCPInstance(scpId)); } public List<String> stopDicomSCPs() { final List<String> stopped = new ArrayList<>(); - for (final DicomSCP dicomSCP : _preferences.getDicomSCPs()) { + for (final DicomSCP dicomSCP : _dicomScpPreferences.getDicomSCPs()) { if (dicomSCP.isStarted()) { dicomSCP.stop(); stopped.add(dicomSCP.getScpId()); @@ -99,12 +100,12 @@ public class DicomSCPManager { } public void stopDicomSCP(final String scpId) { - final DicomSCPInstance instance = _preferences.getDicomSCPInstance(scpId); + final DicomSCPInstance instance = _dicomScpPreferences.getDicomSCPInstance(scpId); if (instance == null) { throw new NrgServiceRuntimeException(NrgServiceError.UnknownEntity, "Couldn't find the DICOM SCP instance identified by " + scpId); } try { - final DicomSCP dicomSCP = _preferences.getDicomSCP(scpId); + final DicomSCP dicomSCP = _dicomScpPreferences.getDicomSCP(scpId); if (dicomSCP != null) { if (dicomSCP.isStarted()) { dicomSCP.stop(); @@ -116,13 +117,13 @@ public class DicomSCPManager { } public void enableDicomSCP(final String scpId) { - final DicomSCPInstance instance = _preferences.getDicomSCPInstance(scpId); + final DicomSCPInstance instance = _dicomScpPreferences.getDicomSCPInstance(scpId); try { if (!instance.isEnabled()) { instance.setEnabled(true); - _preferences.setDicomSCPInstance(instance); + _dicomScpPreferences.setDicomSCPInstance(instance); } - final DicomSCP dicomSCP = _preferences.getDicomSCP(scpId); + final DicomSCP dicomSCP = _dicomScpPreferences.getDicomSCP(scpId); if (!dicomSCP.isStarted()) { dicomSCP.start(); } @@ -132,13 +133,13 @@ public class DicomSCPManager { } public void disableDicomSCP(final String scpId) { - final DicomSCPInstance instance = _preferences.getDicomSCPInstance(scpId); + final DicomSCPInstance instance = _dicomScpPreferences.getDicomSCPInstance(scpId); try { if (instance.isEnabled()) { instance.setEnabled(false); - _preferences.setDicomSCPInstance(instance); + _dicomScpPreferences.setDicomSCPInstance(instance); } - final DicomSCP dicomSCP = _preferences.getDicomSCP(scpId); + final DicomSCP dicomSCP = _dicomScpPreferences.getDicomSCP(scpId); if (dicomSCP.isStarted()) { dicomSCP.stop(); } @@ -149,23 +150,23 @@ public class DicomSCPManager { public Map<String, Boolean> areDicomSCPsStarted() { final Map<String, Boolean> statuses = new HashMap<>(); - for (final DicomSCP dicomSCP : _preferences.getDicomSCPs()) { + for (final DicomSCP dicomSCP : _dicomScpPreferences.getDicomSCPs()) { statuses.put(dicomSCP.getScpId(), dicomSCP.isStarted()); } return statuses; } public boolean hasDicomSCP(final String scpId) { - return _preferences.hasDicomSCPInstance(scpId); + return _dicomScpPreferences.hasDicomSCPInstance(scpId); } public DicomSCPInstance getDicomSCPInstance(final String scpId) { - return _preferences.getDicomSCPInstance(scpId); + return _dicomScpPreferences.getDicomSCPInstance(scpId); } private void startDicomSCP(final DicomSCPInstance instance) { try { - final DicomSCP dicomSCP = _preferences.getDicomSCP(instance.getScpId()); + final DicomSCP dicomSCP = _dicomScpPreferences.getDicomSCP(instance.getScpId()); dicomSCP.start(); } catch (IOException e) { throw new NrgServiceRuntimeException(NrgServiceError.Unknown, "Unable to start DICOM SCP: " + instance.getAeTitle() + ":" + instance.getPort(), e); @@ -174,9 +175,11 @@ public class DicomSCPManager { private static final Logger _log = LoggerFactory.getLogger(DicomSCPManager.class); - @Inject - private SiteConfigurationService _siteConfigurationService; + @Autowired + @Lazy + private DicomSCPPreference _dicomScpPreferences; - @Inject - private DicomSCPPreference _preferences; + @Autowired + @Lazy + private SiteConfigPreferences _siteConfigPreferences; } diff --git a/src/main/java/org/nrg/schedule/TriggerTaskProxy.java b/src/main/java/org/nrg/schedule/TriggerTaskProxy.java deleted file mode 100644 index 562b88d5..00000000 --- a/src/main/java/org/nrg/schedule/TriggerTaskProxy.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.nrg.schedule; - -import org.springframework.scheduling.Trigger; -import org.springframework.scheduling.config.TriggerTask; -import org.springframework.scheduling.support.CronTrigger; -import org.springframework.scheduling.support.PeriodicTrigger; - -import java.util.concurrent.TimeUnit; - -public class TriggerTaskProxy extends TriggerTask { - public TriggerTaskProxy(final Runnable runnable, final long period) { - this(runnable, period, null); - } - - public TriggerTaskProxy(final Runnable runnable, final long period, final TimeUnit timeUnit) { - this(runnable, new PeriodicTrigger(period, timeUnit)); - } - - public TriggerTaskProxy(final Runnable runnable, final long period, final int initialDelay) { - this(runnable, period, null, initialDelay); - } - - public TriggerTaskProxy(final Runnable runnable, final long period, final TimeUnit timeUnit, final int initialDelay) { - this(runnable, new PeriodicTrigger(period, timeUnit) {{ - setInitialDelay(initialDelay); - }}); - } - - public TriggerTaskProxy(final Runnable runnable, final String expression) { - this(runnable, new CronTrigger(expression)); - } - - public TriggerTaskProxy(final Runnable runnable, final Trigger trigger) { - super(runnable, trigger); - } -} diff --git a/src/main/java/org/nrg/user/daos/UserDAO.java b/src/main/java/org/nrg/user/daos/UserDAO.java deleted file mode 100644 index c8dd55c9..00000000 --- a/src/main/java/org/nrg/user/daos/UserDAO.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * org.nrg.user.daos.UserDAO - * XNAT http://www.xnat.org - * Copyright (c) 2014, Washington University School of Medicine - * All Rights Reserved - * - * Released under the Simplified BSD. - * - * Last modified 7/10/13 9:04 PM - */ -package org.nrg.user.daos; - -import org.hibernate.Criteria; -import org.hibernate.criterion.Restrictions; -import org.nrg.framework.orm.hibernate.AbstractHibernateDAO; -import org.nrg.user.entities.User; -import org.springframework.stereotype.Repository; - -@Repository -public class UserDAO extends AbstractHibernateDAO<User> { - - /** - * @param name - * @return - */ - public User getUserByName(String name) { - Criteria criteria = getSession().createCriteria(getParameterizedType()); - criteria.add(Restrictions.eq("name", name)); - criteria.add(Restrictions.eq("enabled", true)); - return (User) criteria.list().get(0); - } - -} diff --git a/src/main/java/org/nrg/user/entities/User.java b/src/main/java/org/nrg/user/entities/User.java deleted file mode 100644 index 78ebb5fa..00000000 --- a/src/main/java/org/nrg/user/entities/User.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * org.nrg.user.entities.User - * XNAT http://www.xnat.org - * Copyright (c) 2014, Washington University School of Medicine - * All Rights Reserved - * - * Released under the Simplified BSD. - * - * Last modified 9/5/13 2:38 PM - */ -package org.nrg.user.entities; - -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; -import org.nrg.framework.orm.hibernate.AbstractHibernateEntity; -import org.nrg.framework.orm.hibernate.annotations.Auditable; - -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; - -@Auditable -@Entity -@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name"})) -@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "nrg") -public class User extends AbstractHibernateEntity { - private static final long serialVersionUID = -163628363303918602L; - - /** - * @param name Sets the name property. - */ - public void setName(String name) { - _name = name; - } - - /** - * @return Returns the name property. - */ - public String getName() { - return _name; - } - - private String _name; -} diff --git a/src/main/java/org/nrg/user/services/UserService.java b/src/main/java/org/nrg/user/services/UserService.java deleted file mode 100644 index b2051d95..00000000 --- a/src/main/java/org/nrg/user/services/UserService.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * org.nrg.user.services.UserService - * XNAT http://www.xnat.org - * Copyright (c) 2014, Washington University School of Medicine - * All Rights Reserved - * - * Released under the Simplified BSD. - * - * Last modified 7/10/13 9:04 PM - */ -package org.nrg.user.services; - -import org.nrg.framework.orm.hibernate.BaseHibernateService; -import org.nrg.user.entities.User; - -public interface UserService extends BaseHibernateService<User> { - abstract public User getUserByName(String name); -} diff --git a/src/main/java/org/nrg/user/services/impl/hibernate/HibernateUserService.java b/src/main/java/org/nrg/user/services/impl/hibernate/HibernateUserService.java deleted file mode 100644 index 897a08f7..00000000 --- a/src/main/java/org/nrg/user/services/impl/hibernate/HibernateUserService.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * org.nrg.user.services.impl.hibernate.HibernateUserService - * XNAT http://www.xnat.org - * Copyright (c) 2014, Washington University School of Medicine - * All Rights Reserved - * - * Released under the Simplified BSD. - * - * Last modified 7/10/13 9:04 PM - */ -package org.nrg.user.services.impl.hibernate; - -import org.nrg.framework.orm.hibernate.AbstractHibernateEntityService; -import org.nrg.user.daos.UserDAO; -import org.nrg.user.entities.User; -import org.nrg.user.services.UserService; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -public class HibernateUserService extends AbstractHibernateEntityService<User, UserDAO> implements UserService { - - /** - * @see org.nrg.user.services.UserService#getUserByName(java.lang.String) - */ - @Override - @Transactional - public User getUserByName(String name) { - return getDao().getUserByName(name); - } -} diff --git a/src/main/java/org/nrg/xapi/rest/event/EventHandlerApi.java b/src/main/java/org/nrg/xapi/rest/event/EventHandlerApi.java index fc39acce..1e0ad096 100644 --- a/src/main/java/org/nrg/xapi/rest/event/EventHandlerApi.java +++ b/src/main/java/org/nrg/xapi/rest/event/EventHandlerApi.java @@ -20,6 +20,7 @@ import org.nrg.xft.security.UserI; import org.nrg.xnat.event.conf.EventPackages; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -49,13 +50,16 @@ public class EventHandlerApi { private static final Logger _log = LoggerFactory.getLogger(EventHandlerApi.class); /** The event ids service. */ + @Autowired private HibernateAutomationEventIdsService eventIdsService; /** The filters service. */ + @Autowired private HibernateAutomationFiltersService filtersService; /** The event packages. */ - private static EventPackages eventPackages; + @Autowired + private EventPackages eventPackages; /** * Inits the this. @@ -64,7 +68,6 @@ public class EventHandlerApi { private void initThis() { getEventIdsService(); getFiltersService(); - getEventPackages(); } /** @@ -82,7 +85,7 @@ public class EventHandlerApi { if (status != null) { return new ResponseEntity<>(status); } - return new ResponseEntity<List<EventClassInfo>>(getEventInfoList(project_id), HttpStatus.OK); + return new ResponseEntity<>(getEventInfoList(project_id), HttpStatus.OK); } /** @@ -99,7 +102,7 @@ public class EventHandlerApi { if (status != null) { return new ResponseEntity<>(status); } - return new ResponseEntity<List<EventClassInfo>>(getEventInfoList(null), HttpStatus.OK); + return new ResponseEntity<>(getEventInfoList(null), HttpStatus.OK); } /** @@ -190,7 +193,6 @@ public class EventHandlerApi { private List<String> getEventClassList(List<AutomationEventIds> eventIdsList) { final List<String> classList = Lists.newArrayList(); // ClassList should be pulled from available event classes rather than from events - final EventPackages eventPackages = getEventPackages(); if (eventPackages != null) { for (final String pkg : eventPackages) { try { @@ -243,18 +245,6 @@ public class EventHandlerApi { return filtersService; } - /** - * Gets the event packages. - * - * @return the event packages - */ - private static EventPackages getEventPackages() { - if (eventPackages == null) { - eventPackages = XDAT.getContextService().getBean("eventPackages",EventPackages.class); - } - return eventPackages; - } - /** * Gets the session user. * diff --git a/src/main/java/org/nrg/xnat/configuration/ApplicationConfig.java b/src/main/java/org/nrg/xnat/configuration/ApplicationConfig.java new file mode 100644 index 00000000..0a2d8fd0 --- /dev/null +++ b/src/main/java/org/nrg/xnat/configuration/ApplicationConfig.java @@ -0,0 +1,106 @@ +package org.nrg.xnat.configuration; + +import org.nrg.config.exceptions.SiteConfigurationException; +import org.nrg.framework.services.ContextService; +import org.nrg.xdat.preferences.InitializerSiteConfiguration; +import org.nrg.xdat.preferences.SiteConfigPreferences; +import org.nrg.xdat.security.HistoricPasswordValidator; +import org.nrg.xdat.security.PasswordValidatorChain; +import org.nrg.xdat.security.RegExpValidator; +import org.nrg.xdat.security.XDATUserMgmtServiceImpl; +import org.nrg.xdat.security.services.UserManagementServiceI; +import org.nrg.xdat.services.ThemeService; +import org.nrg.xdat.services.impl.ThemeServiceImpl; +import org.nrg.xnat.initialization.InitializingTasksExecutor; +import org.nrg.xnat.restlet.XnatRestletExtensions; +import org.nrg.xnat.restlet.actions.importer.ImporterHandlerPackages; +import org.nrg.xnat.utils.XnatUserProvider; +import org.springframework.context.annotation.*; + +import javax.inject.Inject; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; + +@Configuration +@ComponentScan({"org.nrg.automation.repositories", "org.nrg.config.daos", "org.nrg.dcm.xnat", "org.nrg.dicomtools.filters", + "org.nrg.framework.datacache.impl.hibernate", "org.nrg.framework.services.impl", "org.nrg.notify.daos", + "org.nrg.prefs.repositories", "org.nrg.xdat.daos", "org.nrg.xdat.services.impl.hibernate", "org.nrg.xft.daos", + "org.nrg.xft.event.listeners", "org.nrg.xft.services", "org.nrg.xnat.configuration", "org.nrg.xnat.daos", + "org.nrg.xnat.event.listeners", "org.nrg.xnat.helpers.merge", "org.nrg.xnat.initialization.tasks", + "org.nrg.xnat.services", "org.nrg.xnat.services.impl.hibernate", "org.nrg.xnat.spawner.repositories"}) +@Import({FeaturesConfig.class, ReactorConfig.class}) +@ImportResource("WEB-INF/conf/mq-context.xml") +public class ApplicationConfig { + + @Bean + public ThemeService themeService() { + return new ThemeServiceImpl(); + } + + @Bean + @Primary + public ContextService contextService() { + return ContextService.getInstance(); + } + + @Bean + public InitializingTasksExecutor initializingTasksExecutor() { + return new InitializingTasksExecutor(); + } + + @Bean + public SiteConfigPreferences siteConfigPreferences() { + return new SiteConfigPreferences(); + } + + @Bean + public UserManagementServiceI userManagementService() { + // TODO: This should be made to use a preference setting. + return new XDATUserMgmtServiceImpl(); + } + + @Bean + public RegExpValidator regexValidator() throws SiteConfigurationException { + final String complexityExpression = _preferences.getPasswordComplexity(); + final String complexityMessage = _preferences.getPasswordComplexityMessage(); + return new RegExpValidator(complexityExpression, complexityMessage); + } + + @Bean + public HistoricPasswordValidator historicPasswordValidator() throws SiteConfigurationException { + final int durationInDays = _preferences.getPasswordHistoryDuration(); + return new HistoricPasswordValidator(durationInDays); + } + + @Bean + public PasswordValidatorChain validator(final RegExpValidator regExpValidator, final HistoricPasswordValidator historicPasswordValidator) { + return new PasswordValidatorChain(Arrays.asList(regExpValidator, historicPasswordValidator)); + } + + // MIGRATION: I'm not even sure this is used, but we need to do away with it in favor of prefs. + @Bean + public List<String> propertiesRepositories() { + return Collections.singletonList("WEB-INF/conf/properties"); + } + + @Bean + public XnatUserProvider receivedFileUserProvider() throws SiteConfigurationException { + final String receivedFileUser = _preferences.getReceivedFileUser(); + return new XnatUserProvider(receivedFileUser); + } + + @Bean + public XnatRestletExtensions xnatRestletExtensions() { + return new XnatRestletExtensions(new HashSet<>(Arrays.asList(new String[]{"org.nrg.xnat.restlet.extensions"}))); + } + + @Bean + public ImporterHandlerPackages importerHandlerPackages() { + return new ImporterHandlerPackages(new HashSet<>(Arrays.asList(new String[]{"org.nrg.xnat.restlet.actions", "org.nrg.xnat.archive"}))); + } + + @Inject + private InitializerSiteConfiguration _preferences; +} diff --git a/src/main/java/org/nrg/xnat/configuration/ConfigResolver.java b/src/main/java/org/nrg/xnat/configuration/ConfigResolver.java deleted file mode 100644 index 6af8f304..00000000 --- a/src/main/java/org/nrg/xnat/configuration/ConfigResolver.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.nrg.xnat.configuration; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import javax.annotation.Resource; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.util.List; - -@Component -public class ConfigResolver { - - public InputStream getConfigurationFile(final String name) throws IOException { - for (final Path configFolder : _configFolderPaths) { - final Path configFile = configFolder.resolve(name); - if (_log.isDebugEnabled()) { - _log.info("Searching for the configuration file {} in the path {}.", name, configFile.toString()); - } - if (configFile.toFile().exists()) { - if (_log.isInfoEnabled()) { - _log.info("Found the configuration file {} in the path {}, returning.", name, configFile.toString()); - } - return Files.newInputStream(configFile, StandardOpenOption.READ); - } - } - if (_log.isDebugEnabled()) { - _log.info("Found no configuration file named {} on any of the available configuration folders."); - } - return null; - } - - private static final Logger _log = LoggerFactory.getLogger(ConfigResolver.class); - - @Resource(name="configFolderPaths") - private List<Path> _configFolderPaths; -} diff --git a/src/main/java/org/nrg/xnat/configuration/FeaturesConfig.java b/src/main/java/org/nrg/xnat/configuration/FeaturesConfig.java index 5ed2a0c8..450b4565 100644 --- a/src/main/java/org/nrg/xnat/configuration/FeaturesConfig.java +++ b/src/main/java/org/nrg/xnat/configuration/FeaturesConfig.java @@ -2,11 +2,11 @@ package org.nrg.xnat.configuration; import org.apache.commons.lang3.StringUtils; import org.nrg.config.exceptions.SiteConfigurationException; +import org.nrg.xdat.preferences.InitializerSiteConfiguration; import org.nrg.xdat.security.services.FeatureRepositoryServiceI; import org.nrg.xdat.security.services.FeatureServiceI; import org.nrg.xdat.security.services.RoleRepositoryServiceI; import org.nrg.xdat.security.services.RoleServiceI; -import org.nrg.xnat.initialization.InitializerSiteConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; @@ -14,14 +14,14 @@ import org.springframework.context.annotation.Configuration; import javax.inject.Inject; +import static org.nrg.xdat.security.services.FeatureRepositoryServiceI.DEFAULT_FEATURE_REPO_SERVICE; +import static org.nrg.xdat.security.services.FeatureServiceI.DEFAULT_FEATURE_SERVICE; +import static org.nrg.xdat.security.services.RoleRepositoryServiceI.DEFAULT_ROLE_REPO_SERVICE; +import static org.nrg.xdat.security.services.RoleServiceI.DEFAULT_ROLE_SERVICE; + @Configuration public class FeaturesConfig { - public static final String DEFAULT_FEATURE_SERVICE = "org.nrg.xdat.security.services.impl.FeatureServiceImpl"; - public static final String DEFAULT_FEATURE_REPO_SERVICE = "org.nrg.xdat.security.services.impl.FeatureRepositoryServiceImpl"; - public static final String DEFAULT_ROLE_SERVICE = "org.nrg.xdat.security.services.impl.RoleServiceImpl"; - public static final String DEFAULT_ROLE_REPO_SERVICE = "org.nrg.xdat.security.services.impl.RoleRepositoryServiceImpl"; - @Bean public FeatureServiceI featureService() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SiteConfigurationException { final String serviceImpl = StringUtils.defaultIfBlank(_preferences.getFeatureService(), DEFAULT_FEATURE_SERVICE); diff --git a/src/main/java/org/nrg/xnat/configuration/MqConfig.java b/src/main/java/org/nrg/xnat/configuration/MqConfig.java new file mode 100644 index 00000000..993e9e95 --- /dev/null +++ b/src/main/java/org/nrg/xnat/configuration/MqConfig.java @@ -0,0 +1,9 @@ +package org.nrg.xnat.configuration; + +import org.springframework.context.annotation.Configuration; +// import org.springframework.jms.annotation.EnableJms; + +@Configuration +// @EnableJms +public class MqConfig { +} diff --git a/src/main/java/org/nrg/xnat/configuration/NotificationsConfig.java b/src/main/java/org/nrg/xnat/configuration/NotificationsConfig.java index a132589a..41275904 100644 --- a/src/main/java/org/nrg/xnat/configuration/NotificationsConfig.java +++ b/src/main/java/org/nrg/xnat/configuration/NotificationsConfig.java @@ -6,7 +6,7 @@ import org.nrg.framework.orm.hibernate.HibernateEntityPackageList; import org.nrg.notify.entities.ChannelRendererProvider; import org.nrg.notify.renderers.ChannelRenderer; import org.nrg.notify.renderers.NrgMailChannelRenderer; -import org.nrg.xnat.initialization.InitializerSiteConfiguration; +import org.nrg.xdat.preferences.InitializerSiteConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; diff --git a/src/main/java/org/nrg/xnat/configuration/OrmConfig.java b/src/main/java/org/nrg/xnat/configuration/OrmConfig.java new file mode 100644 index 00000000..1e658387 --- /dev/null +++ b/src/main/java/org/nrg/xnat/configuration/OrmConfig.java @@ -0,0 +1,120 @@ +package org.nrg.xnat.configuration; + +import org.apache.commons.io.IOUtils; +import org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory; +import org.hibernate.cache.spi.RegionFactory; +import org.hibernate.cfg.ImprovedNamingStrategy; +import org.nrg.framework.exceptions.NrgServiceError; +import org.nrg.framework.exceptions.NrgServiceException; +import org.nrg.framework.orm.hibernate.PrefixedTableNamingStrategy; +import org.nrg.framework.utilities.BasicXnatResourceLocator; +import org.nrg.framework.utilities.Beans; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.PropertiesFactoryBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.core.io.Resource; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.inject.Inject; +import javax.sql.DataSource; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +@Configuration +@EnableTransactionManagement(proxyTargetClass = true) +public class OrmConfig { + @Bean + public ImprovedNamingStrategy namingStrategy() { + return new PrefixedTableNamingStrategy("xhbm"); + } + + @Bean + public PropertiesFactoryBean hibernateProperties() { + final PropertiesFactoryBean bean = new PropertiesFactoryBean(); + final Properties properties = Beans.getNamespacedProperties(_environment, "hibernate", false); + if (properties.size() == 0) { + if (_log.isDebugEnabled()) { + final StringBuilder message = new StringBuilder("No Hibernate properties specified, using default properties:\n"); + for (final String property : DEFAULT_HIBERNATE_PROPERTIES.stringPropertyNames()) { + message.append(" * ").append(property).append(": ").append(DEFAULT_HIBERNATE_PROPERTIES.getProperty(property)).append("\n"); + } + _log.debug(message.toString()); + } + properties.putAll(DEFAULT_HIBERNATE_PROPERTIES); + } + bean.setProperties(properties); + return bean; + } + + @Bean + public RegionFactory regionFactory() throws NrgServiceException { + try { + return new SingletonEhCacheRegionFactory(hibernateProperties().getObject()); + } catch (IOException e) { + throw new NrgServiceException(NrgServiceError.Unknown, "An error occurred trying to retrieve the Hibernate properties", e); + } + } + + @Bean + public LocalSessionFactoryBean sessionFactory(final DataSource dataSource) throws NrgServiceException { + try { + final LocalSessionFactoryBean bean = new LocalSessionFactoryBean(); + final String[] packages = getXnatEntityPackages(); + if (_log.isDebugEnabled()) { + final StringBuilder message = new StringBuilder("The following packages will be scanned for persistent entities:\n"); + for (final String packageName : packages) { + message.append(" * ").append(packageName).append("\n"); + } + _log.debug(message.toString()); + } + bean.setPackagesToScan(packages); + bean.setDataSource(dataSource); + bean.setCacheRegionFactory(regionFactory()); + bean.setHibernateProperties(hibernateProperties().getObject()); + bean.setNamingStrategy(namingStrategy()); + return bean; + } catch (IOException e) { + throw new NrgServiceException(NrgServiceError.Unknown, "An error occurred trying to retrieve the Hibernate properties", e); + } + } + + @Bean + public PlatformTransactionManager transactionManager(final DataSource dataSource) throws NrgServiceException { + return new HibernateTransactionManager(sessionFactory(dataSource).getObject()); + } + + private static String[] getXnatEntityPackages() throws IOException { + final List<String> packages = new ArrayList<>(); + for (final Resource resource : BasicXnatResourceLocator.getResources("classpath*:META-INF/xnat/entities/**/*-entity-packages.txt")) { + if (_log.isDebugEnabled()) { + _log.debug("Processing entity packages from the resource: " + resource.getFilename()); + } + try (final InputStream input = resource.getInputStream()) { + packages.addAll(IOUtils.readLines(input, "UTF-8")); + } + } + return packages.toArray(new String[packages.size()]); + } + + private static final Properties DEFAULT_HIBERNATE_PROPERTIES = new Properties() {{ + setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect"); + setProperty("hibernate.hbm2ddl.auto", "update"); + setProperty("hibernate.show_sql", "false"); + setProperty("hibernate.cache.use_second_level_cache", "true"); + setProperty("hibernate.cache.use_query_cache", "true"); + }}; + + private static final Logger _log = LoggerFactory.getLogger(OrmConfig.class); + + @Inject + private Environment _environment; +} diff --git a/src/main/java/org/nrg/xnat/configuration/PrearchiveConfig.java b/src/main/java/org/nrg/xnat/configuration/PrearchiveConfig.java deleted file mode 100644 index 54129564..00000000 --- a/src/main/java/org/nrg/xnat/configuration/PrearchiveConfig.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.nrg.xnat.configuration; - -import org.nrg.xnat.helpers.prearchive.PrearcConfig; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class PrearchiveConfig { - @Bean - public PrearcConfig prearcConfig() { - final PrearcConfig prearcConfig = new PrearcConfig(); - prearcConfig.setReloadPrearcDatabaseOnApplicationStartup(false); - return prearcConfig; - } -} diff --git a/src/main/java/org/nrg/xnat/configuration/PreferencesConfig.java b/src/main/java/org/nrg/xnat/configuration/PreferencesConfig.java index 9fcf0b5e..7154bfe7 100644 --- a/src/main/java/org/nrg/xnat/configuration/PreferencesConfig.java +++ b/src/main/java/org/nrg/xnat/configuration/PreferencesConfig.java @@ -8,7 +8,7 @@ import org.nrg.config.services.impl.DefaultConfigService; import org.nrg.config.services.impl.DefaultUserConfigurationService; import org.nrg.prefs.configuration.NrgPrefsServiceConfiguration; import org.nrg.prefs.services.PreferenceService; -import org.nrg.xnat.initialization.InitializerSiteConfiguration; +import org.nrg.xdat.preferences.InitializerSiteConfiguration; import org.nrg.xnat.resolvers.XnatPreferenceEntityResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; diff --git a/src/main/java/org/nrg/xnat/configuration/ReactorConfig.java b/src/main/java/org/nrg/xnat/configuration/ReactorConfig.java index 50fa720b..f1581c29 100755 --- a/src/main/java/org/nrg/xnat/configuration/ReactorConfig.java +++ b/src/main/java/org/nrg/xnat/configuration/ReactorConfig.java @@ -1,18 +1,36 @@ package org.nrg.xnat.configuration; +import org.nrg.xft.event.XftEventService; +import org.nrg.xft.event.listeners.XftItemEventListener; +import org.nrg.xnat.event.conf.EventPackages; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; - import reactor.Environment; import reactor.bus.EventBus; +import java.util.Arrays; +import java.util.HashSet; + /** * The Class ReactorConfig. */ @Configuration -@ComponentScan({"org.nrg.xnat.event.listeners, org.nrg.xft.event, org.nrg.xft.event.listeners"}) public class ReactorConfig { + @Bean + public XftEventService xftEventService() { + return new XftEventService(); + } + + @Bean + public XftItemEventListener xftItemEventListener(final EventBus eventBus) { + return new XftItemEventListener(eventBus); + } + + @Bean + public EventPackages eventPackages() { + // NOTE: These should be treated as parent packages. All sub-packages should be searched + return new EventPackages(new HashSet<>(Arrays.asList(new String[]{"org.nrg.xnat.event", "org.nrg.xft.event", "org.nrg.xdat.event"}))); + } /** * Env. @@ -20,20 +38,19 @@ public class ReactorConfig { * @return the environment */ @Bean - Environment env() { - return Environment.initializeIfEmpty() - .assignErrorJournal(); + public Environment env() { + return Environment.initializeIfEmpty().assignErrorJournal(); } /** * Creates the event bus. * * @param env the env + * * @return the event bus */ @Bean - EventBus createEventBus(Environment env) { - return EventBus.create(env, Environment.THREAD_POOL); + public EventBus createEventBus(Environment env) { + return EventBus.create(env, Environment.THREAD_POOL); } - } diff --git a/src/main/java/org/nrg/xnat/configuration/SchedulerConfig.java b/src/main/java/org/nrg/xnat/configuration/SchedulerConfig.java index d6715fc0..540fee31 100644 --- a/src/main/java/org/nrg/xnat/configuration/SchedulerConfig.java +++ b/src/main/java/org/nrg/xnat/configuration/SchedulerConfig.java @@ -2,52 +2,58 @@ package org.nrg.xnat.configuration; import org.nrg.config.exceptions.SiteConfigurationException; import org.nrg.mail.services.EmailRequestLogService; -import org.nrg.schedule.TriggerTaskProxy; +import org.nrg.xdat.preferences.InitializerSiteConfiguration; import org.nrg.xnat.helpers.prearchive.SessionXMLRebuilder; -import org.nrg.xnat.initialization.InitializerSiteConfiguration; import org.nrg.xnat.security.DisableInactiveUsers; import org.nrg.xnat.security.ResetEmailRequests; import org.nrg.xnat.security.ResetFailedLogins; import org.nrg.xnat.security.alias.ClearExpiredAliasTokens; import org.nrg.xnat.utils.XnatUserProvider; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jms.core.JmsTemplate; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.config.ScheduledTaskRegistrar; +import org.springframework.scheduling.config.TriggerTask; +import org.springframework.scheduling.support.CronTrigger; +import org.springframework.scheduling.support.PeriodicTrigger; import javax.inject.Inject; -import javax.sql.DataSource; import java.util.List; @Configuration @EnableScheduling public class SchedulerConfig implements SchedulingConfigurer { @Bean - public TriggerTaskProxy disableInactiveUsers() throws SiteConfigurationException { - return new TriggerTaskProxy(new DisableInactiveUsers(_preferences.getInactivityBeforeLockout()), _preferences.getInactivityBeforeLockoutSchedule()); + public TriggerTask disableInactiveUsers() throws SiteConfigurationException { + return new TriggerTask(new DisableInactiveUsers(_preferences.getInactivityBeforeLockout()), new CronTrigger(_preferences.getInactivityBeforeLockoutSchedule())); } @Bean - public TriggerTaskProxy resetFailedLogins() throws SiteConfigurationException { - return new TriggerTaskProxy(new ResetFailedLogins(_dataSource), _preferences.getMaxFailedLoginsLockoutDuration()); + public TriggerTask resetFailedLogins() throws SiteConfigurationException { + return new TriggerTask(new ResetFailedLogins(_template, _preferences.getMaxFailedLoginsLockoutDuration()), new PeriodicTrigger(900000)); } @Bean - public TriggerTaskProxy resetEmailRequests() { - return new TriggerTaskProxy(new ResetEmailRequests(_emailRequestLogService), 900000); + public TriggerTask resetEmailRequests() { + return new TriggerTask(new ResetEmailRequests(_emailRequestLogService), new PeriodicTrigger(900000)); } @Bean - public TriggerTaskProxy clearExpiredAliasTokens() throws SiteConfigurationException { - return new TriggerTaskProxy(new ClearExpiredAliasTokens(_dataSource, _preferences.getAliasTokenTimeout()), 3600000); + public TriggerTask clearExpiredAliasTokens() throws SiteConfigurationException { + return new TriggerTask(new ClearExpiredAliasTokens(_template, _preferences.getAliasTokenTimeout()), new PeriodicTrigger(3600000)); } @Bean - public TriggerTaskProxy rebuildSessionéXmls() throws SiteConfigurationException { - return new TriggerTaskProxy(new SessionXMLRebuilder(_provider, _preferences.getSessionXmlRebuilderInterval(), _jmsTemplate), _preferences.getSessionXmlRebuilderRepeat(), 60000); + public TriggerTask rebuildSessionXmls() throws SiteConfigurationException { + final PeriodicTrigger trigger = new PeriodicTrigger(_preferences.getSessionXmlRebuilderRepeat()); + trigger.setInitialDelay(60000); + return new TriggerTask(new SessionXMLRebuilder(_provider, _preferences.getSessionXmlRebuilderInterval(), _jmsTemplate), trigger); } @Bean(destroyMethod = "shutdown") @@ -63,17 +69,18 @@ public class SchedulerConfig implements SchedulingConfigurer { // taskRegistrar.addTriggerTask(resetEmailRequests()); // taskRegistrar.addTriggerTask(clearExpiredAliasTokens()); // taskRegistrar.addTriggerTask(rebuildSessionXmls()); - for (final TriggerTaskProxy triggerTask : _triggerTasks) { + for (final TriggerTask triggerTask : _triggerTasks) { taskRegistrar.addTriggerTask(triggerTask); } } - @Inject - private DataSource _dataSource; - @Inject private EmailRequestLogService _emailRequestLogService; + @Autowired + @Lazy + private JdbcTemplate _template; + @Inject private XnatUserProvider _provider; @@ -85,5 +92,5 @@ public class SchedulerConfig implements SchedulingConfigurer { @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") @Inject - private List<TriggerTaskProxy> _triggerTasks; + private List<TriggerTask> _triggerTasks; } \ No newline at end of file diff --git a/src/main/java/org/nrg/xnat/configuration/SiteConfigPreferences.java b/src/main/java/org/nrg/xnat/configuration/SiteConfigPreferences.java deleted file mode 100644 index afe93e53..00000000 --- a/src/main/java/org/nrg/xnat/configuration/SiteConfigPreferences.java +++ /dev/null @@ -1,881 +0,0 @@ -package org.nrg.xnat.configuration; - -import org.nrg.prefs.annotations.NrgPreference; -import org.nrg.prefs.annotations.NrgPreferenceBean; -import org.nrg.prefs.beans.AbstractPreferenceBean; -import org.nrg.prefs.exceptions.InvalidPreferenceName; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Date; -import java.util.List; -import java.util.Map; - -@NrgPreferenceBean(toolId = SiteConfigPreferences.SITE_CONFIG_TOOL_ID, - toolName = "XNAT Site Preferences", - description = "Manages site configurations and settings for the XNAT system.", - - strict = false) -public class SiteConfigPreferences extends AbstractPreferenceBean { - public static final String SITE_CONFIG_TOOL_ID = "siteConfig"; - - @NrgPreference(defaultValue = "XNAT") - public String getSiteTitle() { - return getValue("siteTitle"); - } - - public void setSiteTitle(final String siteTitle) { - try { - set(siteTitle, "siteTitle"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name siteTitle: something is very wrong here.", e); - } - } - - @NrgPreference - public String getSiteUrl() { - return getValue("siteUrl"); - } - - public void setSiteUrl(final String siteUrl) { - try { - set(siteUrl, "siteUrl"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name siteUrl: something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "you@yoursite.org") - public String getAdminEmail() { - return getValue("adminEmail"); - } - - public void setAdminEmail(final String adminEmail) { - try { - set(adminEmail, "adminEmail"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'adminEmail': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "/data/xnat/archive") - public String getArchiveRootPath() { - return getValue("archiveRootPath"); - } - - public void setArchiveRootPath(final String archiveRootPath) { - try { - set(archiveRootPath, "archiveRootPath"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'archiveRootPath': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "/data/xnat/prearchive") - public String getPrearchivePath() { - return getValue("prearchivePath"); - } - - public void setPrearchivePath(final String prearchivePath) { - try { - set(prearchivePath, "prearchivePath"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'prearchivePath': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "/data/xnat/cache") - public String getCachePath() { - return getValue("cachePath"); - } - - public void setCachePath(final String cachePath) { - try { - set(cachePath, "cachePath"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'cachePath': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "/data/xnat/ftp") - public String getFtpPath() { - return getValue("ftpPath"); - } - - public void setFtpPath(final String ftpPath) { - try { - set(ftpPath, "ftpPath"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'ftpPath': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "/data/xnat/build") - public String getBuildPath() { - return getValue("buildPath"); - } - - public void setBuildPath(final String buildPath) { - try { - set(buildPath, "buildPath"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'buildPath': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "/data/xnat/pipeline") - public String getPipelinePath() { - return getValue("pipelinePath"); - } - - public void setPipelinePath(final String pipelinePath) { - try { - set(pipelinePath, "pipelinePath"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'pipelinePath': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "{'host':'mail.server','port':'25'}") - public Map<String, String> getSmtpServer() { - return getMapValue("smtpServer"); - } - - public void setSmtpServer(final Map<String, String> smtpServer) { - try { - setMapValue("smtpServer", smtpServer); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'smtpServer': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "^.*$") - public String getPasswordComplexity() { - return getValue("passwordComplexity"); - } - - public void setPasswordComplexity(final String passwordComplexity) { - try { - set(passwordComplexity, "passwordComplexity"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'passwordComplexity': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "Password is not sufficiently complex.") - public String getPasswordComplexityMessage() { - return getValue("passwordComplexityMessage"); - } - - public void setPasswordComplexityMessage(final String passwordComplexityMessage) { - try { - set(passwordComplexityMessage, "passwordComplexityMessage"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'passwordComplexityMessage': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "365") - public int getPasswordHistoryDuration() { - return getIntegerValue("passwordHistoryDuration"); - } - - public void setPasswordHistoryDuration(final int passwordHistoryDuration) { - try { - setIntegerValue(passwordHistoryDuration, "passwordHistoryDuration"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'passwordHistoryDuration': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true") - public boolean getRequireLogin() { - return getBooleanValue("requireLogin"); - } - - public void setRequireLogin(final boolean requireLogin) { - try { - setBooleanValue(requireLogin, "requireLogin"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'requireLogin': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "false") - public boolean getUserRegistration() { - return getBooleanValue("userRegistration"); - } - - public void setUserRegistration(final boolean userRegistration) { - try { - setBooleanValue(userRegistration, "userRegistration"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'userRegistration': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true") - public boolean getEmailVerification() { - return getBooleanValue("emailVerification"); - } - - public void setEmailVerification(final boolean emailVerification) { - try { - setBooleanValue(emailVerification, "emailVerification"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'emailVerification': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true") - public boolean getEnableCsrfToken() { - return getBooleanValue("enableCsrfToken"); - } - - public void setEnableCsrfToken(final boolean enableCsrfToken) { - try { - setBooleanValue(enableCsrfToken, "enableCsrfToken"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'enableCsrfToken': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "false") - public boolean getRestrictUserListAccessToAdmins() { - return getBooleanValue("restrictUserListAccessToAdmins"); - } - - public void setRestrictUserListAccessToAdmins(final boolean restrictUserListAccessToAdmins) { - try { - setBooleanValue(restrictUserListAccessToAdmins, "restrictUserListAccessToAdmins"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'restrictUserListAccessToAdmins': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true") - public boolean getRequireSaltedPasswords() { - return getBooleanValue("requireSaltedPasswords"); - } - - public void setRequireSaltedPasswords(final boolean requireSaltedPasswords) { - try { - setBooleanValue(requireSaltedPasswords, "requireSaltedPasswords"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'requireSaltedPasswords': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true") - public boolean getEmailAllowNonuserSubscribers() { - return getBooleanValue("emailAllowNonuserSubscribers"); - } - - public void setEmailAllowNonuserSubscribers(final boolean emailAllowNonuserSubscribers) { - try { - setBooleanValue(emailAllowNonuserSubscribers, "emailAllowNonuserSubscribers"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'emailAllowNonuserSubscribers': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "Interval") - public String getPasswordExpirationType() { - return getValue("passwordExpirationType"); - } - - public void setPasswordExpirationType(final String passwordExpirationType) { - try { - set(passwordExpirationType, "passwordExpirationType"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'passwordExpirationType': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "365") - public int getPasswordExpirationInterval() { - return getIntegerValue("passwordExpirationInterval"); - } - - public void setPasswordExpirationInterval(final int passwordExpirationInterval) { - try { - setIntegerValue(passwordExpirationInterval, "passwordExpirationInterval"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'passwordExpirationInterval': something is very wrong here.", e); - } - } - - @NrgPreference - public Date getPasswordExpirationDate() { - return getDateValue("passwordExpirationDate"); - } - - public void setPasswordExpirationDate(final Date passwordExpirationDate) { - try { - setDateValue(passwordExpirationDate, "passwordExpirationDate"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'passwordExpirationDate': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "false") - public boolean getShowApplet() { - return getBooleanValue("showApplet"); - } - - public void setShowApplet(final boolean showApplet) { - try { - setBooleanValue(showApplet, "showApplet"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'showApplet': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "false") - public boolean getEnableProjectAppletScript() { - return getBooleanValue("enableProjectAppletScript"); - } - - public void setEnableProjectAppletScript(final boolean enableProjectAppletScript) { - try { - setBooleanValue(enableProjectAppletScript, "enableProjectAppletScript"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'enableProjectAppletScript': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true") - public boolean getChecksums() { - return getBooleanValue("checksums"); - } - - public void setChecksums(final boolean checksums) { - try { - setBooleanValue(checksums, "checksums"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'checksums': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true") - public boolean getScanTypeMapping() { - return getBooleanValue("scanTypeMapping"); - } - - public void setScanTypeMapping(final boolean scanTypeMapping) { - try { - setBooleanValue(scanTypeMapping, "scanTypeMapping"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'scanTypeMapping': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "org.nrg.xnat.utils.ChecksumsSiteConfigurationListener", property = "checksums.property.changed.listener") - public String getChecksumsPropertyChangedListener() { - return getValue("checksums.property.changed.listener"); - } - - public void setChecksumsPropertyChangedListener(final String checksumsPropertyChangedListener) { - try { - set(checksumsPropertyChangedListener, "checksums.property.changed.listener"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'checksums.property.changed.listener': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true") - public boolean isEnableDicomReceiver() { - return getBooleanValue("enableDicomReceiver"); - } - - public void setEnableDicomReceiver(final boolean enableDicomReceiver) { - try { - setBooleanValue(enableDicomReceiver, "enableDicomReceiver"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'enableDicomReceiver': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "org.nrg.dcm.DicomSCPSiteConfigurationListener", property = "enableDicomReceiver.property.changed.listener") - public String getEnableDicomReceiverPropertyChangedListener() { - return getValue("enableDicomReceiver.property.changed.listener"); - } - - public void setEnableDicomReceiverPropertyChangedListener(final String enableDicomReceiverPropertyChangedListener) { - try { - set(enableDicomReceiverPropertyChangedListener, "enableDicomReceiver.property.changed.listener"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'enableDicomReceiver.property.changed.listener': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "admin") - public String getReceivedFileUser() { - return getValue("receivedFileUser"); - } - - public void setReceivedFileUser(final String receivedFileUser) { - try { - set(receivedFileUser, "receivedFileUser"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'receivedFileUser': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "Session", property = "displayNameForGenericImageSession.singular") - public String getImageSessionDisplayNameSingular() { - return getValue("displayNameForGenericImageSession.singular"); - } - - public void setImageSessionDisplayNameSingular(final String displayNameForGenericImageSessionSingular) { - try { - set(displayNameForGenericImageSessionSingular, "displayNameForGenericImageSession.singular"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'displayNameForGenericImageSession.singular': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "Sessions", property = "displayNameForGenericImageSession.plural") - public String getImageSessionDisplayNamePlural() { - return getValue("displayNameForGenericImageSession.plural"); - } - - public void setImageSessionDisplayNamePlural(final String displayNameForGenericImageSessionPlural) { - try { - set(displayNameForGenericImageSessionPlural, "displayNameForGenericImageSession.plural"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'displayNameForGenericImageSession.plural': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "['zip','jar','rar','ear','gar','mrb']") - public List<String> getZipExtensions() { - return getListValue("zipExtensions"); - } - - public void setZipExtensions(final List<String> zipExtensions) { - try { - setListValue("zipExtensions", zipExtensions); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'zipExtensions': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "Page") - public String getSiteDescriptionType() { - return getValue("siteDescriptionType"); - } - - public void setSiteDescriptionType(final String siteDescriptionType) { - try { - set(siteDescriptionType, "siteDescriptionType"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'siteDescriptionType': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "/screens/site_description.vm") - public String getSiteDescriptionPage() { - return getValue("siteDescriptionPage"); - } - - public void setSiteDescriptionPage(final String siteDescriptionPage) { - try { - set(siteDescriptionPage, "siteDescriptionPage"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'siteDescriptionPage': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "SITE DESCRIPTION HERE: Go to Administer -> Configuration -> Site Information to change.") - public String getSiteDescriptionText() { - return getValue("siteDescriptionText"); - } - - public void setSiteDescriptionText(final String siteDescriptionText) { - try { - set(siteDescriptionText, "siteDescriptionText"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'siteDescriptionText': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "/screens/QuickSearch.vm") - public String getSiteLoginLanding() { - return getValue("siteLoginLanding"); - } - - public void setSiteLoginLanding(final String siteLoginLanding) { - try { - set(siteLoginLanding, "siteLoginLanding"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'siteLoginLanding': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "/Index.vm") - public String getSiteLandingLayout() { - return getValue("siteLandingLayout"); - } - - public void setSiteLandingLayout(final String siteLandingLayout) { - try { - set(siteLandingLayout, "siteLandingLayout"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'siteLandingLayout': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "/screens/QuickSearch.vm") - public String getSiteHome() { - return getValue("siteHome"); - } - - public void setSiteHome(final String siteHome) { - try { - set(siteHome, "siteHome"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'siteHome': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "/Index.vm") - public String getSiteHomeLayout() { - return getValue("siteHomeLayout"); - } - - public void setSiteHomeLayout(final String siteHomeLayout) { - try { - set(siteHomeLayout, "siteHomeLayout"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'siteHomeLayout': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "false", property = "UI.debug-extension-points") - public boolean getUiDebugExtensionPoints() { - return getBooleanValue("UI.debug-extension-points"); - } - - public void setUiDebugExtensionPoints(final boolean uiDebugExtensionPoints) { - try { - setBooleanValue(uiDebugExtensionPoints, "UI.debug-extension-points"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'UI.debug-extension-points': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true", property = "UI.allow-advanced-search") - public boolean getUiAllowAdvancedSearch() { - return getBooleanValue("UI.allow-advanced-search"); - } - - public void setuiAllowAdvancedSearch(final boolean uiAllowAdvancedSearch) { - try { - setBooleanValue(uiAllowAdvancedSearch, "UI.allow-advanced-search"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'UI.allow-advanced-search': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true", property = "UI.allow-new-user-comments") - public boolean getUiAllowNewUserComments() { - return getBooleanValue("UI.allow-new-user-comments"); - } - - public void setUiAllowNewUserComments(final boolean uiAllowNewUserComments) { - try { - setBooleanValue(uiAllowNewUserComments, "UI.allow-new-user-comments"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'UI.allow-new-user-comments': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true", property = "UI.allow-scan-addition") - public boolean getUiAllowScanAddition() { - return getBooleanValue("UI.allow-scan-addition"); - } - - public void setUiAllowScanAddition(final boolean uiAllowScanAddition) { - try { - setBooleanValue(uiAllowScanAddition, "UI.allow-scan-addition"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'UI.allow-scan-addition': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true", property = "UI.show-left-bar") - public boolean getUiShowLeftBar() { - return getBooleanValue("UI.show-left-bar"); - } - - public void setUiShowLeftBar(final boolean uiShowLeftBar) { - try { - setBooleanValue(uiShowLeftBar, "UI.show-left-bar"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'UI.show-left-bar': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true", property = "UI.show-left-bar-projects") - public boolean getUiShowLeftBarProjects() { - return getBooleanValue("UI.show-left-bar-projects"); - } - - public void setUiShowLeftBarProjects(final boolean uiShowLeftBarProjects) { - try { - setBooleanValue(uiShowLeftBarProjects, "UI.show-left-bar-projects"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'UI.show-left-bar-projects': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true", property = "UI.show-left-bar-favorites") - public boolean getUiShowLeftBarFavorites() { - return getBooleanValue("UI.show-left-bar-favorites"); - } - - public void setUiShowLeftBarFavorites(final boolean uiShowLeftBarFavorites) { - try { - setBooleanValue(uiShowLeftBarFavorites, "UI.show-left-bar-favorites"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'UI.show-left-bar-favorites': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true", property = "UI.show-left-bar-search") - public boolean getUiShowLeftBarSearch() { - return getBooleanValue("UI.show-left-bar-search"); - } - - public void setUiShowLeftBarSearch(final boolean uiShowLeftBarSearch) { - try { - setBooleanValue(uiShowLeftBarSearch, "UI.show-left-bar-search"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'UI.show-left-bar-search': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true", property = "UI.show-left-bar-browse") - public boolean getUiShowLeftBarBrowse() { - return getBooleanValue("UI.show-left-bar-browse"); - } - - public void setUiShowLeftBarBrowse(final boolean uiShowLeftBarBrowse) { - try { - setBooleanValue(uiShowLeftBarBrowse, "UI.show-left-bar-browse"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'UI.show-left-bar-browse': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true", property = "UI.show-manage-files") - public boolean getUiShowManageFiles() { - return getBooleanValue("UI.show-manage-files"); - } - - public void setUiShowManageFiles(final boolean uiShowManageFiles) { - try { - setBooleanValue(uiShowManageFiles, "UI.show-manage-files"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'UI.show-manage-files': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "true", property = "UI.allow-non-admin-project-creation") - public boolean getUiAllowNonAdminProjectCreation() { - return getBooleanValue("UI.allow-non-admin-project-creation"); - } - - public void setUiAllowNonAdminProjectCreation(final boolean uiAllowNonAdminProjectCreation) { - try { - setBooleanValue(uiAllowNonAdminProjectCreation, "UI.allow-non-admin-project-creation"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'UI.allow-non-admin-project-creation': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "Your login attempt failed because the username and password combination you provided was invalid. After %d failed login attempts, your user account will be locked. If you believe your account is currently locked, you can:<ul><li>Unlock it by resetting your password</li><li>Wait one hour for it to unlock automatically</li></ul>", property = "UI.login_failure_message") - public String getUiLogin_failure_message() { - return getValue("UI.login_failure_message"); - } - - public void setUiLoginFailureMessage(final String uiLoginFailureMessage) { - try { - set(uiLoginFailureMessage, "UI.login_failure_message"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'UI.login_failure_message': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "false", property = "UI.allow-blocked-subject-assessor-view") - public boolean getUiAllowBlockedSubjectAssessorView() { - return getBooleanValue("UI.allow-blocked-subject-assessor-view"); - } - - public void setUiAllowBlockedSubjectAssessorView(final boolean uiAllowBlockedSubjectAssessorView) { - try { - setBooleanValue(uiAllowBlockedSubjectAssessorView, "UI.allow-blocked-subject-assessor-view"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'UI.allow-blocked-subject-assessor-view': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = FeaturesConfig.DEFAULT_FEATURE_SERVICE, property = "security.services.feature.default") - public String getFeatureService() { - return getValue("security.services.feature.default"); - } - - public void setFeatureService(final String featureService) { - try { - set(featureService, "security.services.feature.default"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'security.services.feature.default': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = FeaturesConfig.DEFAULT_FEATURE_REPO_SERVICE, property = "security.services.featureRepository.default") - public String getFeatureRepositoryService() { - return getValue("security.services.featureRepository.default"); - } - - public void setFeatureRepositoryService(final String featureRepositoryService) { - try { - set(featureRepositoryService, "security.services.featureRepository.default"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'security.services.featureRepository.default': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = FeaturesConfig.DEFAULT_ROLE_SERVICE, property = "security.services.role.default") - public String getRoleService() { - return getValue("security.services.role.default"); - } - - public void setRoleService(final String roleService) { - try { - set(roleService, "security.services.role.default"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'security.services.role.default': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = FeaturesConfig.DEFAULT_ROLE_REPO_SERVICE, property = "security.services.roleRepository.default") - public String getRoleRepositoryService() { - return getValue("security.services.roleRepository.default"); - } - - public void setRoleRepositoryService(final String roleRepositoryService) { - try { - set(roleRepositoryService, "security.services.roleRepository.default"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'security.services.roleRepository.default': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "XNAT") - public String getEmailPrefix() { - return getValue("emailPrefix"); - } - - public void setEmailPrefix(final String emailPrefix) { - try { - set(emailPrefix, "emailPrefix"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'emailPrefix': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "org.nrg.config.services.impl.PrefsBasedSiteConfigurationService", property = "admin.siteConfig.service") - public String getSiteConfigurationService() { - return getValue("admin.siteConfig.service"); - } - - public void setSiteConfigurationService(final String siteConfigurationService) { - try { - set(siteConfigurationService, "admin.siteConfig.service"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'admin.siteConfig.service': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "86400000") - public int getMaxFailedLoginsLockoutDuration() { - return getIntegerValue("maxFailedLoginsLockoutDuration"); - } - - public void setMaxFailedLoginsLockoutDuration(final int maxFailedLoginsLockoutDuration) { - try { - setIntegerValue(maxFailedLoginsLockoutDuration, "maxFailedLoginsLockoutDuration"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'maxFailedLoginsLockoutDuration': something is very wrong here.", e); - } - } - - private static final Logger _log = LoggerFactory.getLogger(SiteConfigPreferences.class); - - @NrgPreference(defaultValue = "31556926") - public int getInactivityBeforeLockout() { - return getIntegerValue("inactivityBeforeLockout"); - } - - public void setInactivityBeforeLockout(final int inactivityBeforeLockout) { - try { - setIntegerValue(inactivityBeforeLockout, "inactivityBeforeLockout"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'inactivityBeforeLockout': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "0 0 1 * * ?") - public String getInactivityBeforeLockoutSchedule() { - return getValue("inactivityBeforeLockoutSchedule"); - } - - public void setInactivityBeforeLockoutSchedule(final String inactivityBeforeLockoutSchedule) { - try { - set(inactivityBeforeLockoutSchedule, "inactivityBeforeLockoutSchedule"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'inactivityBeforeLockoutSchedule': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "60000") - public long getSessionXmlRebuilderRepeat() { - return getLongValue("sessionXmlRebuilderRepeat"); - } - - public void setSessionXmlRebuilderRepeat(final long sessionXmlRebuilderRepeat) { - try { - setLongValue(sessionXmlRebuilderRepeat, "sessionXmlRebuilderRepeat"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'sessionXmlRebuilderRepeat': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "5") - public int getSessionXmlRebuilderInterval() { - return getIntegerValue("sessionXmlRebuilderInterval"); - } - - public void setSessionXmlRebuilderInterval(final int sessionXmlRebuilderInterval) { - try { - setIntegerValue(sessionXmlRebuilderInterval, "sessionXmlRebuilderInterval"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'sessionXmlRebuilderInterval': something is very wrong here.", e); - } - } - - @NrgPreference(defaultValue = "2 days") - public String getAliasTokenTimeout() { - return getValue("aliasTokenTimeout"); - } - - public void setAliasTokenTimeout(final String aliasTokenTimeout) { - try { - set(aliasTokenTimeout, "aliasTokenTimeout"); - } catch (InvalidPreferenceName e) { - _log.error("Invalid preference name 'aliasTokenTimeout': something is very wrong here.", e); - } - } -} diff --git a/src/main/java/org/nrg/xnat/event/listeners/AutomationEventScriptHandler.java b/src/main/java/org/nrg/xnat/event/listeners/AutomationEventScriptHandler.java index a9267f8b..ea599485 100644 --- a/src/main/java/org/nrg/xnat/event/listeners/AutomationEventScriptHandler.java +++ b/src/main/java/org/nrg/xnat/event/listeners/AutomationEventScriptHandler.java @@ -3,6 +3,7 @@ package org.nrg.xnat.event.listeners; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.lang3.StringUtils; +import org.hibernate.exception.ConstraintViolationException; import org.nrg.automation.entities.Script; import org.nrg.automation.entities.ScriptOutput; import org.nrg.automation.entities.ScriptOutput.Status; @@ -11,13 +12,12 @@ import org.nrg.automation.services.ScriptTriggerService; import org.nrg.automation.services.impl.hibernate.HibernateScriptTriggerService; import org.nrg.framework.constants.Scope; import org.nrg.framework.exceptions.NrgServiceException; -import org.nrg.xdat.XDAT; import org.nrg.xdat.security.helpers.Users; import org.nrg.xdat.security.user.exceptions.UserInitException; import org.nrg.xdat.security.user.exceptions.UserNotFoundException; -import org.nrg.xdat.services.impl.hibernate.HibernateAutomationEventIdsService; -import org.nrg.xdat.services.impl.hibernate.HibernateAutomationFiltersService; -import org.nrg.xdat.services.impl.hibernate.HibernatePersistentEventService; +import org.nrg.xdat.services.AutomationEventIdsService; +import org.nrg.xdat.services.AutomationFiltersService; +import org.nrg.xdat.services.PersistentEventService; import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xft.event.AutomationEventImplementerI; import org.nrg.xft.event.EventUtils; @@ -35,6 +35,8 @@ import org.nrg.xnat.services.messaging.automation.AutomatedScriptRequest; import org.nrg.xnat.utils.WorkflowUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; @@ -61,79 +63,107 @@ import static reactor.bus.selector.Selectors.type; @Service @SuppressWarnings("unused") public class AutomationEventScriptHandler implements Consumer<Event<AutomationEventImplementerI>> { - - private String EMAIL_SUBJECT = "Automation Results"; - - /** The Constant logger. */ + + /** + * The Constant logger. + */ private static final Logger logger = LoggerFactory.getLogger(AutomationEventScriptHandler.class); - - /** The _service. */ - @Inject ScriptRunnerService _service; - - /** The _script trigger service. */ - @Inject ScriptTriggerService _scriptTriggerService; - - /** The _data source. */ - @Inject DataSource _dataSource; - - /** - * Instantiates a new automated script handler. - * - * @param eventBus the event bus - */ - @Inject public AutomationEventScriptHandler( EventBus eventBus ){ - eventBus.on(type(AutomationEventImplementerI.class), this); - } - - /** - * init - update xhbm_script_trigger table for XNAT 1.7 - */ - @PostConstruct - public void initUpdateTables() { - /** Update script trigger table for XNAT 1.7. Drop constraints on any columns other than id and trigger_id */ + + /** + * The _service. + */ + @Autowired + @Lazy + private ScriptRunnerService _service; + + /** + * The _script trigger service. + */ + @Autowired + @Lazy + private ScriptTriggerService _scriptTriggerService; + + /** + * The _data source. + */ + @Inject + private DataSource _dataSource; + + /** + * Automation filters service. + */ + @Inject + private AutomationFiltersService _filtersService; + + /** + * Persistent event service. + */ + @Inject + private PersistentEventService _persistentEventService; + + /** + * Automation event IDs service. + */ + @Inject + private AutomationEventIdsService _idsService; + + /** + * Instantiates a new automated script handler. + * + * @param eventBus the event bus + */ + @Inject + public AutomationEventScriptHandler(EventBus eventBus) { + eventBus.on(type(AutomationEventImplementerI.class), this); + } + + /** + * init - update xhbm_script_trigger table for XNAT 1.7 + */ + @PostConstruct + public void initUpdateTables() { + /** Update script trigger table for XNAT 1.7. Drop constraints on any columns other than id and trigger_id */ if (_scriptTriggerService instanceof HibernateScriptTriggerService) { - + List<String> cleanUpQuery = (new JdbcTemplate(_dataSource)).query( - "SELECT DISTINCT 'ALTER TABLE '||tc.table_name||' DROP CONSTRAINT '||tc.constraint_name||';'" + - " FROM information_schema.table_constraints tc " + - " LEFT JOIN information_schema.constraint_column_usage cu " + - " ON cu.constraint_name = tc.constraint_name " + - " WHERE (tc.table_name='xhbm_script_trigger' AND cu.column_name NOT IN ('id', 'trigger_id')) " - , new RowMapper<String>() { - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - return rs.getString(1); - } - }); + "SELECT DISTINCT 'ALTER TABLE '||tc.table_name||' DROP CONSTRAINT '||tc.constraint_name||';'" + + " FROM information_schema.table_constraints tc " + + " LEFT JOIN information_schema.constraint_column_usage cu " + + " ON cu.constraint_name = tc.constraint_name " + + " WHERE (tc.table_name='xhbm_script_trigger' AND cu.column_name NOT IN ('id', 'trigger_id')) " + , new RowMapper<String>() { + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + return rs.getString(1); + } + }); if (!cleanUpQuery.isEmpty()) { - logger.info("Cleaning up pre XNAT 1.7 constraints on the xhbm_script_trigger and xhbm_event tables"); - for (String query : cleanUpQuery) { - if (query.contains("xhbm_script_trigger")) { - logger.info("Execute clean-up query (" + query + ")"); - new JdbcTemplate(_dataSource).execute(query); - } - } + logger.info("Cleaning up pre XNAT 1.7 constraints on the xhbm_script_trigger and xhbm_event tables"); + for (String query : cleanUpQuery) { + if (query.contains("xhbm_script_trigger")) { + logger.info("Execute clean-up query (" + query + ")"); + new JdbcTemplate(_dataSource).execute(query); + } + } } /** Update table rows for pre-XNAT 1.7 tables to fill in missing column values with defaults */ - ((HibernateScriptTriggerService)_scriptTriggerService).updateOldStyleScriptTriggers(); + ((HibernateScriptTriggerService) _scriptTriggerService).updateOldStyleScriptTriggers(); + } + } + + /* (non-Javadoc) + * @see reactor.fn.Consumer#accept(java.lang.Object) + */ + @Override + public void accept(Event<AutomationEventImplementerI> event) { + try { + handleAsPersistentEventIfMarkedPersistent(event); + updateAutomationTables(event); + } catch (Throwable t) { + logger.error("Unexpected error persisting Persistent/Automation event information", t); + } finally { + handleEvent(event); } - } - - /* (non-Javadoc) - * @see reactor.fn.Consumer#accept(java.lang.Object) - */ - @Override - public void accept(Event<AutomationEventImplementerI> event) { - - try { - handleAsPersistentEventIfMarkedPersistent(event); - updateAutomationTables(event); - } catch (Throwable t) { - logger.error("Unexpected error persisting Persistent/Automation event information",t); - } finally { - handleEvent(event); - } - - } + } /** * Update automation tables. @@ -141,124 +171,121 @@ public class AutomationEventScriptHandler implements Consumer<Event<AutomationEv * @param event the event */ private void updateAutomationTables(Event<AutomationEventImplementerI> event) { - final HibernateAutomationEventIdsService idsService = XDAT.getContextService().getBean(HibernateAutomationEventIdsService.class); - final AutomationEventImplementerI eventData = event.getData(); - if (eventData.getEventId()==null || eventData.getClass()==null) { - return; - } - List<AutomationEventIds> autoIds = idsService.getEventIds(eventData.getExternalId(), eventData.getSrcEventClass(), true); - if (autoIds.size()<1) { - final AutomationEventIds ids = new AutomationEventIds(eventData); - idsService.saveOrUpdate(ids); - } else { - for (final AutomationEventIds ids : autoIds) { - if (!ids.getEventIds().contains(eventData.getEventId())) { - ids.getEventIds().add(eventData.getEventId()); - idsService.saveOrUpdate(ids); - } - } - } - final HibernateAutomationFiltersService filtersService = XDAT.getContextService().getBean(HibernateAutomationFiltersService.class); - final Class<? extends AutomationEventImplementerI> clazz = eventData.getClass(); - for (final Method method : Arrays.asList(clazz.getMethods())) { - if (method.isAnnotationPresent(Filterable.class) && method.getName().substring(0,3).equalsIgnoreCase("get")) { - final char c[] = method.getName().substring(3).toCharArray(); - c[0] = Character.toLowerCase(c[0]); - final String column = new String(c); - AutomationFilters filters = filtersService.getAutomationFilters(eventData.getExternalId(), eventData.getSrcEventClass(), column, true); - if (filters == null) { - filters = new AutomationFilters(eventData, column); - filtersService.saveOrUpdate(filters); - } else { - try { - final String value = method.invoke(eventData).toString(); - final List<String> values = filters.getValues(); - if (!values.contains(value)) { - values.add(value); - filters.setValues(values); - filtersService.saveOrUpdate(filters); - } - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - logger.error("Error invoking method on eventData",e); - } - } - } - } - - } - - /** - * Handle as persistent event if marked persistent. - * - * @param event the event - */ - private void handleAsPersistentEventIfMarkedPersistent(Event<AutomationEventImplementerI> event) { - // Persist the event if this is a PersistentEventImplementerI - if (event.getData() instanceof PersistentEventImplementerI) { - try { - final HibernatePersistentEventService service = XDAT.getContextService().getBean(HibernatePersistentEventService.class); - service.create((PersistentEvent)event.getData()); - } catch (SecurityException | IllegalArgumentException e) { - logger.error("Exception persisting event",e); - } - } - } - - /** - * Handle event. - * - * @param event the event - */ - /* (non-Javadoc) + final AutomationEventImplementerI eventData = event.getData(); + if (eventData.getEventId() == null || eventData.getClass() == null) { + return; + } + final List<AutomationEventIds> autoIds = _idsService.getEventIds(eventData.getExternalId(), eventData.getSrcEventClass(), true); + if (autoIds.size() < 1) { + final AutomationEventIds ids = new AutomationEventIds(eventData); + _idsService.saveOrUpdate(ids); + } else { + for (final AutomationEventIds ids : autoIds) { + if (!ids.getEventIds().contains(eventData.getEventId())) { + ids.getEventIds().add(eventData.getEventId()); + _idsService.saveOrUpdate(ids); + } + } + } + final Class<? extends AutomationEventImplementerI> clazz = eventData.getClass(); + for (final Method method : Arrays.asList(clazz.getMethods())) { + if (method.isAnnotationPresent(Filterable.class) && method.getName().substring(0, 3).equalsIgnoreCase("get")) { + final char c[] = method.getName().substring(3).toCharArray(); + c[0] = Character.toLowerCase(c[0]); + final String column = new String(c); + AutomationFilters filters = _filtersService.getAutomationFilters(eventData.getExternalId(), eventData.getSrcEventClass(), column, true); + if (filters == null) { + filters = new AutomationFilters(eventData, column); + try { + _filtersService.saveOrUpdate(filters); + } catch (ConstraintViolationException e) { + logger.warn("A constraint violation error on {} occurred saving a filters entity: {}\n{}", e.getConstraintName(), filters.toString(), e.getMessage()); + } + } else { + try { + final String value = method.invoke(eventData).toString(); + final List<String> values = filters.getValues(); + if (!values.contains(value)) { + values.add(value); + filters.setValues(values); + _filtersService.saveOrUpdate(filters); + } + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + logger.error("Error invoking method on eventData", e); + } + } + } + } + + } + + /** + * Handle as persistent event if marked persistent. + * + * @param event the event + */ + private void handleAsPersistentEventIfMarkedPersistent(Event<AutomationEventImplementerI> event) { + // Persist the event if this is a PersistentEventImplementerI + if (event.getData() instanceof PersistentEventImplementerI) { + try { + _persistentEventService.create((PersistentEvent) event.getData()); + } catch (SecurityException | IllegalArgumentException e) { + logger.error("Exception persisting event", e); + } + } + } + + /** + * Handle event. + * + * @param event the event + */ + /* (non-Javadoc) * @see org.nrg.xnat.event.listeners.WorkflowStatusEventHandlerAbst#handleEvent(org.nrg.xft.event.WorkflowStatusEvent) */ public void handleEvent(Event<AutomationEventImplementerI> event) { - final AutomationEventImplementerI automationEvent = event.getData(); - if (automationEvent == null) { - logger.debug("Automation script will not be launched because applicationEvent object is null"); - return; - } - final UserI user; - try { - user = Users.getUser(automationEvent.getUserId()); - } catch (UserNotFoundException | UserInitException e) { - // User is required to launch script - logger.debug("Automation not launching because user object is null"); - return; - } + final AutomationEventImplementerI automationEvent = event.getData(); + if (automationEvent == null) { + logger.debug("Automation script will not be launched because applicationEvent object is null"); + return; + } + final UserI user; + try { + user = Users.getUser(automationEvent.getUserId()); + } catch (UserNotFoundException | UserInitException e) { + // User is required to launch script + logger.debug("Automation not launching because user object is null"); + return; + } final String eventClass = automationEvent.getSrcEventClass(); if (eventClass == null) { - logger.debug("Automation not launching because eventClass is null"); - return; + logger.debug("Automation not launching because eventClass is null"); + return; } final String eventID = automationEvent.getEventId(); if (eventID == null) { - logger.debug("Automation not launching because eventID is null"); - return; + logger.debug("Automation not launching because eventID is null"); + return; } - final Map<String,String> filterMap = Maps.newHashMap(); - final Class<? extends AutomationEventImplementerI> clazz = automationEvent.getClass(); - for (final Method method : Arrays.asList(clazz.getMethods())) { - if (method.isAnnotationPresent(Filterable.class) && method.getName().substring(0,3).equalsIgnoreCase("get")) { - final char c[] = method.getName().substring(3).toCharArray(); - c[0] = Character.toLowerCase(c[0]); - final String column = new String(c); - String value; - try { - final Object rtValue = method.invoke(automationEvent); - if (rtValue != null) { - value = rtValue.toString(); - filterMap.put(column, value); - } - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - logger.error("ERROR calling method on filterable field in event object", e); - // Let's let this pass for now. - } - } - } - if (eventID == null) { - logger.debug("Automation not launching because eventID is null"); - return; + final Map<String, String> filterMap = Maps.newHashMap(); + final Class<? extends AutomationEventImplementerI> clazz = automationEvent.getClass(); + for (final Method method : Arrays.asList(clazz.getMethods())) { + if (method.isAnnotationPresent(Filterable.class) && method.getName().substring(0, 3).equalsIgnoreCase("get")) { + final char c[] = method.getName().substring(3).toCharArray(); + c[0] = Character.toLowerCase(c[0]); + final String column = new String(c); + String value; + try { + final Object rtValue = method.invoke(automationEvent); + if (rtValue != null) { + value = rtValue.toString(); + filterMap.put(column, value); + } + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + logger.error("ERROR calling method on filterable field in event object", e); + // Let's let this pass for now. + } + } } final String eventName = eventID.replaceAll("\\*OPEN\\*", "(").replaceAll("\\*CLOSE\\*", ")"); //check to see if this has been handled before @@ -266,88 +293,90 @@ public class AutomationEventScriptHandler implements Consumer<Event<AutomationEv for (final Script script : getScripts(automationEvent.getExternalId(), eventClass, eventID, filterMap)) { try { final String action = "Executed script " + script.getScriptId(); - Method justMethod = null; - try { - justMethod = automationEvent.getClass().getMethod("getJustification"); - } catch (NoSuchMethodException | NullPointerException | SecurityException e) { - // Do nothing for now - } - final Object justObject = (justMethod!=null) ? justMethod.invoke(automationEvent) : null; - final String justification = (justObject!=null) ? justObject.toString() : ""; + Method justMethod = null; + try { + justMethod = automationEvent.getClass().getMethod("getJustification"); + } catch (NoSuchMethodException | NullPointerException | SecurityException e) { + // Do nothing for now + } + final Object justObject = (justMethod != null) ? justMethod.invoke(automationEvent) : null; + final String justification = (justObject != null) ? justObject.toString() : ""; final String comment = "Executed script " + script.getScriptId() + " triggered by event " + eventID; final PersistentWorkflowI scriptWrk = PersistentWorkflowUtils.buildOpenWorkflow(user, automationEvent.getEntityType(), automationEvent.getEntityId(), automationEvent.getExternalId(), - EventUtils.newEventInstance(EventUtils.CATEGORY.DATA, EventUtils.TYPE.PROCESS, action, - StringUtils.isNotBlank(justification) ? justification : "Automated execution: " + comment, comment)); + EventUtils.newEventInstance(EventUtils.CATEGORY.DATA, EventUtils.TYPE.PROCESS, action, + StringUtils.isNotBlank(justification) ? justification : "Automated execution: " + comment, comment)); assert scriptWrk != null; scriptWrk.setStatus(PersistentWorkflowUtils.QUEUED); WorkflowUtils.save(scriptWrk, scriptWrk.buildEvent()); - + final AutomatedScriptRequest request = new AutomatedScriptRequest(automationEvent.getSrcStringifiedId(), automationEvent.getSrcEventClass(), user, script.getScriptId(), eventName, - scriptWrk.getWorkflowId().toString(), automationEvent.getEntityType(), automationEvent.getSrcStringifiedId(), automationEvent.getExternalId(), automationEvent.getParameterMap()); - + scriptWrk.getWorkflowId().toString(), automationEvent.getEntityType(), automationEvent.getSrcStringifiedId(), automationEvent.getExternalId(), automationEvent.getParameterMap()); + // We're running this here now, so we can return script output //XDAT.sendJmsRequest(request); final ScriptOutput scriptOut = executeScriptRequest(request); if (automationCompletionEvent != null && scriptOut != null) { - automationCompletionEvent.getScriptOutputs().add(scriptOut); + automationCompletionEvent.getScriptOutputs().add(scriptOut); } } catch (Exception e1) { logger.error("Script launch exception", e1); } } - if (automationCompletionEvent!= null && automationCompletionEvent.getScriptOutputs().size()>0) { - XftEventService eventService = XftEventService.getService(); - if (eventService != null) { - automationCompletionEvent.setEventCompletionTime(System.currentTimeMillis()); - eventService.triggerEvent(automationCompletionEvent); - List<String> notifyList = automationCompletionEvent.getNotificationList(); - if (notifyList != null && !notifyList.isEmpty()) { - AdminUtils.sendUserHTMLEmail(EMAIL_SUBJECT, scriptOutputToHtmlString(automationCompletionEvent.getScriptOutputs()), false, notifyList.toArray(new String[0])); - } - } + if (automationCompletionEvent != null && automationCompletionEvent.getScriptOutputs().size() > 0) { + XftEventService eventService = XftEventService.getService(); + if (eventService != null) { + automationCompletionEvent.setEventCompletionTime(System.currentTimeMillis()); + eventService.triggerEvent(automationCompletionEvent); + List<String> notifyList = automationCompletionEvent.getNotificationList(); + if (notifyList != null && !notifyList.isEmpty()) { + final String EMAIL_SUBJECT = "Automation Results"; + AdminUtils.sendUserHTMLEmail(EMAIL_SUBJECT, scriptOutputToHtmlString(automationCompletionEvent.getScriptOutputs()), false, notifyList.toArray(new String[0])); + } + } + } + } + + private String scriptOutputToHtmlString(List<ScriptOutput> scriptOutputs) { + if (scriptOutputs == null) { + return ""; + } + StringBuilder sb = new StringBuilder(); + for (ScriptOutput scriptOut : scriptOutputs) { + sb.append("<br><b>SCRIPT EXECUTION RESULTS</b><br>"); + sb.append("<br><b>FINAL STATUS: ").append(scriptOut.getStatus()).append("</b><br>"); + if (scriptOut.getStatus().equals(Status.ERROR) && scriptOut.getResults() != null && scriptOut.getResults().toString().length() > 0) { + sb.append("<br><b>SCRIPT RESULTS</b><br>"); + sb.append(scriptOut.getResults().toString().replace("\n", "<br>")); + } + if (scriptOut.getOutput() != null && scriptOut.getOutput().length() > 0) { + sb.append("<br><b>SCRIPT STDOUT</b><br>"); + sb.append(scriptOut.getOutput().replace("\n", "<br>")); + } + if (scriptOut.getErrorOutput() != null && scriptOut.getErrorOutput().length() > 0) { + sb.append("<br><b>SCRIPT STDERR/EXCEPTION</b><br>"); + sb.append(scriptOut.getErrorOutput().replace("\n", "<br>")); + } } + return sb.toString(); } - private String scriptOutputToHtmlString(List<ScriptOutput> scriptOutputs) { - if (scriptOutputs == null) { - return ""; - } - StringBuilder sb = new StringBuilder(); - for (ScriptOutput scriptOut : scriptOutputs) { - sb.append("<br><b>SCRIPT EXECUTION RESULTS</b><br>"); - sb.append("<br><b>FINAL STATUS: " + scriptOut.getStatus() + "</b><br>"); - if (scriptOut.getStatus().equals(Status.ERROR) && scriptOut.getResults()!=null && scriptOut.getResults().toString().length()>0) { - sb.append("<br><b>SCRIPT RESULTS</b><br>"); - sb.append(scriptOut.getResults().toString().replace("\n", "<br>")); - } - if (scriptOut.getOutput()!=null && scriptOut.getOutput().length()>0) { - sb.append("<br><b>SCRIPT STDOUT</b><br>"); - sb.append(scriptOut.getOutput().replace("\n", "<br>")); - } - if (scriptOut.getErrorOutput()!=null && scriptOut.getErrorOutput().length()>0) { - sb.append("<br><b>SCRIPT STDERR/EXCEPTION</b><br>"); - sb.append(scriptOut.getErrorOutput().replace("\n", "<br>")); - } - } - return sb.toString(); - } - - /** + /** * Gets the scripts. * - * @param projectId the project id + * @param projectId the project id * @param eventClass the event class - * @param event the event - * @param filterMap the filter map + * @param event the event + * @param filterMap the filter map + * * @return the scripts */ - private List<Script> getScripts(final String projectId, String eventClass, String event, Map<String,String> filterMap) { + private List<Script> getScripts(final String projectId, String eventClass, String event, Map<String, String> filterMap) { final List<Script> scripts = Lists.newArrayList(); //project level scripts if (StringUtils.isNotBlank(projectId)) { - + final Script script = _service.getScript(Scope.Project, projectId, eventClass, event, filterMap); if (script != null) { scripts.add(script); @@ -362,17 +391,23 @@ public class AutomationEventScriptHandler implements Consumer<Event<AutomationEv return scripts; } - + /** * Execute script request. * * @param request the request + * * @return the script output + * * @throws Exception the exception */ private ScriptOutput executeScriptRequest(AutomatedScriptRequest request) throws Exception { - final PersistentWorkflowI workflow = WorkflowUtils.getUniqueWorkflow(request.getUser(), request.getScriptWorkflowId()); + if (workflow == null) { + logger.warn("Didn't find the workflow indicated by an automated script request: " + request.getScriptWorkflowId() + " (requested by " + request.getUser().getUsername() + ")"); + return null; + } + workflow.setStatus(PersistentWorkflowUtils.IN_PROGRESS); WorkflowUtils.save(workflow, workflow.buildEvent()); @@ -388,8 +423,8 @@ public class AutomationEventScriptHandler implements Consumer<Event<AutomationEv parameters.put("dataId", request.getDataId()); parameters.put("externalId", request.getExternalId()); parameters.put("workflow", workflow); - if (request.getArgumentMap()!=null && !request.getArgumentMap().isEmpty()) { - parameters.putAll(request.getArgumentMap()); + if (request.getArgumentMap() != null && !request.getArgumentMap().isEmpty()) { + parameters.putAll(request.getArgumentMap()); } ScriptOutput scriptOut = null; @@ -400,12 +435,12 @@ public class AutomationEventScriptHandler implements Consumer<Event<AutomationEv } } catch (NrgServiceException e) { final String message = String.format("Failed running the script %s by user %s for event %s on data type %s instance %s from project %s", - request.getScriptId(), - request.getUser().getLogin(), - request.getEvent(), - request.getDataType(), - request.getDataId(), - request.getExternalId()); + request.getScriptId(), + request.getUser().getLogin(), + request.getEvent(), + request.getDataType(), + request.getDataId(), + request.getExternalId()); AdminUtils.sendAdminEmail("Script execution failure", message); logger.error(message, e); if (PersistentWorkflowUtils.IN_PROGRESS.equals(workflow.getStatus())) { @@ -413,6 +448,5 @@ public class AutomationEventScriptHandler implements Consumer<Event<AutomationEv } } return scriptOut; - } - + } } diff --git a/src/main/java/org/nrg/xnat/configuration/DatabaseConfig.java b/src/main/java/org/nrg/xnat/initialization/DatabaseConfig.java similarity index 60% rename from src/main/java/org/nrg/xnat/configuration/DatabaseConfig.java rename to src/main/java/org/nrg/xnat/initialization/DatabaseConfig.java index b8da1456..60a1063b 100644 --- a/src/main/java/org/nrg/xnat/configuration/DatabaseConfig.java +++ b/src/main/java/org/nrg/xnat/initialization/DatabaseConfig.java @@ -1,40 +1,26 @@ -package org.nrg.xnat.configuration; +package org.nrg.xnat.initialization; -import org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory; -import org.hibernate.cache.spi.RegionFactory; -import org.hibernate.cfg.ImprovedNamingStrategy; import org.nrg.framework.exceptions.NrgServiceError; import org.nrg.framework.exceptions.NrgServiceException; -import org.nrg.framework.orm.hibernate.AggregatedAnnotationSessionFactoryBean; -import org.nrg.framework.orm.hibernate.HibernateEntityPackageList; -import org.nrg.framework.orm.hibernate.PrefixedTableNamingStrategy; import org.nrg.framework.utilities.Beans; import org.postgresql.Driver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SimpleDriverDataSource; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.inject.Inject; import javax.sql.DataSource; -import java.io.IOException; import java.lang.reflect.InvocationTargetException; -import java.util.List; import java.util.Properties; /** * Sets up the database configuration for XNAT. */ @Configuration -@EnableTransactionManagement(proxyTargetClass = true) public class DatabaseConfig { public static final String DEFAULT_DATASOURCE_URL = "jdbc:postgresql://localhost/xnat"; @@ -71,51 +57,6 @@ public class DatabaseConfig { return new JdbcTemplate(dataSource()); } - @Bean - public ImprovedNamingStrategy namingStrategy() { - return new PrefixedTableNamingStrategy("xhbm"); - } - - @Bean - public PropertiesFactoryBean hibernateProperties() { - final PropertiesFactoryBean bean = new PropertiesFactoryBean(); - final Properties properties = Beans.getNamespacedProperties(_environment, "hibernate", false); - if (properties.size() == 0) { - properties.putAll(DEFAULT_HIBERNATE_PROPERTIES); - } - bean.setProperties(properties); - return bean; - } - - @Bean - public RegionFactory regionFactory() throws NrgServiceException { - try { - return new SingletonEhCacheRegionFactory(hibernateProperties().getObject()); - } catch (IOException e) { - throw new NrgServiceException(NrgServiceError.Unknown, "An error occurred trying to retrieve the Hibernate properties", e); - } - } - - @Bean - public LocalSessionFactoryBean sessionFactory(final List<HibernateEntityPackageList> packageLists) throws NrgServiceException { - try { - final AggregatedAnnotationSessionFactoryBean bean = new AggregatedAnnotationSessionFactoryBean(); - bean.setEntityPackageLists(packageLists); - bean.setDataSource(dataSource()); - bean.setCacheRegionFactory(regionFactory()); - bean.setHibernateProperties(hibernateProperties().getObject()); - bean.setNamingStrategy(namingStrategy()); - return bean; - } catch (IOException e) { - throw new NrgServiceException(NrgServiceError.Unknown, "An error occurred trying to retrieve the Hibernate properties", e); - } - } - - @Bean - public PlatformTransactionManager transactionManager(final List<HibernateEntityPackageList> packageLists) throws NrgServiceException { - return new HibernateTransactionManager(sessionFactory(packageLists).getObject()); - } - private static Properties setDefaultDatasourceProperties(final Properties properties) { // Configure some defaults if they're not already set. if (!properties.containsKey("class")) { @@ -153,14 +94,6 @@ public class DatabaseConfig { private static final Logger _log = LoggerFactory.getLogger(DatabaseConfig.class); - private static final Properties DEFAULT_HIBERNATE_PROPERTIES = new Properties() {{ - setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect"); - setProperty("hibernate.hbm2ddl.auto", "update"); - setProperty("hibernate.show_sql", "false"); - setProperty("hibernate.cache.use_second_level_cache", "true"); - setProperty("hibernate.cache.use_query_cache", "true"); - }}; - @Inject private Environment _environment; } diff --git a/src/main/java/org/nrg/xnat/initialization/InitializerSiteConfiguration.java b/src/main/java/org/nrg/xnat/initialization/InitializerSiteConfiguration.java deleted file mode 100644 index f5714bba..00000000 --- a/src/main/java/org/nrg/xnat/initialization/InitializerSiteConfiguration.java +++ /dev/null @@ -1,154 +0,0 @@ -/** - * InitializerSiteConfig - * (C) 2016 Washington University School of Medicine - * All Rights Reserved - * - * Released under the Simplified BSD License - */ -package org.nrg.xnat.initialization; - -import org.apache.commons.lang3.StringUtils; -import org.nrg.config.exceptions.SiteConfigurationException; -import org.nrg.config.services.impl.PropertiesBasedSiteConfigurationService; -import org.nrg.framework.exceptions.NrgServiceError; -import org.nrg.framework.exceptions.NrgServiceRuntimeException; -import org.nrg.framework.services.SerializerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.ResultSetExtractor; -import org.springframework.stereotype.Service; - -import javax.inject.Inject; -import java.io.IOException; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Map; -import java.util.Properties; - -@Service -public class InitializerSiteConfiguration extends PropertiesBasedSiteConfigurationService { - public String getSiteConfigurationService() throws SiteConfigurationException { - return getSiteConfigurationProperty("admin.siteConfig.service"); - } - - public String getPasswordComplexity() throws SiteConfigurationException { - return getSiteConfigurationProperty("passwordComplexity"); - } - - public String getPasswordComplexityMessage() throws SiteConfigurationException { - return getSiteConfigurationProperty("passwordComplexityMessage"); - } - - public int getPasswordHistoryDuration() throws SiteConfigurationException { - return getIntegerSiteConfigurationProperty("passwordHistoryDuration"); - } - - public String getReceivedFileUser() throws SiteConfigurationException { - return getSiteConfigurationProperty("receivedFileUser"); - } - - public int getInactivityBeforeLockout() throws SiteConfigurationException { - return getIntegerSiteConfigurationProperty("inactivityBeforeLockout"); - } - - public long getInactivityBeforeLockoutSchedule() throws SiteConfigurationException { - return getLongSiteConfigurationProperty("inactivityBeforeLockoutSchedule"); - } - - public long getMaxFailedLoginsLockoutDuration() throws SiteConfigurationException { - return getLongSiteConfigurationProperty("maxFailedLoginsLockoutDuration"); - } - - public double getSessionXmlRebuilderInterval() throws SiteConfigurationException { - return getDoubleSiteConfigurationProperty("sessionXmlRebuilderInterval"); - } - - public long getSessionXmlRebuilderRepeat() throws SiteConfigurationException { - return getLongSiteConfigurationProperty("sessionXmlRebuilderRepeat"); - } - - public String getAliasTokenTimeout() throws SiteConfigurationException { - return getSiteConfigurationProperty("aliasTokenTimeout"); - } - - public Map<String, String> getSmtpServer() throws SiteConfigurationException, IOException { - final String definition = getSiteConfigurationProperty("smtpServer"); - if (StringUtils.isBlank(definition)) { - return null; - } - return _serializerService.deserializeJsonToMapOfStrings(definition); - } - - public String getAdminEmail() throws SiteConfigurationException { - return getSiteConfigurationProperty("adminEmail"); - } - - public String getEmailPrefix() throws SiteConfigurationException { - return getSiteConfigurationProperty("emailPrefix"); - } - - public String getFeatureService() throws SiteConfigurationException { - return getSiteConfigurationProperty("featureService"); - } - - public String getFeatureRepositoryService() throws SiteConfigurationException { - return getSiteConfigurationProperty("featureRepositoryService"); - } - - public String getRoleService() throws SiteConfigurationException { - return getSiteConfigurationProperty("roleService"); - } - - public String getRoleRepositoryService() throws SiteConfigurationException { - return getSiteConfigurationProperty("roleRepositoryService"); - } - - @Override - protected void setPreferenceValue(final String username, final String property, final String value) { - throw new NrgServiceRuntimeException(NrgServiceError.PermissionsViolation, "This site configuration service is for initialization and is read only."); - } - - @Override - protected void getPreferenceValuesFromPersistentStore(final Properties properties) { - final Integer siteConfigToolKey = getSiteConfigToolKey(); - if (siteConfigToolKey == null) { - _log.info("Didn't find a tool for the {} ID, checking for import values from configuration service.", SITE_CONFIG_TOOL_ID); - final Properties existing = checkForConfigServiceSiteConfiguration(); - if (existing != null) { - _log.info("Found {} properties in the configuration service, importing those.", existing.size()); - properties.putAll(existing); - } - } else { - _log.info("Working with the existing {} tool, checking for new import values.", SITE_CONFIG_TOOL_ID); - properties.putAll(getPersistedSiteConfiguration(siteConfigToolKey)); - } - } - - @SuppressWarnings({"SqlDialectInspection", "SqlNoDataSourceInspection"}) - private Properties getPersistedSiteConfiguration(final int toolId) { - return getJdbcTemplate().query("select name, value from xhbm_preference where tool = ?", PROPERTIES_RESULT_SET_EXTRACTOR, toolId); - } - - @SuppressWarnings({"SqlDialectInspection", "SqlNoDataSourceInspection"}) - private Integer getSiteConfigToolKey() { - return getJdbcTemplate().queryForObject("select id from xhbm_tool where tool_id = ?", Integer.class, SITE_CONFIG_TOOL_ID); - } - - private static final ResultSetExtractor<Properties> PROPERTIES_RESULT_SET_EXTRACTOR = new ResultSetExtractor<Properties>() { - @Override - public Properties extractData(final ResultSet results) throws SQLException, DataAccessException { - final Properties properties = new Properties(); - while (results.next()) { - properties.put(results.getString("name"), results.getString("value")); - } - return properties; - } - }; - - private static final Logger _log = LoggerFactory.getLogger(InitializerSiteConfiguration.class); - private static final String SITE_CONFIG_TOOL_ID = "siteConfig"; - - @Inject - private SerializerService _serializerService; -} diff --git a/src/main/java/org/nrg/xnat/initialization/InitializingTask.java b/src/main/java/org/nrg/xnat/initialization/InitializingTask.java new file mode 100644 index 00000000..9fc1ed68 --- /dev/null +++ b/src/main/java/org/nrg/xnat/initialization/InitializingTask.java @@ -0,0 +1,15 @@ +package org.nrg.xnat.initialization; + +import java.util.Date; + +public interface InitializingTask extends Runnable { + String getTaskName(); + + boolean isCompleted(); + + Date completedAt(); + + void complete(); + + void reset(); +} diff --git a/src/main/java/org/nrg/xnat/initialization/InitializingTasksExecutor.java b/src/main/java/org/nrg/xnat/initialization/InitializingTasksExecutor.java new file mode 100644 index 00000000..64fbd2d1 --- /dev/null +++ b/src/main/java/org/nrg/xnat/initialization/InitializingTasksExecutor.java @@ -0,0 +1,38 @@ +package org.nrg.xnat.initialization; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class InitializingTasksExecutor { + @EventListener + public void executeOnContextRefresh(final ContextRefreshedEvent event) { + if (_log.isDebugEnabled()) { + _log.debug("Handling context refreshed event at " + event.getTimestamp()); + } + for (final InitializingTask task : _tasks) { + if (!task.isCompleted()) { + if (_log.isInfoEnabled()) { + _log.info("Executing type: " + task.getTaskName()); + } + task.run(); + if (_log.isInfoEnabled()) { + _log.info("Task \"" + task.getTaskName() + "\" " + (task.isCompleted() ? "completed at " + task.completedAt() : "did not complete.")); + } + } + } + } + + private static final Logger _log = LoggerFactory.getLogger(InitializingTasksExecutor.class); + + @Autowired + @Lazy + private List<InitializingTask> _tasks; +} diff --git a/src/main/java/org/nrg/xnat/configuration/PropertiesConfig.java b/src/main/java/org/nrg/xnat/initialization/PropertiesConfig.java similarity index 99% rename from src/main/java/org/nrg/xnat/configuration/PropertiesConfig.java rename to src/main/java/org/nrg/xnat/initialization/PropertiesConfig.java index 124bd166..af431c4d 100644 --- a/src/main/java/org/nrg/xnat/configuration/PropertiesConfig.java +++ b/src/main/java/org/nrg/xnat/initialization/PropertiesConfig.java @@ -1,4 +1,4 @@ -package org.nrg.xnat.configuration; +package org.nrg.xnat.initialization; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.lang3.StringUtils; diff --git a/src/main/java/org/nrg/xnat/initialization/RootConfig.java b/src/main/java/org/nrg/xnat/initialization/RootConfig.java index 963fdb5f..cd76f5bf 100644 --- a/src/main/java/org/nrg/xnat/initialization/RootConfig.java +++ b/src/main/java/org/nrg/xnat/initialization/RootConfig.java @@ -1,99 +1,83 @@ package org.nrg.xnat.initialization; -import org.nrg.config.exceptions.SiteConfigurationException; -import org.nrg.framework.configuration.FrameworkConfig; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.PrettyPrinter; +import com.fasterxml.jackson.core.util.DefaultIndenter; +import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import org.nrg.framework.datacache.SerializerRegistry; -import org.nrg.framework.orm.hibernate.HibernateEntityPackageList; +import org.nrg.framework.exceptions.NrgServiceException; import org.nrg.framework.services.ContextService; -import org.nrg.xdat.security.HistoricPasswordValidator; -import org.nrg.xdat.security.PasswordValidatorChain; -import org.nrg.xdat.security.RegExpValidator; -import org.nrg.xnat.event.conf.EventPackages; -import org.nrg.xnat.restlet.XnatRestletExtensions; -import org.nrg.xnat.restlet.actions.importer.ImporterHandlerPackages; -import org.nrg.xnat.utils.XnatUserProvider; -import org.springframework.context.annotation.*; - -import javax.inject.Inject; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; - +import org.nrg.framework.services.SerializerService; +import org.nrg.xdat.preferences.InitializerSiteConfiguration; +import org.nrg.xnat.helpers.prearchive.PrearcConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.ImportResource; + +/** + * Configuration for the XNAT root application context. This contains all of the basic infrastructure for initializing + * and bootstrapping the site, including data source configuration, transaction and session management, and site + * configuration preferences. + * + * <b>NOTE:</b> If you are adding code to this class, please be sure you know what you're doing! Most configuration code + * for standard XNAT components should be added in {@link org.nrg.xnat.configuration.ApplicationConfig} + */ @Configuration -@ComponentScan({"org.nrg.xdat.daos", "org.nrg.xnat.daos", "org.nrg.xnat.services.impl.hibernate", "org.nrg.xdat.services", "org.nrg.xft.daos", "org.nrg.xft.services", "org.nrg.xnat.helpers.merge", "org.nrg.xnat.configuration", "org.nrg.xnat.services", "org.nrg.dicomtools.filters"}) -@Import(FrameworkConfig.class) -@ImportResource({"WEB-INF/conf/xnat-security.xml", "WEB-INF/conf/mq-context.xml"}) +@Import({PropertiesConfig.class, DatabaseConfig.class}) +@ImportResource("WEB-INF/conf/xnat-security.xml") public class RootConfig { - - public static final List<String> DEFAULT_ENTITY_PACKAGES = Arrays.asList("org.nrg.xft.entities", "org.nrg.xft.event.entities", "org.nrg.xdat.entities", "org.nrg.xnat.entities", "org.nrg.xnat.event.entities", "org.nrg.config.entities"); - @Bean public InitializerSiteConfiguration initializerSiteConfiguration() { return new InitializerSiteConfiguration(); } @Bean - public RegExpValidator regexValidator() throws SiteConfigurationException { - final String complexityExpression = _preferences.getPasswordComplexity(); - final String complexityMessage = _preferences.getPasswordComplexityMessage(); - return new RegExpValidator(complexityExpression, complexityMessage); - } - - @Bean - public HistoricPasswordValidator historicPasswordValidator() throws SiteConfigurationException { - final int durationInDays = _preferences.getPasswordHistoryDuration(); - return new HistoricPasswordValidator(durationInDays); - } - - @Bean - public PasswordValidatorChain validator(final RegExpValidator regExpValidator, final HistoricPasswordValidator historicPasswordValidator) { - return new PasswordValidatorChain(Arrays.asList(regExpValidator, historicPasswordValidator)); - } - - // MIGRATION: I'm not even sure this is used, but we need to do away with it in favor of prefs. - @Bean - public List<String> propertiesRepositories() { - return Collections.singletonList("WEB-INF/conf/properties"); - } - - @Bean - public ContextService contextService() { + public ContextService rootContextService() throws NrgServiceException { return ContextService.getInstance(); } @Bean - public HibernateEntityPackageList coreXnatEntityPackages() { - return new HibernateEntityPackageList(DEFAULT_ENTITY_PACKAGES); + public PrearcConfig prearcConfig() { + final PrearcConfig prearcConfig = new PrearcConfig(); + prearcConfig.setReloadPrearcDatabaseOnApplicationStartup(false); + return prearcConfig; } @Bean - public XnatUserProvider receivedFileUserProvider() throws SiteConfigurationException { - final String receivedFileUser = _preferences.getReceivedFileUser(); - return new XnatUserProvider(receivedFileUser); + public PrettyPrinter prettyPrinter() { + final DefaultIndenter indenter = new DefaultIndenter(" ", DefaultIndenter.SYS_LF); + return new DefaultPrettyPrinter() {{ + indentObjectsWith(indenter); + indentArraysWith(indenter); + }}; } @Bean - public XnatRestletExtensions xnatRestletExtensions() { - return new XnatRestletExtensions(new HashSet<>(Arrays.asList(new String[]{"org.nrg.xnat.restlet.extensions"}))); + public ObjectMapper jsonObjectMapper() { + final PrettyPrinter printer = prettyPrinter(); + final ObjectMapper mapper = new ObjectMapper().setDefaultPrettyPrinter(printer); + mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); + return mapper; } @Bean - public ImporterHandlerPackages importerHandlerPackages() { - return new ImporterHandlerPackages(new HashSet<>(Arrays.asList(new String[]{"org.nrg.xnat.restlet.actions", "org.nrg.xnat.archive"}))); + public ObjectMapper yamlObjectMapper() { + final PrettyPrinter printer = prettyPrinter(); + final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()).setDefaultPrettyPrinter(printer); + mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); + return mapper; } @Bean - public EventPackages eventPackages() { - // NOTE: These should be treated as parent packages. All sub-packages should be searched - return new EventPackages(new HashSet<>(Arrays.asList(new String[]{"org.nrg.xnat.event", "org.nrg.xft.event", "org.nrg.xdat.event"}))); + public SerializerService serializerService() { + return new SerializerService(); } @Bean public SerializerRegistry serializerRegistry() { return new SerializerRegistry(); } - - @Inject - private InitializerSiteConfiguration _preferences; } diff --git a/src/main/java/org/nrg/xnat/initialization/XnatWebAppInitializer.java b/src/main/java/org/nrg/xnat/initialization/XnatWebAppInitializer.java index 3c4f7fcd..20466e40 100644 --- a/src/main/java/org/nrg/xnat/initialization/XnatWebAppInitializer.java +++ b/src/main/java/org/nrg/xnat/initialization/XnatWebAppInitializer.java @@ -10,6 +10,7 @@ import org.nrg.framework.processors.XnatPluginBean; import org.nrg.framework.utilities.BasicXnatResourceLocator; import org.nrg.xdat.servlet.XDATAjaxServlet; import org.nrg.xdat.servlet.XDATServlet; +import org.nrg.xnat.configuration.ApplicationConfig; import org.nrg.xnat.restlet.servlet.XNATRestletServlet; import org.nrg.xnat.restlet.util.UpdateExpirationCookie; import org.nrg.xnat.security.XnatSessionEventPublisher; @@ -17,6 +18,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PropertiesLoaderUtils; +import org.springframework.stereotype.Service; import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; @@ -62,20 +64,20 @@ public class XnatWebAppInitializer extends AbstractAnnotationConfigDispatcherSer @Override protected String[] getServletMappings() { - return new String[] {"/admin/*", "/xapi/*"}; + return new String[]{"/admin/*", "/xapi/*"}; } @Override protected Class<?>[] getRootConfigClasses() { - final List<Class<?>> configClasses = new ArrayList<>(); - configClasses.add(RootConfig.class); - configClasses.addAll(getPluginConfigs()); - return configClasses.toArray(new Class[configClasses.size()]); + return new Class<?>[]{RootConfig.class}; } @Override protected Class<?>[] getServletConfigClasses() { - return new Class<?>[0]; + final List<Class<?>> configClasses = new ArrayList<>(); + configClasses.add(ApplicationConfig.class); + configClasses.addAll(getPluginConfigs()); + return configClasses.toArray(new Class[configClasses.size()]); } @Override @@ -115,9 +117,9 @@ public class XnatWebAppInitializer extends AbstractAnnotationConfigDispatcherSer final List<Class<?>> configs = new ArrayList<>(); try { for (final Resource resource : BasicXnatResourceLocator.getResources("classpath*:META-INF/xnat/**/*-plugin.properties")) { - final Properties properties = PropertiesLoaderUtils.loadProperties(resource); - final XnatPluginBean plugin = new XnatPluginBean(properties); - final Class<?> config = plugin.getConfigClass(); + final Properties properties = PropertiesLoaderUtils.loadProperties(resource); + final XnatPluginBean plugin = new XnatPluginBean(properties); + final Class<?> config = plugin.getConfigClass(); configs.add(config); } } catch (IOException e) { @@ -130,7 +132,7 @@ public class XnatWebAppInitializer extends AbstractAnnotationConfigDispatcherSer } private void addServlet(final Class<? extends Servlet> clazz, final int loadOnStartup, final String... mappings) { - final String name = StringUtils.uncapitalize(clazz.getSimpleName()); + final String name = StringUtils.uncapitalize(clazz.getSimpleName()); final ServletRegistration.Dynamic registration = _context.addServlet(name, clazz); registration.setLoadOnStartup(loadOnStartup); registration.addMapping(mappings); diff --git a/src/main/java/org/nrg/xnat/initialization/tasks/AbstractInitializingTask.java b/src/main/java/org/nrg/xnat/initialization/tasks/AbstractInitializingTask.java new file mode 100644 index 00000000..20681767 --- /dev/null +++ b/src/main/java/org/nrg/xnat/initialization/tasks/AbstractInitializingTask.java @@ -0,0 +1,35 @@ +package org.nrg.xnat.initialization.tasks; + +import org.nrg.xnat.initialization.InitializingTask; + +import java.util.Date; + +public abstract class AbstractInitializingTask implements InitializingTask { + @Override + public abstract String getTaskName(); + + @Override + public abstract void run(); + + @Override + public boolean isCompleted() { + return _completedAt != null; + } + + @Override + public Date completedAt() { + return _completedAt; + } + + @Override + public void complete() { + _completedAt = new Date(); + } + + @Override + public void reset() { + _completedAt = null; + } + + private Date _completedAt; +} diff --git a/src/main/java/org/nrg/xnat/initialization/tasks/EncryptXnatPasswords.java b/src/main/java/org/nrg/xnat/initialization/tasks/EncryptXnatPasswords.java new file mode 100644 index 00000000..e6968b17 --- /dev/null +++ b/src/main/java/org/nrg/xnat/initialization/tasks/EncryptXnatPasswords.java @@ -0,0 +1,86 @@ +/* + * org.nrg.xnat.initialization.tasks.XnatPasswordEncrypter + * XNAT http://www.xnat.org + * Copyright (c) 2016, Washington University School of Medicine + * All Rights Reserved + * + * Released under the Simplified BSD. + */ +package org.nrg.xnat.initialization.tasks; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.ResultSetExtractor; +import org.springframework.security.authentication.encoding.ShaPasswordEncoder; +import org.springframework.stereotype.Component; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + +@Component +public class EncryptXnatPasswords extends AbstractInitializingTask { + @Override + public String getTaskName() { + return "Encrypt XNAT passwords"; + } + + @Override + public void run() { + try { + final PasswordResultSetExtractor extractor = new PasswordResultSetExtractor(); + final Map<Integer, String> userPasswords = _template.query("SELECT xdat_user_id, primary_password FROM xdat_user WHERE primary_password IS NOT NULL AND length(primary_password) != 64", extractor); + final Map<Integer, String> historyPasswords = _template.query("SELECT history_id, primary_password FROM xdat_user_history WHERE primary_password IS NOT NULL AND length(primary_password) != 64", extractor); + + for (final int userId : userPasswords.keySet()) { + _template.update("UPDATE xdat_user SET primary_password = ? WHERE xdat_user_id = ?", userPasswords.get(userId), userId); + } + + for (int historyId : historyPasswords.keySet()) { + _template.update("UPDATE xdat_user_history SET primary_password = ? WHERE history_id = ?", userPasswords.get(historyId), historyId); + } + + if ((!userPasswords.isEmpty() || !historyPasswords.isEmpty()) && tableExists("xs_item_cache")) { + _template.update("DELETE FROM xs_item_cache"); + } + + complete(); + } catch (Exception e) { + logger.error("", e); + } + } + + private boolean tableExists(final String name) throws SQLException { + try (final Connection connection = _template.getDataSource().getConnection(); + final ResultSet results = connection.getMetaData().getTables("catalog", null, name, new String[]{"table"})) { + if (results.next()) { + return true; + } + } + return false; + } + + private static class PasswordResultSetExtractor implements ResultSetExtractor<Map<Integer, String>> { + @Override + public Map<Integer, String> extractData(final ResultSet results) throws SQLException, DataAccessException { + final Map<Integer, String> passwords = new HashMap<>(); + while (results.next()) { + passwords.put(results.getInt(1), encoder.encodePassword(results.getString(2), null)); + } + return passwords; + } + final ShaPasswordEncoder encoder = new ShaPasswordEncoder(256); + } + + private static Logger logger = LoggerFactory.getLogger(EncryptXnatPasswords.class); + + @Autowired + @Lazy + private JdbcTemplate _template; +} diff --git a/src/main/java/org/nrg/xnat/initialization/tasks/GetSiteWideAnonScript.java b/src/main/java/org/nrg/xnat/initialization/tasks/GetSiteWideAnonScript.java new file mode 100644 index 00000000..eae59e03 --- /dev/null +++ b/src/main/java/org/nrg/xnat/initialization/tasks/GetSiteWideAnonScript.java @@ -0,0 +1,48 @@ +package org.nrg.xnat.initialization.tasks; + +import org.apache.commons.io.FileUtils; +import org.nrg.config.entities.Configuration; +import org.nrg.xdat.preferences.SiteConfigPreferences; +import org.nrg.xnat.helpers.editscript.DicomEdit; +import org.nrg.xnat.helpers.merge.AnonUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +@Component +public class GetSiteWideAnonScript extends AbstractInitializingTask { + @Override + public String getTaskName() { + return "Get site-wide anon script"; + } + + @Override + public void run() { + try { + final String path = DicomEdit.buildScriptPath(DicomEdit.ResourceScope.SITE_WIDE, ""); + final Configuration initConfig = AnonUtils.getService().getScript(path, null); + if (initConfig == null) { + _log.info("Creating Script Table."); + final String siteWideScript = FileUtils.readFileToString(AnonUtils.getDefaultScript()); + final String adminUser = _preferences.getReceivedFileUser(); + if (adminUser != null) { + AnonUtils.getService().setSiteWideScript(adminUser, path, siteWideScript); + } else { + throw new Exception("Site administrator not found."); + } + } + // there is a default site-wide script, so nothing to do here for the else. + complete(); + } catch (Throwable e) { + _log.error("Unable to either find or initialize script database", e); + } + } + + private static final Logger _log = LoggerFactory.getLogger(GetSiteWideAnonScript.class); + + @Autowired + @Lazy + private SiteConfigPreferences _preferences; +} diff --git a/src/main/java/org/nrg/xnat/initialization/tasks/GetSiteWidePETTracerList.java b/src/main/java/org/nrg/xnat/initialization/tasks/GetSiteWidePETTracerList.java new file mode 100644 index 00000000..4942dae0 --- /dev/null +++ b/src/main/java/org/nrg/xnat/initialization/tasks/GetSiteWidePETTracerList.java @@ -0,0 +1,53 @@ +package org.nrg.xnat.initialization.tasks; + +import org.apache.commons.io.FileUtils; +import org.nrg.config.entities.Configuration; +import org.nrg.xdat.security.helpers.Roles; +import org.nrg.xdat.security.helpers.Users; +import org.nrg.xft.security.UserI; +import org.nrg.xnat.services.PETTracerUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class GetSiteWidePETTracerList extends AbstractInitializingTask { + @Override + public String getTaskName() { + return "Get site-wide PET tracer list"; + } + + @Override + public void run() { + try { + final String path = PETTracerUtils.buildScriptPath(PETTracerUtils.ResourceScope.SITE_WIDE, ""); + final Configuration configuration = PETTracerUtils.getService().getTracerList(path, null); + if (configuration == null) { + _log.info("Creating PET Tracer List."); + final String siteWide = FileUtils.readFileToString(PETTracerUtils.getDefaultTracerList()); + final UserI adminUser = getAdminUser(); + if (adminUser != null) { + PETTracerUtils.getService().setSiteWideTracerList(adminUser.getUsername(), path, siteWide); + } else { + throw new Exception("Site administrator not found."); + } + } + // there is a default site-wide tracer list, so nothing to do here for the else. + complete(); + } catch (Throwable e){ + _log.error("Unable to either find or initialize the PET tracer list.", e); + } + } + + private UserI getAdminUser() throws Exception { + for (String login : Users.getAllLogins()) { + final UserI user = Users.getUser(login); + if (Roles.isSiteAdmin(user)) { + return user; + } + } + return null; + } + + private static final Logger _log = LoggerFactory.getLogger(GetSiteWidePETTracerList.class); +} diff --git a/src/main/java/org/nrg/xnat/initialization/tasks/UpdateNewSecureDefinitions.java b/src/main/java/org/nrg/xnat/initialization/tasks/UpdateNewSecureDefinitions.java new file mode 100644 index 00000000..357ee715 --- /dev/null +++ b/src/main/java/org/nrg/xnat/initialization/tasks/UpdateNewSecureDefinitions.java @@ -0,0 +1,36 @@ +package org.nrg.xnat.initialization.tasks; + +import org.nrg.xdat.security.ElementSecurity; +import org.nrg.xdat.security.services.FeatureRepositoryServiceI; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +@Component +public class UpdateNewSecureDefinitions extends AbstractInitializingTask { + @Override + public String getTaskName() { + return "Update new secure definitions"; + } + + @Override + public void run() { + try { + if (ElementSecurity.GetElementSecurities() != null) { + _log.debug("Found element securities, running update new secure definitions."); + _featureRepositoryService.updateNewSecureDefinitions(); + } + complete(); + } catch (Exception ignore) { + // No worries... + } + } + + private static final Logger _log = LoggerFactory.getLogger(UpdateNewSecureDefinitions.class); + + @Autowired + @Lazy + private FeatureRepositoryServiceI _featureRepositoryService; +} diff --git a/src/main/java/org/nrg/xnat/initialization/tasks/UpdateUserAuthTable.java b/src/main/java/org/nrg/xnat/initialization/tasks/UpdateUserAuthTable.java new file mode 100644 index 00000000..fd4cde90 --- /dev/null +++ b/src/main/java/org/nrg/xnat/initialization/tasks/UpdateUserAuthTable.java @@ -0,0 +1,62 @@ +package org.nrg.xnat.initialization.tasks; + +import org.nrg.xdat.entities.XdatUserAuth; +import org.nrg.xdat.services.XdatUserAuthService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.stereotype.Component; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +@Component +public class UpdateUserAuthTable extends AbstractInitializingTask { + @Override + public String getTaskName() { + return "Update the user authentication table"; + } + + @Override + public void run() { + /** + * Adds users from /old xdat_user table to new user authentication table if they are not already there. New local database users now get added to both automatically, but this is necessary + * so that those who upgrade from an earlier version will still have their users be able to log in. Password expiry times are also added so that pre-existing users still have their passwords expire. + */ + final List<XdatUserAuth> unmapped = _template.query("SELECT login, enabled FROM xdat_user WHERE login NOT IN (SELECT xdat_username FROM xhbm_xdat_user_auth)", new RowMapper<XdatUserAuth>() { + @Override + public XdatUserAuth mapRow(final ResultSet resultSet, final int i) throws SQLException { + final String login = resultSet.getString("login"); + final boolean enabled = resultSet.getInt("enabled") == 1; + if (_log.isDebugEnabled()) { + _log.debug("Creating new user auth object for user {}, authentication is {}", login, enabled ? "enabled" : "disabled"); + } + return new XdatUserAuth(login, XdatUserAuthService.LOCALDB, enabled, true, true, true, AuthorityUtils.NO_AUTHORITIES, login, 0); + } + }); + for (XdatUserAuth userAuth : unmapped) { + if (_log.isDebugEnabled()) { + _log.debug("Persisting user auth object for user {}", userAuth.getXdatUsername()); + } + _xdatUserAuthService.create(userAuth); + } + _log.debug("Updating the user auth table to set password updated to the current time for local users"); + _template.execute("UPDATE xhbm_xdat_user_auth SET password_updated=current_timestamp WHERE auth_method='" + XdatUserAuthService.LOCALDB + "' AND password_updated IS NULL"); + complete(); + } + + private static final Logger _log = LoggerFactory.getLogger(UpdateUserAuthTable.class); + + @Autowired + @Lazy + private JdbcTemplate _template; + + @Autowired + @Lazy + private XdatUserAuthService _xdatUserAuthService; +} diff --git a/src/main/java/org/nrg/xnat/restlet/services/SettingsRestlet.java b/src/main/java/org/nrg/xnat/restlet/services/SettingsRestlet.java index 5763aa25..b73e8956 100644 --- a/src/main/java/org/nrg/xnat/restlet/services/SettingsRestlet.java +++ b/src/main/java/org/nrg/xnat/restlet/services/SettingsRestlet.java @@ -28,6 +28,7 @@ import org.nrg.xdat.XDAT; import org.nrg.xdat.model.ArcArchivespecificationNotificationTypeI; import org.nrg.xdat.om.ArcArchivespecification; import org.nrg.xdat.om.ArcArchivespecificationNotificationType; +import org.nrg.xdat.preferences.SiteConfigPreferences; import org.nrg.xdat.security.helpers.Roles; import org.nrg.xdat.security.helpers.Users; import org.nrg.xdat.turbine.utils.PopulateItem; @@ -132,8 +133,10 @@ public class SettingsRestlet extends SecureResource { private Map<Object, Object> getArcSpecAsMap() throws IOException, ConfigServiceException { Map<Object, Object> settings = new HashMap<>(); + final SiteConfigPreferences preferences = XDAT.getContextService().getBean(SiteConfigPreferences.class); + settings.putAll(XDAT.getSiteConfiguration()); - settings.put("siteId", getSiteId()); + settings.put("siteId", preferences.getSiteTitle()); final String siteUrl = StringUtils.isBlank(_arcSpec.getSiteUrl()) ? XnatHttpUtils.getServerRoot(getHttpServletRequest()) : _arcSpec.getSiteUrl(); settings.put("siteUrl", siteUrl); settings.put("siteAdminEmail", _arcSpec.getSiteAdminEmail()); @@ -168,18 +171,6 @@ public class SettingsRestlet extends SecureResource { return settings; } - private String getSiteId() { - String siteId = XFT.GetSiteID(); - if (StringUtils.isNotBlank(siteId)) { - return siteId; - } - siteId = _arcSpec.getSiteId(); - if (StringUtils.isNotBlank(siteId)) { - return siteId; - } - return XDAT.getContextService().getBean("siteId", String.class); - } - private String emptyStringIfNull(final String configContents) { return configContents == null ? "" : configContents; } diff --git a/src/main/java/org/nrg/xnat/restlet/servlet/XNATRestletServlet.java b/src/main/java/org/nrg/xnat/restlet/servlet/XNATRestletServlet.java index 40a516aa..743892dc 100644 --- a/src/main/java/org/nrg/xnat/restlet/servlet/XNATRestletServlet.java +++ b/src/main/java/org/nrg/xnat/restlet/servlet/XNATRestletServlet.java @@ -11,32 +11,15 @@ package org.nrg.xnat.restlet.servlet; import com.noelios.restlet.ext.servlet.ServerServlet; -import org.apache.commons.io.FileUtils; -import org.nrg.config.entities.Configuration; import org.nrg.dcm.DicomSCPManager; import org.nrg.xdat.XDAT; -import org.nrg.xdat.entities.XdatUserAuth; -import org.nrg.xdat.security.helpers.Roles; -import org.nrg.xdat.security.helpers.Users; -import org.nrg.xdat.services.XdatUserAuthService; -import org.nrg.xft.security.UserI; -import org.nrg.xnat.helpers.editscript.DicomEdit; -import org.nrg.xnat.helpers.merge.AnonUtils; import org.nrg.xnat.helpers.prearchive.PrearcConfig; import org.nrg.xnat.helpers.prearchive.PrearcDatabase; -import org.nrg.xnat.security.XnatPasswordEncrypter; -import org.nrg.xnat.services.PETTracerUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.security.core.authority.AuthorityUtils; import javax.servlet.ServletConfig; import javax.servlet.ServletException; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; public class XNATRestletServlet extends ServerServlet { private static final long serialVersionUID = -4149339105144231596L; @@ -45,65 +28,11 @@ public class XNATRestletServlet extends ServerServlet { private final Logger logger = LoggerFactory.getLogger(XNATRestletServlet.class); - /** - * Get the username of the site administrator. If there are multiple - * site admins, just get the first one. If none are found, return null. - * @return The name of the admin user. - */ - @SuppressWarnings("unchecked") - private String getAdminUser() throws Exception { - for (String login : Users.getAllLogins()) { - final UserI user = Users.getUser(login); - if (Roles.isSiteAdmin(user)) { - return login; - } - } - return null; - } - @Override public void init() throws ServletException { super.init(); - updateAuthTable(); - XNATRestletServlet.REST_CONFIG=this.getServletConfig(); - try { - String path = DicomEdit.buildScriptPath(DicomEdit.ResourceScope.SITE_WIDE, ""); - Configuration init_config = AnonUtils.getService().getScript(path, null); - if (init_config == null) { - logger.info("Creating Script Table."); - String site_wide = FileUtils.readFileToString(AnonUtils.getDefaultScript()); - String adminUser = this.getAdminUser(); - if (adminUser != null) { - AnonUtils.getService().setSiteWideScript(adminUser, path,site_wide); - } else { - throw new Exception("Site administrator not found."); - } - } - // there is a default site-wide script, so nothing to do here for the else. - } catch (Throwable e){ - logger.error("Unable to either find or initialize script database", e); - } - - // blatant copy of how we initialize the anon script - try { - String path = PETTracerUtils.buildScriptPath(PETTracerUtils.ResourceScope.SITE_WIDE, ""); - Configuration init_config = PETTracerUtils.getService().getTracerList(path, null); - if (init_config == null) { - logger.info("Creating PET Tracer List."); - String site_wide = FileUtils.readFileToString(PETTracerUtils.getDefaultTracerList()); - String adminUser = this.getAdminUser(); - if (adminUser != null) { - PETTracerUtils.getService().setSiteWideTracerList(adminUser, path, site_wide); - } else { - throw new Exception("Site administrator not found."); - } - } - // there is a default site-wide tracer list, so nothing to do here for the else. - } catch (Throwable e){ - logger.error("Unable to either find or initialize the PET tracer list.", e); - } PrearcConfig prearcConfig = XDAT.getContextService().getBean(PrearcConfig.class); try { @@ -112,32 +41,9 @@ public class XNATRestletServlet extends ServerServlet { logger.error("Unable to initialize prearchive database", e); } - XnatPasswordEncrypter.execute(); - XDAT.getContextService().getBean(DicomSCPManager.class).startOrStopDicomSCPAsDictatedByConfiguration(); } - - /** - * Adds users from /old xdat_user table to new user authentication table if they are not already there. New local database users now get added to both automatically, but this is necessary - * so that those who upgrade from an earlier version will still have their users be able to log in. Password expiry times are also added so that pre-existing users still have their passwords expire. - */ - private void updateAuthTable(){ - JdbcTemplate template = new JdbcTemplate(XDAT.getDataSource()); - List<XdatUserAuth> unmapped = template.query("SELECT login, enabled FROM xdat_user WHERE login NOT IN (SELECT xdat_username FROM xhbm_xdat_user_auth)", new RowMapper<XdatUserAuth>() { - @Override - public XdatUserAuth mapRow(final ResultSet resultSet, final int i) throws SQLException { - final String login = resultSet.getString("login"); - final boolean enabled = resultSet.getInt("enabled") == 1; - return new XdatUserAuth(login, XdatUserAuthService.LOCALDB, enabled, true, true, true, AuthorityUtils.NO_AUTHORITIES, login,0); - } - }); - for (XdatUserAuth userAuth : unmapped) { - XDAT.getXdatUserAuthService().create(userAuth); - } - template.execute("UPDATE xhbm_xdat_user_auth SET password_updated=current_timestamp WHERE auth_method='"+XdatUserAuthService.LOCALDB+"' AND password_updated IS NULL"); - } - @Override public void destroy() { XDAT.getContextService().getBean(DicomSCPManager.class).stopDicomSCPs(); diff --git a/src/main/java/org/nrg/xnat/security/FilterSecurityInterceptorBeanPostProcessor.java b/src/main/java/org/nrg/xnat/security/FilterSecurityInterceptorBeanPostProcessor.java index bd43be4b..78b409aa 100644 --- a/src/main/java/org/nrg/xnat/security/FilterSecurityInterceptorBeanPostProcessor.java +++ b/src/main/java/org/nrg/xnat/security/FilterSecurityInterceptorBeanPostProcessor.java @@ -10,12 +10,9 @@ */ package org.nrg.xnat.security; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.nrg.framework.constants.Scope; -import org.nrg.prefs.entities.Preference; -import org.nrg.prefs.services.PreferenceService; +import org.nrg.xdat.preferences.InitializerSiteConfiguration; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.security.access.ConfigAttribute; @@ -52,7 +49,7 @@ public class FilterSecurityInterceptorBeanPostProcessor implements BeanPostProce if (bean instanceof FilterSecurityInterceptor) { FilterSecurityInterceptor interceptor = (FilterSecurityInterceptor) bean; - final ExpressionBasedFilterInvocationSecurityMetadataSource metadataSource = getMetadataSource(isRequiredLogin()); + final ExpressionBasedFilterInvocationSecurityMetadataSource metadataSource = getMetadataSource(_service.getRequireLogin()); if (_log.isDebugEnabled()) { _log.debug("Found a FilterSecurityInterceptor bean with the following metadata configuration:"); displayMetadataSource(interceptor.getSecurityMetadataSource()); @@ -106,20 +103,6 @@ public class FilterSecurityInterceptorBeanPostProcessor implements BeanPostProce } } - private boolean isRequiredLogin() { - final Preference preference = _service.getPreference("system", "require_login", Scope.Site, null); - if (preference == null) { - _log.warn("There is no preference set for the require_login setting."); - return true; - } - final String value = preference.getValue(); - if (StringUtils.isBlank(value)) { - _log.warn("There is no preference value set for the require_login setting."); - return true; - } - return Boolean.parseBoolean(value); - } - private static final Log _log = LogFactory.getLog(FilterSecurityInterceptorBeanPostProcessor.class); private static final String PERMIT_ALL = "permitAll"; private static final String DEFAULT_PATTERN = "/**"; @@ -127,7 +110,7 @@ public class FilterSecurityInterceptorBeanPostProcessor implements BeanPostProce private static final String DEFAULT_EXPRESSION = "hasRole('ROLE_USER')"; @Inject - private PreferenceService _service; + private InitializerSiteConfiguration _service; private final List<String> _openUrls = new ArrayList<>(); private final List<String> _adminUrls = new ArrayList<>(); diff --git a/src/main/java/org/nrg/xnat/security/ResetFailedLogins.java b/src/main/java/org/nrg/xnat/security/ResetFailedLogins.java index d2bf58ae..9ca3f130 100644 --- a/src/main/java/org/nrg/xnat/security/ResetFailedLogins.java +++ b/src/main/java/org/nrg/xnat/security/ResetFailedLogins.java @@ -14,25 +14,27 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; -import javax.inject.Inject; -import javax.sql.DataSource; -import java.util.concurrent.Callable; - public class ResetFailedLogins implements Runnable { - public ResetFailedLogins(final DataSource dataSource) { - _dataSource = dataSource; + public ResetFailedLogins(final JdbcTemplate template, final String interval) { + _template = template; + _interval = interval; } @Override public void run() { - JdbcTemplate template = new JdbcTemplate(_dataSource); - template.execute("UPDATE xhbm_xdat_user_auth SET failed_login_attempts=0"); - _log.info("Reset all failed login attempts."); + if (_template.queryForObject("SELECT count(*) from xhbm_xdat_user_auth", Integer.TYPE) > 0) { + final int updated = _template.update("UPDATE xhbm_xdat_user_auth SET failed_login_attempts = 0 WHERE failed_login_attempts > 0 AND last_login_attempt < NOW() - INTERVAL '" + _interval + "'"); + if (_log.isInfoEnabled()) { + _log.info("Reset {} failed login attempts.", updated); + } + } else { + _log.info("Didn't reset any failed login attempts, there's no data in the relevant table."); + } } private static final Logger _log = LoggerFactory.getLogger(ResetFailedLogins.class); - private final DataSource _dataSource; + private final JdbcTemplate _template; + private final String _interval; } - diff --git a/src/main/java/org/nrg/xnat/security/XnatExpiredPasswordFilter.java b/src/main/java/org/nrg/xnat/security/XnatExpiredPasswordFilter.java index 845c9706..2dbbd476 100644 --- a/src/main/java/org/nrg/xnat/security/XnatExpiredPasswordFilter.java +++ b/src/main/java/org/nrg/xnat/security/XnatExpiredPasswordFilter.java @@ -10,22 +10,21 @@ */ package org.nrg.xnat.security; -import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.nrg.config.exceptions.SiteConfigurationException; -import org.nrg.config.services.SiteConfigurationService; import org.nrg.xdat.XDAT; import org.nrg.xdat.entities.AliasToken; import org.nrg.xdat.entities.UserRole; import org.nrg.xdat.om.ArcArchivespecification; +import org.nrg.xdat.preferences.InitializerSiteConfiguration; import org.nrg.xdat.security.helpers.Roles; import org.nrg.xdat.services.AliasTokenService; import org.nrg.xdat.services.XdatUserAuthService; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.security.UserI; import org.nrg.xnat.turbine.utils.ArcSpecManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.security.crypto.codec.Base64; @@ -44,9 +43,11 @@ import java.net.URI; import java.net.URISyntaxException; import java.sql.ResultSet; import java.sql.SQLException; +import java.text.SimpleDateFormat; +import java.util.Date; import java.util.List; - +@SuppressWarnings({"SqlDialectInspection", "SqlNoDataSourceInspection"}) public class XnatExpiredPasswordFilter extends GenericFilterBean { private String changePasswordPath = ""; private String changePasswordDestination = ""; @@ -132,7 +133,12 @@ public class XnatExpiredPasswordFilter extends GenericFilterBean { logger.error(e); } - if (isPasswordExpirationDisabled()) { + try { + passwordExpirationDisabled = isPasswordExpirationDisabled(); + } catch (SiteConfigurationException e) { + logger.error("An error occurred trying to check for expired passwords, continuing processing.", e); + } + if (passwordExpirationDisabled) { chain.doFilter(request, response); } else { final boolean isExpired = checkForExpiredPassword(username); @@ -177,7 +183,7 @@ public class XnatExpiredPasswordFilter extends GenericFilterBean { } else if (user.isEnabled()) { boolean isExpired = checkForExpiredPassword(user); - if ((!isUserNonExpiring(user) && isExpired) || (getBoolSiteConfigurationProperty("requireSaltedPasswords", true) && user.getSalt() == null)) { + if ((!isUserNonExpiring(user) && isExpired) || (_preferences.getRequireSaltedPasswords() && user.getSalt() == null)) { request.getSession().setAttribute("expired", isExpired); response.sendRedirect(TurbineUtils.GetFullServerPath() + changePasswordPath); } else { @@ -191,20 +197,6 @@ public class XnatExpiredPasswordFilter extends GenericFilterBean { } } - private String getSiteConfigurationProperty(final String property) { - try { - return _siteConfigurationService.getSiteConfigurationProperty(property); - } catch (SiteConfigurationException e) { - _log.warn("An error occurred retrieving the site configuration property " + property, e); - return null; - } - } - - private boolean getBoolSiteConfigurationProperty(final String property, final boolean _default) { - final String value = getSiteConfigurationProperty(property); - return StringUtils.isBlank(value) ? _default : BooleanUtils.toBoolean(value); - } - public void setChangePasswordPath(String path) { this.changePasswordPath = path; } @@ -271,14 +263,14 @@ public class XnatExpiredPasswordFilter extends GenericFilterBean { return false; } if (isPasswordExpirationInterval()) { - List<Boolean> expired = (new JdbcTemplate(_dataSource)).query("SELECT ((now()-password_updated)> (Interval '" + getPasswordExpirationSetting() + " days')) AS expired FROM xhbm_xdat_user_auth WHERE auth_user = ? AND auth_method = 'localdb'", new String[]{username}, new RowMapper<Boolean>() { + List<Boolean> expired = (new JdbcTemplate(_dataSource)).query("SELECT ((now()-password_updated)> (Interval '" + passwordExpirationSetting + " days')) AS expired FROM xhbm_xdat_user_auth WHERE auth_user = ? AND auth_method = 'localdb'", new String[]{username}, new RowMapper<Boolean>() { public Boolean mapRow(ResultSet rs, int rowNum) throws SQLException { return rs.getBoolean(1); } }); return expired.get(0); } else { - List<Boolean> expired = (new JdbcTemplate(_dataSource)).query("SELECT (to_date('" + getPasswordExpirationSetting() + "', 'MM/DD/YYYY') BETWEEN password_updated AND now()) AS expired FROM xhbm_xdat_user_auth WHERE auth_user = ? AND auth_method = 'localdb'", new String[]{username}, new RowMapper<Boolean>() { + List<Boolean> expired = (new JdbcTemplate(_dataSource)).query("SELECT (to_date('" + new SimpleDateFormat("MM/dd/yyyy").format(new Date(Long.parseLong(passwordExpirationSetting))) + "', 'MM/DD/YYYY') BETWEEN password_updated AND now()) AS expired FROM xhbm_xdat_user_auth WHERE auth_user = ? AND auth_method = 'localdb'", new String[]{username}, new RowMapper<Boolean>() { public Boolean mapRow(ResultSet rs, int rowNum) throws SQLException { return rs.getBoolean(1); } @@ -291,20 +283,20 @@ public class XnatExpiredPasswordFilter extends GenericFilterBean { return false; } - private boolean isPasswordExpirationDisabled() { + private boolean isPasswordExpirationDisabled() throws SiteConfigurationException { if (!passwordExpirationDirtied) { return passwordExpirationDisabled; } - final String type = getSiteConfigurationProperty("passwordExpirationType"); + final String type = _preferences.getPasswordExpirationType(); if (StringUtils.isBlank(type)) { passwordExpirationDisabled = true; } else if (type.equals("Interval")) { passwordExpirationInterval = true; - passwordExpirationSetting = validatePasswordExpirationInterval(getSiteConfigurationProperty("passwordExpirationInterval")); + passwordExpirationSetting = Integer.toString(_preferences.getPasswordExpirationInterval()); passwordExpirationDisabled = passwordExpirationSetting.equals("0"); } else if (type.equals("Date")) { passwordExpirationInterval = false; - passwordExpirationSetting = validatePasswordExpirationDate(getSiteConfigurationProperty("passwordExpirationDate")); + passwordExpirationSetting = Long.toString(_preferences.getPasswordExpirationDate().getTime()); passwordExpirationDisabled = passwordExpirationSetting.equals("0"); } else { passwordExpirationDisabled = true; @@ -313,25 +305,10 @@ public class XnatExpiredPasswordFilter extends GenericFilterBean { return passwordExpirationDisabled; } - private String validatePasswordExpirationInterval(final String passwordExpirationInterval) { - // overly long intervals break the query; this limit allows intervals up to approximately 2700 years, which should be sufficient for most purposes - return StringUtils.isNotBlank(passwordExpirationInterval) && !passwordExpirationInterval.equals("0") && passwordExpirationInterval.length() <= 6 && passwordExpirationInterval.matches("\\d+") ? - passwordExpirationInterval : "0"; - } - - private String validatePasswordExpirationDate(final String passwordExpirationDate) { - return StringUtils.isNotBlank(passwordExpirationDate) && passwordExpirationDate.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d") - ? passwordExpirationDate : "0"; - } - private boolean isPasswordExpirationInterval() { return passwordExpirationInterval; } - private String getPasswordExpirationSetting() { - return passwordExpirationSetting; - } - private boolean isUserNonExpiring(UserI user) { try { return Roles.checkRole(user, UserRole.ROLE_NON_EXPIRING); @@ -350,12 +327,12 @@ public class XnatExpiredPasswordFilter extends GenericFilterBean { } } - private static final Logger _log = LoggerFactory.getLogger(XnatExpiredPasswordFilter.class); - - @Inject - private SiteConfigurationService _siteConfigurationService; + @Autowired + @Lazy + private InitializerSiteConfiguration _preferences; - @Inject + @Autowired + @Lazy private AliasTokenService _aliasTokenService; @Inject diff --git a/src/main/java/org/nrg/xnat/security/XnatLdapUserDetailsMapper.java b/src/main/java/org/nrg/xnat/security/XnatLdapUserDetailsMapper.java index c23f9b4d..cbced69c 100644 --- a/src/main/java/org/nrg/xnat/security/XnatLdapUserDetailsMapper.java +++ b/src/main/java/org/nrg/xnat/security/XnatLdapUserDetailsMapper.java @@ -12,7 +12,7 @@ package org.nrg.xnat.security; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.nrg.config.services.SiteConfigurationService; +import org.nrg.xdat.preferences.SiteConfigPreferences; import org.nrg.xdat.security.helpers.Users; import org.nrg.xdat.services.XdatUserAuthService; import org.nrg.xft.security.UserI; @@ -22,7 +22,6 @@ import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper; import org.springframework.util.Assert; -import javax.inject.Inject; import java.util.Collection; import java.util.HashMap; import java.util.Map; @@ -30,11 +29,11 @@ import java.util.Map; public class XnatLdapUserDetailsMapper extends LdapUserDetailsMapper { public static final String PROPERTY_PREFIX = "attributes."; - public static final String PROPERTY_EMAIL = PROPERTY_PREFIX + "email"; - public static final String PROPERTY_FIRST = PROPERTY_PREFIX + "firstname"; - public static final String PROPERTY_LAST = PROPERTY_PREFIX + "lastname"; + public static final String PROPERTY_EMAIL = PROPERTY_PREFIX + "email"; + public static final String PROPERTY_FIRST = PROPERTY_PREFIX + "firstname"; + public static final String PROPERTY_LAST = PROPERTY_PREFIX + "lastname"; - public XnatLdapUserDetailsMapper(final String authMethodId, final Map<String, String> properties) { + public XnatLdapUserDetailsMapper(final String authMethodId, final Map<String, String> properties, final XdatUserAuthService userAuthService, final SiteConfigPreferences preferences) { super(); Assert.hasText(authMethodId, "You must provide an authentication method ID."); Assert.notEmpty(properties, "You must provide the authentication provider properties."); @@ -60,6 +59,8 @@ public class XnatLdapUserDetailsMapper extends LdapUserDetailsMapper { } _properties = properties; } + _userAuthService = userAuthService; + _preferences = preferences; } @Override @@ -73,8 +74,8 @@ public class XnatLdapUserDetailsMapper extends LdapUserDetailsMapper { UserI userDetails = _userAuthService.getUserDetailsByNameAndAuth(user.getUsername(), XdatUserAuthService.LDAP, _authMethodId, email, lastname, firstname); try { - UserI xdatUser = Users.getUser(userDetails.getUsername()); - if ((!_siteConfigurationService.getBoolSiteConfigurationProperty("emailVerification", false) || xdatUser.isVerified()) && userDetails.getAuthorization().isEnabled()) { + final UserI xdatUser = Users.getUser(userDetails.getUsername()); + if ((!_preferences.getEmailVerification() || xdatUser.isVerified()) && userDetails.getAuthorization().isEnabled()) { return userDetails; } else { throw new NewLdapAccountNotAutoEnabledException( @@ -92,12 +93,8 @@ public class XnatLdapUserDetailsMapper extends LdapUserDetailsMapper { private static final Log _log = LogFactory.getLog(XnatLdapUserDetailsMapper.class); - @Inject - private XdatUserAuthService _userAuthService; - - @Inject - private SiteConfigurationService _siteConfigurationService; - - private final String _authMethodId; - private final Map<String, String> _properties; + private final XdatUserAuthService _userAuthService; + private final SiteConfigPreferences _preferences; + private final String _authMethodId; + private final Map<String, String> _properties; } diff --git a/src/main/java/org/nrg/xnat/security/XnatPasswordEncrypter.java b/src/main/java/org/nrg/xnat/security/XnatPasswordEncrypter.java deleted file mode 100644 index 3bb0feb4..00000000 --- a/src/main/java/org/nrg/xnat/security/XnatPasswordEncrypter.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * org.nrg.xnat.security.XnatPasswordEncrypter - * XNAT http://www.xnat.org - * Copyright (c) 2014, Washington University School of Medicine - * All Rights Reserved - * - * Released under the Simplified BSD. - * - * Last modified 12/11/13 3:33 PM - */ -package org.nrg.xnat.security;/* - * org.nrg.xnat.helpers.prearchive.PrearcDatabase - * XNAT http://www.xnat.org - * Copyright (c) 2013, Washington University School of Medicine - * All Rights Reserved - * - * Released under the Simplified BSD. - * - * Created 12/4/13 3:12 PM - */ - -import org.nrg.xft.db.PoolDBUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.authentication.encoding.ShaPasswordEncoder; - -import java.sql.ResultSet; -import java.util.HashMap; -import java.util.Map; - -public class XnatPasswordEncrypter { - private static Logger logger = LoggerFactory.getLogger(XnatPasswordEncrypter.class); - - public static void execute() { - try { - ShaPasswordEncoder encoder = new ShaPasswordEncoder(256); - - Map<Integer, String> userPasswords = new HashMap<Integer, String>(); - ResultSet rs= new PoolDBUtils().executeQuery(null, "SELECT xdat_user_id, primary_password FROM xdat_user WHERE primary_password IS NOT NULL AND length(primary_password) != 64", null); - while(rs.next()){ - int id = rs.getInt(1); - String password = rs.getString(2); - String encodedPassword = encoder.encodePassword(password, null); - userPasswords.put(id, encodedPassword); - } - - Map<Integer, String> historyPasswords = new HashMap<Integer, String>(); - ResultSet rs2 = new PoolDBUtils().executeQuery(null, "SELECT history_id, primary_password FROM xdat_user_history WHERE primary_password IS NOT NULL AND length(primary_password) != 64", null); - while(rs2.next()){ - int id = rs2.getInt(1); - String password = rs2.getString(2); - String encodedPassword = encoder.encodePassword(password, null); - historyPasswords.put(id, encodedPassword); - } - - for (int userId : userPasswords.keySet()) { - new PoolDBUtils().executeNonSelectQuery("UPDATE xdat_user SET primary_password = '" + userPasswords.get(userId) + "' WHERE xdat_user_id = " + userId, null, null); - } - - for (int historyId : historyPasswords.keySet()) { - new PoolDBUtils().executeNonSelectQuery("UPDATE xdat_user_history SET primary_password = '" + historyPasswords.get(historyId) + "' WHERE history_id = " + historyId, null, null); - } - - if (!userPasswords.isEmpty() || !historyPasswords.isEmpty()) { - new PoolDBUtils().executeNonSelectQuery("DELETE FROM xs_item_cache", null, null); - } - } catch (Exception e) { - logger.error("",e); - } - } -} diff --git a/src/main/java/org/nrg/xnat/security/XnatProviderManager.java b/src/main/java/org/nrg/xnat/security/XnatProviderManager.java index 429e320f..6e1e149f 100644 --- a/src/main/java/org/nrg/xnat/security/XnatProviderManager.java +++ b/src/main/java/org/nrg/xnat/security/XnatProviderManager.java @@ -17,6 +17,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.velocity.VelocityContext; import org.hibernate.exception.DataException; +import org.nrg.framework.services.ContextService; import org.nrg.xdat.XDAT; import org.nrg.xdat.entities.AliasToken; import org.nrg.xdat.entities.UserAuthI; @@ -35,6 +36,9 @@ import org.nrg.xnat.security.provider.XnatLdapAuthenticationProvider; import org.nrg.xnat.security.tokens.XnatDatabaseUsernamePasswordAuthenticationToken; import org.nrg.xnat.security.tokens.XnatLdapUsernamePasswordAuthenticationToken; import org.nrg.xnat.security.userdetailsservices.XnatDatabaseUserDetailsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Lazy; import org.springframework.context.support.MessageSourceAccessor; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; @@ -81,9 +85,8 @@ public class XnatProviderManager extends ProviderManager { // HACK: This is a hack to work around open XNAT auth issue. If this is a bare un/pw auth token, use anon auth. if (authentication.getClass() == UsernamePasswordAuthenticationToken.class && authentication.getName().equalsIgnoreCase("guest")) { - - providers.add(_anonymousAuthenticationProvider); - authentication = new AnonymousAuthenticationToken(_anonymousAuthenticationProvider.getKey(), authentication.getPrincipal(), Collections.<GrantedAuthority>singletonList(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))); + providers.add(getAnonymousAuthenticationProvider()); + authentication = new AnonymousAuthenticationToken(getAnonymousAuthenticationProvider().getKey(), authentication.getPrincipal(), Collections.<GrantedAuthority>singletonList(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))); } else { for (AuthenticationProvider candidate : getProviders()) { if (!candidate.supports(toTest)) { @@ -169,6 +172,10 @@ public class XnatProviderManager extends ProviderManager { } } + private AnonymousAuthenticationProvider getAnonymousAuthenticationProvider() { + return _contextService.getBean(AnonymousAuthenticationProvider.class); + } + public void setProperties(List<String> fileNames) { _properties = new Properties(); for (String filename : fileNames) { @@ -184,7 +191,7 @@ public class XnatProviderManager extends ProviderManager { } } - public static XdatUserAuth getUserByAuth(Authentication authentication) { + public XdatUserAuth getUserByAuth(Authentication authentication) { if(authentication==null){ return null; } @@ -206,7 +213,7 @@ public class XnatProviderManager extends ProviderManager { } try { - return XDAT.getXdatUserAuthService().getUserByNameAndAuth(u, method, provider); + return getUserAuthService().getUserByNameAndAuth(u, method, provider); } catch (DataException exception) { _log.error("An error occurred trying to retrieve the auth method", exception); throw new RuntimeException("An error occurred trying to validate the given information. Please check your username and password. If this problem persists, please contact your system administrator."); @@ -227,7 +234,7 @@ public class XnatProviderManager extends ProviderManager { String auth = cached_methods.get(username); if (auth == null) { try { - List<XdatUserAuth> userAuths = _service.getUsersByName(username); + List<XdatUserAuth> userAuths = getUserAuthService().getUsersByName(username); if (userAuths.size() == 1) { auth = userAuths.get(0).getAuthMethod(); cached_methods.put(username.intern(), auth.intern()); @@ -252,6 +259,13 @@ public class XnatProviderManager extends ProviderManager { return auth; } + private XdatUserAuthService getUserAuthService() { + if (_userAuthService == null) { + _userAuthService = _contextService.getBean(XdatUserAuthService.class); + } + return _userAuthService; + } + private static UsernamePasswordAuthenticationToken buildUPToken(XnatAuthenticationProvider provider, String username, String password){ if (provider instanceof XnatLdapAuthenticationProvider) { return new XnatLdapUsernamePasswordAuthenticationToken(username, password, provider.getProviderId()); @@ -301,8 +315,13 @@ public class XnatProviderManager extends ProviderManager { private static final class AuthenticationAttemptEventPublisher implements AuthenticationEventPublisher { - private final FailedAttemptsManager failedAttemptsManager = new FailedAttemptsManager(); - private final LastSuccessfulLoginManager lastSuccessfulLoginManager = new LastSuccessfulLoginManager(); + private final FailedAttemptsManager failedAttemptsManager; + private final LastSuccessfulLoginManager lastSuccessfulLoginManager; + + private AuthenticationAttemptEventPublisher(final XnatProviderManager manager) { + failedAttemptsManager = new FailedAttemptsManager(manager); + lastSuccessfulLoginManager = new LastSuccessfulLoginManager(manager); + } public void publishAuthenticationFailure(AuthenticationException exception, Authentication authentication) { //increment failed login attempt @@ -316,27 +335,41 @@ public class XnatProviderManager extends ProviderManager { } private static final class LastSuccessfulLoginManager { + private final XnatProviderManager _manager; + + public LastSuccessfulLoginManager(final XnatProviderManager manager) { + _manager = manager; + } + private void updateLastSuccessfulLogin(Authentication auth) { - XdatUserAuth ua = getUserByAuth(auth); + XdatUserAuth ua = _manager.getUserByAuth(auth); if (ua != null) { Date now = java.util.Calendar.getInstance(TimeZone.getDefault()).getTime(); ua.setLastSuccessfulLogin(now); + ua.setLastLoginAttempt(now); XDAT.getXdatUserAuthService().update(ua); } } } private static final class FailedAttemptsManager { + private final XnatProviderManager _manager; + + public FailedAttemptsManager(final XnatProviderManager manager) { + _manager = manager; + } + /** * Increments failed Login count * * @param auth The authentication that failed. */ private synchronized void addFailedLoginAttempt(final Authentication auth) { - XdatUserAuth ua = getUserByAuth(auth); + XdatUserAuth ua = _manager.getUserByAuth(auth); if (ua != null) { if (AuthUtils.MAX_FAILED_LOGIN_ATTEMPTS > 0) { ua.setFailedLoginAttempts(ua.getFailedLoginAttempts() + 1); + ua.setLastLoginAttempt(new Date()); XDAT.getXdatUserAuthService().update(ua); } @@ -359,7 +392,7 @@ public class XnatProviderManager extends ProviderManager { public void clearCount(final Authentication auth) { if (AuthUtils.MAX_FAILED_LOGIN_ATTEMPTS > 0) { - XdatUserAuth ua = getUserByAuth(auth); + XdatUserAuth ua = _manager.getUserByAuth(auth); if (ua != null) { ua.setFailedLoginAttempts(0); XDAT.getXdatUserAuthService().update(ua); @@ -382,14 +415,15 @@ public class XnatProviderManager extends ProviderManager { protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); @Inject - private XdatUserAuthService _service; + private DataSource _dataSource; - @Inject - private AnonymousAuthenticationProvider _anonymousAuthenticationProvider; + @Autowired + @Qualifier("rootContextService") + @Lazy + private ContextService _contextService; - @Inject - private DataSource _dataSource; + private XdatUserAuthService _userAuthService; - private final AuthenticationEventPublisher eventPublisher = new AuthenticationAttemptEventPublisher(); + private final AuthenticationEventPublisher eventPublisher = new AuthenticationAttemptEventPublisher(this); private Properties _properties; } diff --git a/src/main/java/org/nrg/xnat/security/alias/AliasTokenAuthenticationProvider.java b/src/main/java/org/nrg/xnat/security/alias/AliasTokenAuthenticationProvider.java index 37e51060..bce95af4 100644 --- a/src/main/java/org/nrg/xnat/security/alias/AliasTokenAuthenticationProvider.java +++ b/src/main/java/org/nrg/xnat/security/alias/AliasTokenAuthenticationProvider.java @@ -17,6 +17,8 @@ import org.nrg.xdat.services.AliasTokenService; import org.nrg.xdat.services.XdatUserAuthService; import org.nrg.xft.security.UserI; import org.nrg.xnat.security.provider.XnatAuthenticationProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -176,10 +178,12 @@ public class AliasTokenAuthenticationProvider extends AbstractUserDetailsAuthent return _userAuthService.getUserDetailsByUsernameAndMostRecentSuccessfulLogin(token.getXdatUserId()); } - @Inject + @Autowired + @Lazy private AliasTokenService _aliasTokenService; - @Inject + @Autowired + @Lazy private XdatUserAuthService _userAuthService; private String _name; diff --git a/src/main/java/org/nrg/xnat/security/alias/ClearExpiredAliasTokens.java b/src/main/java/org/nrg/xnat/security/alias/ClearExpiredAliasTokens.java index 5d8067cf..cb1ed6fc 100644 --- a/src/main/java/org/nrg/xnat/security/alias/ClearExpiredAliasTokens.java +++ b/src/main/java/org/nrg/xnat/security/alias/ClearExpiredAliasTokens.java @@ -14,17 +14,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; -import javax.sql.DataSource; import java.util.Arrays; import java.util.List; public class ClearExpiredAliasTokens implements Runnable { - public ClearExpiredAliasTokens(final DataSource dataSource, final String timeout) { + public ClearExpiredAliasTokens(final JdbcTemplate template, final String timeout) { if (_log.isDebugEnabled()) { _log.debug("Initializing the alias token sweeper job with an interval of: " + timeout); } - _dataSource = dataSource; + _template = template; _timeout = timeout; } @@ -35,13 +34,12 @@ public class ClearExpiredAliasTokens implements Runnable { if (_log.isDebugEnabled()) { _log.debug("Executing alias token sweep function"); } - JdbcTemplate template = new JdbcTemplate(_dataSource); for (final String format : ALIAS_TOKEN_QUERIES) { final String query = String.format(format, _timeout); if (_log.isDebugEnabled()) { _log.debug("Executing alias token sweep query: " + query); } - template.execute(query); + _template.execute(query); } } @@ -50,6 +48,6 @@ public class ClearExpiredAliasTokens implements Runnable { private static final String QUERY_DELETE_ALIAS_TOKENS = "DELETE FROM xhbm_alias_token WHERE created < NOW() - INTERVAL '%s'"; private static final List<String> ALIAS_TOKEN_QUERIES = Arrays.asList(QUERY_DELETE_TOKEN_IP_ADDRESSES, QUERY_DELETE_ALIAS_TOKENS); - private final DataSource _dataSource; - private final String _timeout; + private final JdbcTemplate _template; + private final String _timeout; } diff --git a/src/main/java/org/nrg/xnat/security/config/DatabaseAuthenticationProviderConfigurator.java b/src/main/java/org/nrg/xnat/security/config/DatabaseAuthenticationProviderConfigurator.java index 4b6eecb3..3f338a30 100644 --- a/src/main/java/org/nrg/xnat/security/config/DatabaseAuthenticationProviderConfigurator.java +++ b/src/main/java/org/nrg/xnat/security/config/DatabaseAuthenticationProviderConfigurator.java @@ -10,15 +10,16 @@ */ package org.nrg.xnat.security.config; -import org.nrg.config.services.SiteConfigurationService; +import org.nrg.xdat.preferences.InitializerSiteConfiguration; import org.nrg.xdat.security.ObfuscatedPasswordEncoder; import org.nrg.xnat.security.provider.XnatDatabaseAuthenticationProvider; import org.nrg.xnat.security.userdetailsservices.XnatDatabaseUserDetailsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.ReflectionSaltSource; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; -import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -31,7 +32,7 @@ public class DatabaseAuthenticationProviderConfigurator extends AbstractAuthenti ReflectionSaltSource saltSource = new ReflectionSaltSource(); saltSource.setUserPropertyToUse("salt"); - XnatDatabaseAuthenticationProvider sha2DatabaseAuthProvider = new XnatDatabaseAuthenticationProvider(_siteConfigurationService); + XnatDatabaseAuthenticationProvider sha2DatabaseAuthProvider = new XnatDatabaseAuthenticationProvider(_preferences.getEmailVerification()); ShaPasswordEncoder encoder = new ShaPasswordEncoder(256); sha2DatabaseAuthProvider.setUserDetailsService(_detailsService); sha2DatabaseAuthProvider.setPasswordEncoder(encoder); @@ -40,7 +41,7 @@ public class DatabaseAuthenticationProviderConfigurator extends AbstractAuthenti sha2DatabaseAuthProvider.setSaltSource(saltSource); providers.add(sha2DatabaseAuthProvider); - XnatDatabaseAuthenticationProvider sha2ObfuscatedDatabaseAuthProvider = new XnatDatabaseAuthenticationProvider(_siteConfigurationService); + XnatDatabaseAuthenticationProvider sha2ObfuscatedDatabaseAuthProvider = new XnatDatabaseAuthenticationProvider(_preferences.getEmailVerification()); ObfuscatedPasswordEncoder encoder2 = new ObfuscatedPasswordEncoder(256); sha2ObfuscatedDatabaseAuthProvider.setUserDetailsService(_detailsService); sha2ObfuscatedDatabaseAuthProvider.setPasswordEncoder(encoder2); @@ -57,11 +58,10 @@ public class DatabaseAuthenticationProviderConfigurator extends AbstractAuthenti return getAuthenticationProviders(id, name); } - @Inject + @Autowired + @Lazy private XnatDatabaseUserDetailsService _detailsService; - @Inject - private SiteConfigurationService _siteConfigurationService; - - + @Autowired + private InitializerSiteConfiguration _preferences; } diff --git a/src/main/java/org/nrg/xnat/security/config/LdapAuthenticationProviderConfigurator.java b/src/main/java/org/nrg/xnat/security/config/LdapAuthenticationProviderConfigurator.java index 874b2d0d..b0e535b1 100644 --- a/src/main/java/org/nrg/xnat/security/config/LdapAuthenticationProviderConfigurator.java +++ b/src/main/java/org/nrg/xnat/security/config/LdapAuthenticationProviderConfigurator.java @@ -13,9 +13,13 @@ package org.nrg.xnat.security.config; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.nrg.xdat.preferences.SiteConfigPreferences; +import org.nrg.xdat.services.XdatUserAuthService; import org.nrg.xnat.security.XnatLdapAuthoritiesPopulator; import org.nrg.xnat.security.XnatLdapUserDetailsMapper; import org.nrg.xnat.security.provider.XnatLdapAuthenticationProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.ldap.DefaultSpringSecurityContextSource; import org.springframework.security.ldap.authentication.BindAuthenticator; @@ -35,7 +39,7 @@ public class LdapAuthenticationProviderConfigurator extends AbstractAuthenticati public List<AuthenticationProvider> getAuthenticationProviders(String id, String name, Map<String, String> properties) { try { XnatLdapAuthenticationProvider ldapAuthProvider = new XnatLdapAuthenticationProvider(getBindAuthenticator(properties, getLdapContextSource(properties)), new XnatLdapAuthoritiesPopulator()); - ldapAuthProvider.setUserDetailsContextMapper(new XnatLdapUserDetailsMapper(id, properties)); + ldapAuthProvider.setUserDetailsContextMapper(new XnatLdapUserDetailsMapper(id, properties, _userAuthService, _preferences)); ldapAuthProvider.setName(name); ldapAuthProvider.setProviderId(id); return Arrays.asList(new AuthenticationProvider[] { ldapAuthProvider }); @@ -60,4 +64,12 @@ public class LdapAuthenticationProviderConfigurator extends AbstractAuthenticati } private static final Log _log = LogFactory.getLog(LdapAuthenticationProviderConfigurator.class); + + @Autowired + @Lazy + private XdatUserAuthService _userAuthService; + + @Autowired + @Lazy + private SiteConfigPreferences _preferences; } diff --git a/src/main/java/org/nrg/xnat/security/provider/XnatDatabaseAuthenticationProvider.java b/src/main/java/org/nrg/xnat/security/provider/XnatDatabaseAuthenticationProvider.java index cef069f4..ed43dced 100644 --- a/src/main/java/org/nrg/xnat/security/provider/XnatDatabaseAuthenticationProvider.java +++ b/src/main/java/org/nrg/xnat/security/provider/XnatDatabaseAuthenticationProvider.java @@ -10,17 +10,11 @@ */ package org.nrg.xnat.security.provider; -import org.nrg.config.services.SiteConfigurationService; import org.nrg.xdat.services.XdatUserAuthService; import org.nrg.xft.db.PoolDBUtils; import org.nrg.xft.security.UserI; import org.nrg.xnat.security.tokens.XnatDatabaseUsernamePasswordAuthenticationToken; -import org.springframework.security.authentication.AccountExpiredException; -import org.springframework.security.authentication.AuthenticationServiceException; -import org.springframework.security.authentication.CredentialsExpiredException; -import org.springframework.security.authentication.DisabledException; -import org.springframework.security.authentication.LockedException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.authentication.*; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.PlaintextPasswordEncoder; import org.springframework.security.core.AuthenticationException; @@ -29,9 +23,9 @@ import org.springframework.security.core.userdetails.UserDetailsChecker; public class XnatDatabaseAuthenticationProvider extends DaoAuthenticationProvider implements XnatAuthenticationProvider { - public XnatDatabaseAuthenticationProvider(final SiteConfigurationService siteConfigurationService) { + public XnatDatabaseAuthenticationProvider(final boolean requireEmailVerification) { super(); - _siteConfigurationService = siteConfigurationService; + _requireEmailVerification = requireEmailVerification; this.setPreAuthenticationChecks(new PreAuthenticationChecks()); } @@ -85,7 +79,7 @@ public class XnatDatabaseAuthenticationProvider extends DaoAuthenticationProvide throw new AuthenticationServiceException("User details class is not of a type I know how to handle: " + userDetails.getClass()); } final UserI xdatUserDetails = (UserI) userDetails; - if ((_siteConfigurationService.getBoolSiteConfigurationProperty("emailVerification", false) && !xdatUserDetails.isVerified() && xdatUserDetails.isEnabled()) || !xdatUserDetails.isAccountNonLocked()) { + if ((_requireEmailVerification && !xdatUserDetails.isVerified() && xdatUserDetails.isEnabled()) || !xdatUserDetails.isAccountNonLocked()) { throw new CredentialsExpiredException("Attempted login to unverified or locked account: " + xdatUserDetails.getUsername()); } super.additionalAuthenticationChecks(userDetails, authentication); @@ -95,8 +89,6 @@ public class XnatDatabaseAuthenticationProvider extends DaoAuthenticationProvide return (this.getPasswordEncoder().getClass() == plainText); } - private final SiteConfigurationService _siteConfigurationService; - private String displayName = ""; private String _providerId = ""; private Class plainText = PlaintextPasswordEncoder.class; @@ -148,4 +140,6 @@ public class XnatDatabaseAuthenticationProvider extends DaoAuthenticationProvide return false; } } + + private final boolean _requireEmailVerification; } diff --git a/src/main/java/org/nrg/xnat/security/userdetailsservices/XnatDatabaseUserDetailsService.java b/src/main/java/org/nrg/xnat/security/userdetailsservices/XnatDatabaseUserDetailsService.java index 0dc6d84b..a69154c7 100644 --- a/src/main/java/org/nrg/xnat/security/userdetailsservices/XnatDatabaseUserDetailsService.java +++ b/src/main/java/org/nrg/xnat/security/userdetailsservices/XnatDatabaseUserDetailsService.java @@ -1,43 +1,54 @@ /* - * org.nrg.xnat.security.userdetailsservices.XnatDatabaseUserDetailsService + * XnatDatabaseUserDetailsService * XNAT http://www.xnat.org - * Copyright (c) 2014, Washington University School of Medicine + * Copyright (c) 2016, Washington University School of Medicine * All Rights Reserved * * Released under the Simplified BSD. - * - * Last modified 7/10/13 9:04 PM */ package org.nrg.xnat.security.userdetailsservices; +import org.nrg.framework.services.ContextService; import org.nrg.xdat.services.XdatUserAuthService; import org.nrg.xnat.security.PasswordExpiredException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Lazy; import org.springframework.dao.DataAccessException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl; -import javax.inject.Inject; - public class XnatDatabaseUserDetailsService extends JdbcDaoImpl implements UserDetailsService { // MIGRATION: This needs to go away and be replaced by a standard property for an XNAT user details service. - public static final String DB_PROVIDER = ""; - - @Override + public static final String DB_PROVIDER = ""; + + @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException, PasswordExpiredException { - UserDetails user = _service.getUserDetailsByNameAndAuth(username, XdatUserAuthService.LOCALDB, DB_PROVIDER); + UserDetails user = getXdatUserAuthService().getUserDetailsByNameAndAuth(username, XdatUserAuthService.LOCALDB, DB_PROVIDER); if (_log.isDebugEnabled()) { _log.debug("Loaded user {} by username from user-auth service.", user.getUsername()); } return user; } + private XdatUserAuthService getXdatUserAuthService() { + if (_xdatUserAuthService == null) { + _xdatUserAuthService = _contextService.getBean(XdatUserAuthService.class); + } + return _xdatUserAuthService; + } + private static final Logger _log = LoggerFactory.getLogger(XnatDatabaseUserDetailsService.class); - @Inject - private XdatUserAuthService _service; + @Autowired + @Qualifier("rootContextService") + @Lazy + private ContextService _contextService; + + private XdatUserAuthService _xdatUserAuthService; } diff --git a/src/main/java/org/nrg/xnat/utils/XnatUserProvider.java b/src/main/java/org/nrg/xnat/utils/XnatUserProvider.java index 42d296ce..cbc893b8 100644 --- a/src/main/java/org/nrg/xnat/utils/XnatUserProvider.java +++ b/src/main/java/org/nrg/xnat/utils/XnatUserProvider.java @@ -10,13 +10,15 @@ */ package org.nrg.xnat.utils; -import javax.inject.Provider; - import org.nrg.xdat.security.helpers.Users; import org.nrg.xft.security.UserI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.inject.Provider; +@Component public class XnatUserProvider implements Provider<UserI> { public XnatUserProvider(final String login) { _login = login; diff --git a/src/main/resources/META-INF/xnat/entities/xnat-entity-packages.txt b/src/main/resources/META-INF/xnat/entities/xnat-entity-packages.txt new file mode 100644 index 00000000..91c8dacd --- /dev/null +++ b/src/main/resources/META-INF/xnat/entities/xnat-entity-packages.txt @@ -0,0 +1,12 @@ +org.nrg.automation.entities +org.nrg.config.entities +org.nrg.dcm.xnat +org.nrg.framework.datacache +org.nrg.notify.entities +org.nrg.prefs.entities +org.nrg.xdat.entities +org.nrg.xft.entities +org.nrg.xft.event.entities +org.nrg.xnat.entities +org.nrg.xnat.event.entities +org.nrg.xnat.spawner.entities diff --git a/src/main/webapp/WEB-INF/conf/TurbineResources.properties b/src/main/webapp/WEB-INF/conf/TurbineResources.properties index f6653832..4671c0b6 100644 --- a/src/main/webapp/WEB-INF/conf/TurbineResources.properties +++ b/src/main/webapp/WEB-INF/conf/TurbineResources.properties @@ -270,7 +270,7 @@ services.ServletService.classname=org.apache.turbine.services.servlet.TurbineSer services.AssemblerBrokerService.classname=org.apache.turbine.services.assemblerbroker.TurbineAssemblerBrokerService services.GlobalCacheService.classname=org.apache.turbine.services.cache.TurbineGlobalCacheService services.PullService.classname=org.apache.turbine.services.pull.TurbinePullService -services.IntakeService.classname=org.apache.turbine.services.intake.TurbineIntakeService +# services.IntakeService.classname=org.apache.turbine.services.intake.TurbineIntakeService services.TemplateService.classname=org.apache.turbine.services.template.TurbineTemplateService services.VelocityService.classname=org.apache.turbine.services.velocity.TurbineVelocityService services.UploadService.classname=org.apache.turbine.services.upload.TurbineUploadService @@ -421,7 +421,7 @@ tool.session.sessionData=org.apache.turbine.services.pull.util.SessionData # These are intake tools. #tool.request.om=org.apache.turbine.om.OMTool -tool.request.intake=org.apache.turbine.services.intake.IntakeTool +# tool.request.intake=org.apache.turbine.services.intake.IntakeTool # This is a tool that allows access to the scheduler service. #tool.request.scheduler=org.apache.turbine.services.SchedulerTool @@ -630,7 +630,7 @@ services.PoolService.pool.capacity = 128 # # Default: WEB-INF/appData.ser # -services.IntakeService.serialize.path= none +# services.IntakeService.serialize.path= none #WEB-INF/appData.ser #-------------------------------------------------------------------- diff --git a/src/main/webapp/WEB-INF/conf/mq-context.xml b/src/main/webapp/WEB-INF/conf/mq-context.xml index 5e682487..2afc1210 100644 --- a/src/main/webapp/WEB-INF/conf/mq-context.xml +++ b/src/main/webapp/WEB-INF/conf/mq-context.xml @@ -12,17 +12,12 @@ <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns:context="http://www.springframework.org/schema/context" xmlns:amq="http://activemq.apache.org/schema/core" xmlns:jms="http://www.springframework.org/schema/jms" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd - http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd"> - <!-- Pull in property values from services definition files. --> - <context:property-placeholder location="WEB-INF/conf/services.properties, WEB-INF/conf/services-custom.properties" ignore-resource-not-found="true" ignore-unresolvable="true" /> - <!-- embedded ActiveMQ Broker --> <amq:broker id="activeMQBroker" brokerName="activeMQBroker" useJmx="false" persistent="true" schedulerSupport="false" useShutdownHook="false"> <amq:persistenceAdapter> @@ -33,9 +28,9 @@ </amq:persistenceAdapter> <amq:systemUsage> <amq:systemUsage> - <amq:tempUsage><amq:tempUsage limit="${amq.usage.temp}"/></amq:tempUsage> - <amq:memoryUsage><amq:memoryUsage limit="${amq.usage.mem}"/></amq:memoryUsage> - <amq:storeUsage><amq:storeUsage limit="${amq.usage.store}"/></amq:storeUsage> + <amq:tempUsage><amq:tempUsage limit="${amq.usage.temp:128mb}"/></amq:tempUsage> + <amq:memoryUsage><amq:memoryUsage limit="${amq.usage.mem:512mb}"/></amq:memoryUsage> + <amq:storeUsage><amq:storeUsage limit="${amq.usage.store:1gb}"/></amq:storeUsage> </amq:systemUsage> </amq:systemUsage> </amq:broker> diff --git a/src/main/webapp/WEB-INF/conf/xnat-conf.properties b/src/main/webapp/WEB-INF/conf/xnat-conf.properties index 518aba10..0592e4d2 100644 --- a/src/main/webapp/WEB-INF/conf/xnat-conf.properties +++ b/src/main/webapp/WEB-INF/conf/xnat-conf.properties @@ -15,4 +15,8 @@ hibernate.dialect=org.hibernate.dialect.PostgreSQL9Dialect hibernate.hbm2ddl.auto=update hibernate.show_sql=false hibernate.cache.use_second_level_cache=true -hibernate.cache.use_query_cache=true \ No newline at end of file +hibernate.cache.use_query_cache=true + +amq.usage.temp=128mb +amq.usage.mem=512mb +amq.usage.store=1gb -- GitLab