diff --git a/build.gradle b/build.gradle index c4358a0c9775af41ce7b1ab19ce7ecc2207cfda3..7822995b9d21f0e9b7ae4d3e685a028736c83115 100644 --- a/build.gradle +++ b/build.gradle @@ -18,11 +18,14 @@ def vGroovy = '2.4.6' def vJython = '2.7.0' group 'org.nrg.xnat' -version vXnat buildscript { repositories { mavenLocal() + jcenter() + maven { + url "https://plugins.gradle.org/m2/" + } maven { url 'https://nrgxnat.artifactoryonline.com/nrgxnat/libs-release' name 'XNAT Release Repository' @@ -31,11 +34,11 @@ buildscript { url 'https://nrgxnat.artifactoryonline.com/nrgxnat/libs-snapshot' name 'XNAT Snapshot Repository' } - jcenter() } dependencies { classpath "com.bmuschko:gradle-cargo-plugin:2.2.2" classpath "com.bmuschko:gradle-tomcat-plugin:2.2.4" + classpath "gradle.plugin.com.zoltu.gradle.plugin:git-versioning:2.0.19" } } @@ -46,6 +49,7 @@ apply plugin: 'maven' apply plugin: 'maven-publish' apply plugin: 'com.bmuschko.tomcat' apply plugin: 'com.bmuschko.cargo' +apply plugin: "com.zoltu.git-versioning" apply plugin: 'idea' apply plugin: 'eclipse' @@ -135,6 +139,26 @@ if (JavaVersion.current().isJava8Compatible()) { } } +// Pulls in the Jenkins BUILD_NUMBER environment variable if available. +def buildNumber = hasProperty("BUILD_NUMBER") ? getProperty("BUILD_NUMBER") : "Manual" +def buildDate = new Date() + +jar { + manifest { + attributes 'Build-Number': buildNumber, + 'Build-Date': buildDate, + 'Application-Name': 'XNAT' + } +} + +war { + manifest { + attributes 'Build-Number': buildNumber, + 'Build-Date': buildDate, + 'Application-Name': 'XNAT' + } +} + task sourceJar(type: Jar, dependsOn: classes) { from sourceSets.main.allSource } diff --git a/src/main/java/org/nrg/pipeline/XnatPipelineLauncher.java b/src/main/java/org/nrg/pipeline/XnatPipelineLauncher.java index c912575f44b720c9d156b1c9f186a0ed0139eb9e..e88d15ba45848bc0f9db1244a01339fd0d4acdc8 100644 --- a/src/main/java/org/nrg/pipeline/XnatPipelineLauncher.java +++ b/src/main/java/org/nrg/pipeline/XnatPipelineLauncher.java @@ -22,9 +22,7 @@ import org.nrg.xdat.om.WrkWorkflowdata; import org.nrg.xdat.om.XnatExperimentdata; import org.nrg.xdat.om.XnatImagesessiondata; import org.nrg.xdat.services.AliasTokenService; -import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xdat.turbine.utils.TurbineUtils; -import org.nrg.xft.XFT; import org.nrg.xft.event.EventUtils; import org.nrg.xft.security.UserI; import org.nrg.xnat.turbine.utils.ArcSpecManager; @@ -54,8 +52,8 @@ public class XnatPipelineLauncher { private UserI user; private String dataType; private String host; - private Set<String> notificationEmailIds = new HashSet<String>(); - private Map<String, List<String>> parameters = new Hashtable<String, List<String>>(); + private Set<String> notificationEmailIds = new HashSet<>(); + private Map<String, List<String>> parameters = new Hashtable<>(); private String startAt; private boolean waitFor; private boolean needsBuildDir; @@ -136,7 +134,7 @@ public class XnatPipelineLauncher { } if (needsBuildDir) { - parameters.put("builddir", Arrays.asList(path)); + parameters.put("builddir", Collections.singletonList(path)); } setNeedsBuildDir(false); @@ -159,7 +157,7 @@ public class XnatPipelineLauncher { } public XnatPipelineLauncher(RunData data, Context context) { - user = TurbineUtils.getUser(data); + user = XDAT.getUserDetails(); host = TurbineUtils.GetFullServerPath(); startAt = null; supressNotification = false; @@ -182,7 +180,7 @@ public class XnatPipelineLauncher { private void addUserEmailForNotification() { notify(user.getEmail()); - notify(AdminUtils.getAdminEmailId()); + notify(XDAT.getSiteConfigPreferences().getAdminEmail()); } /* @@ -192,7 +190,7 @@ public class XnatPipelineLauncher { */ public boolean launch() { - return launch(XFT.GetPipelinePath() + "bin" + File.separator + SCHEDULE); + return launch(XDAT.getSiteConfigPreferences().getPipelinePath() + "bin" + File.separator + SCHEDULE); } /* @@ -305,7 +303,7 @@ public class XnatPipelineLauncher { command = ""; } - command += XFT.GetPipelinePath() + "bin" + File.separator + "XnatPipelineLauncher"; + command += XDAT.getSiteConfigPreferences().getAdminEmail() + "bin" + File.separator + "XnatPipelineLauncher"; if (System.getProperty("os.name").toUpperCase().startsWith("WINDOWS")) { command += ".bat"; @@ -330,9 +328,9 @@ public class XnatPipelineLauncher { * @return The pipeline configuration arguments. */ private List<String> getPipelineConfigurationArguments() { - List<String> arguments = new ArrayList<String>(); + List<String> arguments = new ArrayList<>(); try { - String pipelinePath = new File(XFT.GetPipelinePath()).getCanonicalPath(); + String pipelinePath = new File(XDAT.getSiteConfigPreferences().getAdminEmail()).getCanonicalPath(); boolean requiresQuotes = pipelinePath.contains(" "); arguments.add("-config"); String configPath = pipelinePath + File.separator + "pipeline.config"; @@ -361,7 +359,7 @@ public class XnatPipelineLauncher { private List<String> getCommandLineArguments() { AliasToken token = XDAT.getContextService().getBean(AliasTokenService.class).issueTokenForUser(user); - List<String> arguments = new ArrayList<String>(); + List<String> arguments = new ArrayList<>(); arguments.add("-pipeline"); arguments.add(pipelineName); arguments.add("-id"); @@ -437,7 +435,7 @@ public class XnatPipelineLauncher { } private Integer initiateWorkflowEntry() throws Exception { - WrkWorkflowdata wrk = new WrkWorkflowdata((UserI)user); + WrkWorkflowdata wrk = new WrkWorkflowdata(user); wrk.setDataType(this.getDataType()); wrk.setId(this.getId()); wrk.setExternalid(this.getExternalId()); @@ -516,7 +514,7 @@ public class XnatPipelineLauncher { if (parameters.containsKey(name)) { parameters.get(name).add(value); } else { - parameters.put(name, Arrays.asList(value)); + parameters.put(name, Collections.singletonList(value)); } } @@ -528,7 +526,7 @@ public class XnatPipelineLauncher { buildPath = buildPath.substring(0, buildPath.length() - 1); } if (needsBuildDir) { - parameters.put("builddir", Arrays.asList(buildPath + File.separator + "Pipeline")); + parameters.put("builddir", Collections.singletonList(buildPath + File.separator + "Pipeline")); } } @@ -622,11 +620,11 @@ public class XnatPipelineLauncher { public static XnatPipelineLauncher GetLauncherForExperiment(RunData data, Context context, XnatExperimentdata imageSession) throws Exception { XnatPipelineLauncher xnatPipelineLauncher = new XnatPipelineLauncher(data, context); xnatPipelineLauncher.setSupressNotification(true); - UserI user = TurbineUtils.getUser(data); + UserI user = XDAT.getUserDetails(); xnatPipelineLauncher.setParameter("useremail", user.getEmail()); xnatPipelineLauncher.setParameter("userfullname", XnatPipelineLauncher.getUserName(user)); - xnatPipelineLauncher.setParameter("adminemail", AdminUtils.getAdminEmailId()); - xnatPipelineLauncher.setParameter("mailhost", AdminUtils.getMailServer()); + xnatPipelineLauncher.setParameter("adminemail", XDAT.getSiteConfigPreferences().getAdminEmail()); + xnatPipelineLauncher.setParameter("mailhost", XDAT.getSiteConfigPreferences().getSmtpServer().get("host")); xnatPipelineLauncher.setParameter("xnatserver", TurbineUtils.GetSystemName()); xnatPipelineLauncher.setId(imageSession.getId()); @@ -637,8 +635,8 @@ public class XnatPipelineLauncher { xnatPipelineLauncher.setParameter("project", imageSession.getProject()); xnatPipelineLauncher.setParameter("cachepath", QCImageCreator.getQCCachePathForSession(imageSession.getProject())); - List<String> emails = new ArrayList<String>(); - emails.add(TurbineUtils.getUser(data).getEmail()); + List<String> emails = new ArrayList<>(); + emails.add(XDAT.getUserDetails().getEmail()); String extraEmails = (String) TurbineUtils.GetPassedParameter("emailField", data); if (!StringUtils.isBlank(extraEmails)) { @@ -659,11 +657,11 @@ public class XnatPipelineLauncher { public static XnatPipelineLauncher GetBareLauncherForExperiment(RunData data, Context context, XnatExperimentdata imageSession) throws Exception { XnatPipelineLauncher xnatPipelineLauncher = new XnatPipelineLauncher(data, context); xnatPipelineLauncher.setSupressNotification(true); - UserI user = TurbineUtils.getUser(data); + UserI user = XDAT.getUserDetails(); xnatPipelineLauncher.setParameter("useremail", user.getEmail()); xnatPipelineLauncher.setParameter("userfullname", XnatPipelineLauncher.getUserName(user)); - xnatPipelineLauncher.setParameter("adminemail", AdminUtils.getAdminEmailId()); - xnatPipelineLauncher.setParameter("mailhost", AdminUtils.getMailServer()); + xnatPipelineLauncher.setParameter("adminemail", XDAT.getSiteConfigPreferences().getAdminEmail()); + xnatPipelineLauncher.setParameter("mailhost", XDAT.getSiteConfigPreferences().getSmtpServer().get("host")); xnatPipelineLauncher.setParameter("xnatserver", TurbineUtils.GetSystemName()); xnatPipelineLauncher.setId(imageSession.getId()); diff --git a/src/main/java/org/nrg/pipeline/utils/PipelineFileUtils.java b/src/main/java/org/nrg/pipeline/utils/PipelineFileUtils.java index 9799b168ddac98e10c72c41843ce4044cb1c0198..4165fa6172bfbf241f497af456af81c1eb0b972b 100644 --- a/src/main/java/org/nrg/pipeline/utils/PipelineFileUtils.java +++ b/src/main/java/org/nrg/pipeline/utils/PipelineFileUtils.java @@ -15,13 +15,14 @@ import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; import org.nrg.pipeline.xmlbeans.PipelineDocument; +import org.nrg.xdat.XDAT; import org.nrg.xdat.om.ArcProject; -import org.nrg.xft.XFT; import org.nrg.xnat.turbine.utils.ArcSpecManager; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Arrays; import java.util.Calendar; public class PipelineFileUtils { @@ -35,7 +36,7 @@ public class PipelineFileUtils { xopt.setErrorListener(errors); XmlObject xo = XmlObject.Factory.parse(xmlFile, xopt); if (errors.size() != 0) { - throw new XmlException(errors.toArray().toString()); + throw new XmlException(Arrays.toString(errors.toArray())); } //String err = XMLBeansUtils.validateAndGetErrors(xo); //if (err != null) { @@ -54,7 +55,7 @@ public class PipelineFileUtils { public static String getMaxMatching(String file1, String file2, String scanId1, String scanId2) { - String rtn = null; + String rtn; if (file1 == null || file2 == null || scanId1 == null || scanId2 == null) return null; int index = 0; while (true) { @@ -91,7 +92,7 @@ public class PipelineFileUtils { public static String getBuildDir(String project, boolean postfixTimestamp) { ArcProject arcProject = ArcSpecManager.GetFreshInstance().getProjectArc(project); - String buildPath = XFT.GetPipelinePath() ; + String buildPath = XDAT.getSiteConfigPreferences().getAdminEmail() ; if (arcProject != null) { buildPath = arcProject.getPaths().getBuildpath(); } diff --git a/src/main/java/org/nrg/viewer/QCImageCreator.java b/src/main/java/org/nrg/viewer/QCImageCreator.java index fee11743b79e4e518538629459ae7aea18c27dd0..9a13829c9ff00c730f461e219d88fc999cf618df 100644 --- a/src/main/java/org/nrg/viewer/QCImageCreator.java +++ b/src/main/java/org/nrg/viewer/QCImageCreator.java @@ -11,24 +11,22 @@ package org.nrg.viewer; -import java.io.File; - -import org.apache.log4j.Logger; import org.nrg.pipeline.XnatPipelineLauncher; import org.nrg.plexiViewer.lite.xml.PlexiViewerSpecForSession; import org.nrg.plexiViewer.manager.PlexiSpecDocReader; +import org.nrg.xdat.XDAT; import org.nrg.xdat.om.XnatMrsessiondata; -import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.security.UserI; import org.nrg.xnat.turbine.utils.ArcSpecManager; +import java.io.File; + public class QCImageCreator { XnatMrsessiondata mrSession; UserI user; - static Logger logger = Logger.getLogger(QCImageCreator.class); - + public QCImageCreator(XnatMrsessiondata mrSession, UserI user) { this.mrSession = mrSession; this.user = user; @@ -38,7 +36,7 @@ public class QCImageCreator { public boolean createQCImagesForScans() throws Exception { XnatPipelineLauncher xnatPipelineLauncher = new XnatPipelineLauncher(user); - xnatPipelineLauncher.setAdmin_email(AdminUtils.getAdminEmailId()); + xnatPipelineLauncher.setAdmin_email(XDAT.getSiteConfigPreferences().getAdminEmail()); xnatPipelineLauncher.setAlwaysEmailAdmin(ArcSpecManager.GetInstance().getEmailspecifications_pipeline()); xnatPipelineLauncher.setWaitFor(true); String pipelineName = "images/WebBasedQCImageCreator.xml"; @@ -53,9 +51,9 @@ public class QCImageCreator { xnatPipelineLauncher.setParameter("session", mrSession.getId() ); xnatPipelineLauncher.setParameter("notify", "0" ); xnatPipelineLauncher.setParameter("xnatserver", TurbineUtils.GetSystemName()); - xnatPipelineLauncher.setParameter("mailhost", AdminUtils.getMailServer()); + xnatPipelineLauncher.setParameter("mailhost", XDAT.getSiteConfigPreferences().getSmtpServer().get("host")); xnatPipelineLauncher.setParameter("useremail", user.getEmail()); - xnatPipelineLauncher.setParameter("adminemail", AdminUtils.getAdminEmailId()); + xnatPipelineLauncher.setParameter("adminemail", XDAT.getSiteConfigPreferences().getAdminEmail()); return xnatPipelineLauncher.launch(null); @@ -68,8 +66,7 @@ public class QCImageCreator { public static String GetPathToQCFile(XnatMrsessiondata mrSession, String mrScanId) { PlexiViewerSpecForSession viewerSpec = PlexiSpecDocReader.GetInstance().getSpecDoc(mrSession.getSessionType()); - String rtn = viewerSpec.getThumbnailArchiveLocation() + File.separator + mrSession.getId() +"_" + mrScanId + "_qc.gif"; - return rtn; + return viewerSpec.getThumbnailArchiveLocation() + File.separator + mrSession.getId() + "_" + mrScanId + "_qc.gif"; } @@ -79,18 +76,17 @@ public class QCImageCreator { public static String getQCThumbnailPathForSession(String project) { - String path = null; + String path; if (project!=null){ path= ArcSpecManager.GetInstance().getCachePathForProject(project); }else{ path= ArcSpecManager.GetInstance().getGlobalCachePath(); } - String thumb_path = path +"Thumbnail/"; - return thumb_path; + return path + "Thumbnail/"; } public static String getQCCachePathForSession(String project) { - String path = null; + String path; if (project!=null){ path= ArcSpecManager.GetInstance().getCachePathForProject(project); }else{ diff --git a/src/main/java/org/nrg/xapi/rest/settings/SiteConfigApi.java b/src/main/java/org/nrg/xapi/rest/settings/SiteConfigApi.java index 6c3ca05a8742c8588c6e7d9eb69496c13b95a192..fcdad8eba51bb7cb3d552a1987b8575e7f119271 100644 --- a/src/main/java/org/nrg/xapi/rest/settings/SiteConfigApi.java +++ b/src/main/java/org/nrg/xapi/rest/settings/SiteConfigApi.java @@ -21,11 +21,40 @@ import org.springframework.web.bind.annotation.RequestMethod; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Properties; +import java.util.jar.Attributes; +import java.util.jar.Manifest; @Api(description = "Site Configuration Management API") @XapiRestController @RequestMapping(value = "/siteConfig") public class SiteConfigApi extends AbstractXnatRestApi { + @ApiOperation(value = "Returns a map of application build properties.", notes = "This includes the implementation version, Git commit hash, and build number and number.", response = Properties.class) + @ApiResponses({@ApiResponse(code = 200, message = "Application build properties successfully retrieved."), @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), @ApiResponse(code = 500, message = "Unexpected error")}) + @RequestMapping(value = "buildInfo", produces = {MediaType.APPLICATION_JSON_VALUE}, method = {RequestMethod.GET}) + public ResponseEntity<Properties> getBuildInfo() { + if (_log.isDebugEnabled()) { + _log.debug("User " + getSessionUser().getUsername() + " requested the application build information."); + } + + if (_properties.size() == 0) { + final Attributes attributes = _manifest.getMainAttributes(); + _properties.setProperty("buildNumber", attributes.getValue("Build-Number")); + _properties.setProperty("buildDate", attributes.getValue("Build-Date")); + _properties.setProperty("version", attributes.getValue("Implementation-Version")); + _properties.setProperty("commit", attributes.getValue("Implementation-Sha")); + if (_log.isDebugEnabled()) { + _log.debug("Initialized application build information:\n * Version: {}\n * Build number: {}\n * Build Date: {}\n * Commit: {}", + _properties.getProperty("version"), + _properties.getProperty("buildNumber"), + _properties.getProperty("buildDate"), + _properties.getProperty("commit")); + } + } + + return new ResponseEntity<>(_properties, HttpStatus.OK); + } + @ApiOperation(value = "Returns the full map of site configuration properties.", notes = "Complex objects may be returned as encapsulated JSON strings.", response = SiteConfigPreferences.class) @ApiResponses({@ApiResponse(code = 200, message = "Site configuration properties successfully retrieved."), @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), @ApiResponse(code = 403, message = "Not authorized to set site configuration properties."), @ApiResponse(code = 500, message = "Unexpected error")}) @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE}, method = {RequestMethod.GET}) @@ -134,4 +163,10 @@ public class SiteConfigApi extends AbstractXnatRestApi { @Autowired @Lazy private SiteConfigPreferences _preferences; + + @Autowired + @Lazy + private Manifest _manifest; + + private Properties _properties = new Properties(); } diff --git a/src/main/java/org/nrg/xnat/ajax/GrantProjectAccess.java b/src/main/java/org/nrg/xnat/ajax/GrantProjectAccess.java index 43c0230eed9bd50b908ff3dd85fb89dd85396adc..38a16d323e25daa3b3452789bdd28251176ef865 100644 --- a/src/main/java/org/nrg/xnat/ajax/GrantProjectAccess.java +++ b/src/main/java/org/nrg/xnat/ajax/GrantProjectAccess.java @@ -55,7 +55,7 @@ public class GrantProjectAccess { context.put("process","Transfer to the archive."); context.put("system",TurbineUtils.GetSystemName()); context.put("access_level",level); - context.put("admin_email",AdminUtils.getAdminEmailId()); + context.put("admin_email",XDAT.getSiteConfigPreferences().getAdminEmail()); context.put("projectOM",project); //SEND email to user ProjectAccessRequest.InviteUser(context, email, user, user.getFirstname() + " " + user.getLastname() diff --git a/src/main/java/org/nrg/xnat/archive/BatchTransfer.java b/src/main/java/org/nrg/xnat/archive/BatchTransfer.java index c28f9d3f537d00368999d3b6b793b91c03690c77..d33c56380a5ba6ff6322ed3097aee7a8182139ce 100644 --- a/src/main/java/org/nrg/xnat/archive/BatchTransfer.java +++ b/src/main/java/org/nrg/xnat/archive/BatchTransfer.java @@ -409,8 +409,8 @@ public class BatchTransfer extends Thread{ } } - String[] to = new String[] { AdminUtils.getAdminEmailId(), user.getEmail() }; - String from = AdminUtils.getAdminEmailId(); + String[] to = new String[] { XDAT.getSiteConfigPreferences().getAdminEmail(), user.getEmail() }; + String from = XDAT.getSiteConfigPreferences().getAdminEmail(); String subject = system + " update: Archiving Complete."; if (errors.size()>0) subject += errors.size() + " errors"; diff --git a/src/main/java/org/nrg/xnat/archive/Transfer.java b/src/main/java/org/nrg/xnat/archive/Transfer.java index 88dcccd9277eca735f849d4d44b1dfe3a72189ca..7fc86549ec47919711018a3fbafc55e0c636faad 100644 --- a/src/main/java/org/nrg/xnat/archive/Transfer.java +++ b/src/main/java/org/nrg/xnat/archive/Transfer.java @@ -20,6 +20,7 @@ import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.nrg.pipeline.XnatPipelineLauncher; +import org.nrg.xdat.XDAT; import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.XFT; @@ -101,7 +102,7 @@ public class Transfer { XnatPipelineLauncher xnatPipelineLauncher = new XnatPipelineLauncher((UserI)user); // Modified by MR - 2010/03/11 AdminEmail is set in pipeline setup setup - // xnatPipelineLauncher.setAdmin_email(AdminUtils.getAdminEmailId()); + // xnatPipelineLauncher.setAdmin_email(XDAT.getSiteConfigPreferences().getAdminEmail()); //Modified bt MR - 2010/03/11 There is a setting for Site Admin to set email notification for Transfer pipeline // xnatPipelineLauncher.setAlwaysEmailAdmin(ArcSpecManager.GetInstance().getEmailspecifications_pipeline()); String pipelineName = "xnat_tools/Transfer.xml"; @@ -130,10 +131,10 @@ public class Transfer { xnatPipelineLauncher.setParameter("userfullname", XnatPipelineLauncher.getUserName(user)); xnatPipelineLauncher.setParameter("adminemail", admin_email); xnatPipelineLauncher.setParameter("xnatserver", system); - xnatPipelineLauncher.setParameter("mailhost", AdminUtils.getMailServer()); + xnatPipelineLauncher.setParameter("mailhost", XDAT.getSiteConfigPreferences().getSmtpServer().get("host")); xnatPipelineLauncher.setParameter("sessionType", mr.getXSIType()); xnatPipelineLauncher.setParameter("xnat_project", mr.getProject()); - xnatPipelineLauncher.setParameter("logDir", XFT.GetCachePath()+"logs" + "/" + "transfer" ); + xnatPipelineLauncher.setParameter("logDir", XDAT.getSiteConfigPreferences().getCachePath() + "logs" + "/" + "transfer"); // xnatPipelineLauncher.setParameter("notify","" +getNotifies()); xnatPipelineLauncher.setWaitFor(waitForTransfer); diff --git a/src/main/java/org/nrg/xnat/helpers/prearchive/PrearcDatabase.java b/src/main/java/org/nrg/xnat/helpers/prearchive/PrearcDatabase.java index 1941edcb19fe892701605e7cb800c7ab6caeb0c3..3e8b0f9124fafd14748f14380f31541b921b5ad8 100644 --- a/src/main/java/org/nrg/xnat/helpers/prearchive/PrearcDatabase.java +++ b/src/main/java/org/nrg/xnat/helpers/prearchive/PrearcDatabase.java @@ -17,6 +17,7 @@ import org.apache.commons.lang3.StringUtils; import org.nrg.action.ClientException; import org.nrg.automation.entities.Script; import org.nrg.automation.services.ScriptService; +import org.nrg.config.exceptions.ConfigServiceException; import org.nrg.dicomtools.filters.DicomFilterService; import org.nrg.dicomtools.filters.SeriesImportFilter; import org.nrg.framework.constants.PrearchiveCode; @@ -29,8 +30,9 @@ import org.nrg.xdat.bean.XnatPetmrsessiondataBean; import org.nrg.xdat.bean.XnatPetsessiondataBean; import org.nrg.xdat.model.XnatImagescandataI; import org.nrg.xdat.model.XnatPetscandataI; -import org.nrg.xdat.om.ArcArchivespecification; import org.nrg.xdat.om.XnatExperimentdata; +import org.nrg.xdat.preferences.InitializerSiteConfiguration; +import org.nrg.xdat.preferences.SiteConfigPreferences; import org.nrg.xft.db.PoolDBUtils; import org.nrg.xft.exception.DBPoolException; import org.nrg.xft.security.UserI; @@ -174,10 +176,14 @@ public final class PrearcDatabase { */ protected static String getPrearcPath() { - ArcArchivespecification arcSpec = ArcSpecManager.GetInstance(false); - if (arcSpec != null) { - return arcSpec.getGlobalPrearchivePath(); - } else { + final SiteConfigPreferences preferences = XDAT.getSiteConfigPreferences(); + if (preferences != null) { + return preferences.getPrearchivePath(); + } + try { + final Properties properties = XDAT.getSiteConfiguration(); + return properties.getProperty("prearchivePath"); + } catch (ConfigServiceException e) { return null; } } @@ -443,7 +449,7 @@ public final class PrearcDatabase { * @return The path to the project. */ static String projectPath(String project) { - return StringUtils.join(new String[]{PrearcDatabase.prearcPath, project}); + return Paths.get(PrearcDatabase.prearcPath, project).toString(); } /** diff --git a/src/main/java/org/nrg/xnat/initialization/RootConfig.java b/src/main/java/org/nrg/xnat/initialization/RootConfig.java index 3a539cafb3ea77258db674618b10c66535386799..cb878fda7262db9a5632e5340c8cf1bd3627cde1 100644 --- a/src/main/java/org/nrg/xnat/initialization/RootConfig.java +++ b/src/main/java/org/nrg/xnat/initialization/RootConfig.java @@ -24,9 +24,13 @@ import org.springframework.http.converter.json.MappingJackson2HttpMessageConvert import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; import org.springframework.oxm.jaxb.Jaxb2Marshaller; +import javax.servlet.ServletContext; import javax.xml.bind.Marshaller; +import java.io.IOException; +import java.io.InputStream; import java.util.HashMap; import java.util.Map; +import java.util.jar.Manifest; /** * Configuration for the XNAT root application context. This contains all of the basic infrastructure for initializing @@ -40,6 +44,13 @@ import java.util.Map; @Import({PropertiesConfig.class, DatabaseConfig.class}) @ImportResource("WEB-INF/conf/xnat-security.xml") public class RootConfig { + @Bean + public Manifest applicationManifest(final ServletContext context) throws IOException { + try (final InputStream input = context.getResourceAsStream("/META-INF/MANIFEST.MF")) { + return new Manifest(input); + } + } + @Bean public InitializerSiteConfiguration initializerSiteConfiguration() { return new InitializerSiteConfiguration(); diff --git a/src/main/java/org/nrg/xnat/notifications/NotifyProjectListeners.java b/src/main/java/org/nrg/xnat/notifications/NotifyProjectListeners.java index 9a5f0b30e2cb0ae4d4bcbc070ab69f6211ed3d6c..cc1f376143c5760dba72c72d1a3c105c84f1c6ac 100644 --- a/src/main/java/org/nrg/xnat/notifications/NotifyProjectListeners.java +++ b/src/main/java/org/nrg/xnat/notifications/NotifyProjectListeners.java @@ -83,13 +83,13 @@ public class NotifyProjectListeners implements Callable<Boolean> { Context context =new VelocityContext(_params); - String from = AdminUtils.getAdminEmailId(); + String from = XDAT.getSiteConfigPreferences().getAdminEmail(); context.put("user", _user); context.put("expt", _expt); context.put("username", _user.getUsername()); context.put("server", TurbineUtils.GetFullServerPath()); context.put("system", TurbineUtils.GetSystemName()); - context.put("admin_email", AdminUtils.getAdminEmailId()); + context.put("admin_email", XDAT.getSiteConfigPreferences().getAdminEmail()); context.put("params", _params); if(_params.get("justification")!=null){ context.put("justification",_params.get("justification")); diff --git a/src/main/java/org/nrg/xnat/notifications/NotifyProjectPipelineListeners.java b/src/main/java/org/nrg/xnat/notifications/NotifyProjectPipelineListeners.java index 621488d70c0a0cf8cf2d642b90b008ce7f0697a6..00ecd637de1f7f4eb4c7cb915e5d3b0713276981 100644 --- a/src/main/java/org/nrg/xnat/notifications/NotifyProjectPipelineListeners.java +++ b/src/main/java/org/nrg/xnat/notifications/NotifyProjectPipelineListeners.java @@ -75,21 +75,21 @@ public class NotifyProjectPipelineListeners extends NotifyProjectListeners { email.add(e); } } - if(!email.contains(AdminUtils.getAdminEmailId())){ - email.add(AdminUtils.getAdminEmailId()); + if(!email.contains(XDAT.getSiteConfigPreferences().getAdminEmail())){ + email.add(XDAT.getSiteConfigPreferences().getAdminEmail()); } if(email.size()>0){ Context context =new VelocityContext(Maps.newHashMap()); - String from = AdminUtils.getAdminEmailId(); + String from = XDAT.getSiteConfigPreferences().getAdminEmail(); context.put("user", _user); context.put("expt", _expt); context.put("username", _user.getUsername()); context.put("server", TurbineUtils.GetFullServerPath()); context.put("system", TurbineUtils.GetSystemName()); - context.put("admin_email", AdminUtils.getAdminEmailId()); + context.put("admin_email", XDAT.getSiteConfigPreferences().getAdminEmail()); context.put("workflow",_workflow); context.put("params", _params); for(Map.Entry<String,Object> entry : _params.entrySet()) { diff --git a/src/main/java/org/nrg/xnat/restlet/XNATApplication.java b/src/main/java/org/nrg/xnat/restlet/XNATApplication.java index 1bcbc4b25bf3fbaadf3d99377864e64df9f0e752..f297f018abf18274437323fc2866638744bde574 100755 --- a/src/main/java/org/nrg/xnat/restlet/XNATApplication.java +++ b/src/main/java/org/nrg/xnat/restlet/XNATApplication.java @@ -350,9 +350,6 @@ public class XNATApplication extends Application { "/automation/templates/{TEMPLATE_ID}", "/projects/{PROJECT_ID}/automation/templates", "/projects/{PROJECT_ID}/automation/templates/{TEMPLATE_ID}"); - attachURI(router, "/services/settings", SettingsRestlet.class); - attachURI(router, "/services/settings/{PROPERTY}", SettingsRestlet.class); - attachURI(router, "/services/settings/{PROPERTY}/{VALUE}", SettingsRestlet.class); attachURI(router, "/status/{TRANSACTION_ID}", SQListenerRepresentation.class); @@ -401,7 +398,7 @@ public class XNATApplication extends Application { if (clazz.isAnnotationPresent(XnatRestlet.class)) { XnatRestlet annotation = clazz.getAnnotation(XnatRestlet.class); final String[] urls = annotation.value(); - if (urls == null || urls.length == 0) { + if (urls.length == 0) { throw new RuntimeException("The restlet extension class " + clazz.getName() + " has no URLs configured."); } if (annotation.secure()) { @@ -418,7 +415,7 @@ public class XNATApplication extends Application { }else if (clazz.isAnnotationPresent(XnatRestlet2.class)) { XnatRestlet2 annotation = clazz.getAnnotation(XnatRestlet2.class); final XnatRestletURI[] urls = annotation.value(); - if (urls == null || urls.length == 0) { + if (urls.length == 0) { throw new RuntimeException("The restlet extension class " + clazz.getName() + " has no URLs configured."); } if (annotation.secure()) { @@ -445,7 +442,7 @@ public class XNATApplication extends Application { private void attachPath(Router router, Class<? extends Resource> clazz, XnatRestlet annotation) { String[] paths = annotation.value(); boolean required = annotation.required(); - if (paths == null || paths.length == 0) { + if (paths.length == 0) { String message = "You must specify a value for the XnatRestlet annotation to indicate the hosting path for the restlet extension in class: " + clazz.getName(); if (required) { throw new NrgServiceRuntimeException(message); @@ -462,7 +459,7 @@ public class XNATApplication extends Application { private void attachPath(Router router, Class<? extends Resource> clazz, XnatRestlet2 annotation) { XnatRestletURI[] paths = annotation.value(); boolean required = annotation.required(); - if (paths == null || paths.length == 0) { + if (paths.length == 0) { String message = "You must specify a value for the XnatRestlet annotation to indicate the hosting path for the restlet extension in class: " + clazz.getName(); if (required) { throw new NrgServiceRuntimeException(message); @@ -477,8 +474,6 @@ public class XNATApplication extends Application { } private void addPublicRoutes(final Router router, List<Class<? extends Resource>> publicRoutes) { - attachURI(router, "/version", VersionRepresentation.class); - if (publicRoutes == null) { return; } diff --git a/src/main/java/org/nrg/xnat/restlet/actions/TriggerPipelines.java b/src/main/java/org/nrg/xnat/restlet/actions/TriggerPipelines.java index 4b58b4703da744f5f5c43e0a0eb0ccce081ea0c8..e0d04488f34e8e374dff1be4f69eafde8ec883d2 100644 --- a/src/main/java/org/nrg/xnat/restlet/actions/TriggerPipelines.java +++ b/src/main/java/org/nrg/xnat/restlet/actions/TriggerPipelines.java @@ -10,24 +10,23 @@ */ package org.nrg.xnat.restlet.actions; -import java.util.concurrent.Callable; - import org.apache.log4j.Logger; import org.nrg.pipeline.XnatPipelineLauncher; +import org.nrg.xdat.XDAT; import org.nrg.xdat.om.XnatExperimentdata; -import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.util.XNATRestConstants; import org.nrg.xnat.turbine.utils.ArcSpecManager; +import java.util.concurrent.Callable; + /** * @author Timothy R. Olsen <olsent@wustl.edu> * */ public class TriggerPipelines implements Callable<Boolean> { - static Logger logger = Logger.getLogger(TriggerPipelines.class); private static final String XNAT_TOOLS_AUTO_RUN_XML = "xnat_tools/AutoRun.xml"; private final XnatExperimentdata expt; @@ -48,7 +47,7 @@ public class TriggerPipelines implements Callable<Boolean> { public Boolean call() { XnatPipelineLauncher xnatPipelineLauncher = new XnatPipelineLauncher(user); - xnatPipelineLauncher.setAdmin_email(AdminUtils.getAdminEmailId()); + xnatPipelineLauncher.setAdmin_email(XDAT.getSiteConfigPreferences().getAdminEmail()); xnatPipelineLauncher.setAlwaysEmailAdmin(ArcSpecManager.GetInstance().getEmailspecifications_pipeline()); String pipelineName = XNAT_TOOLS_AUTO_RUN_XML; xnatPipelineLauncher.setPipelineName(pipelineName); @@ -59,14 +58,14 @@ public class TriggerPipelines implements Callable<Boolean> { xnatPipelineLauncher.setDataType(expt.getXSIType()); xnatPipelineLauncher.setExternalId(expt.getProject()); xnatPipelineLauncher.setWaitFor(this.waitFor); - xnatPipelineLauncher.setParameter(XNATRestConstants.SUPRESS_EMAIL, (new Boolean(supressEmail)).toString()); + xnatPipelineLauncher.setParameter(XNATRestConstants.SUPRESS_EMAIL, (Boolean.valueOf(supressEmail)).toString()); xnatPipelineLauncher.setParameter("session", expt.getId()); xnatPipelineLauncher.setParameter("sessionLabel", expt.getLabel()); xnatPipelineLauncher.setParameter("useremail", user.getEmail()); xnatPipelineLauncher.setParameter("userfullname", XnatPipelineLauncher.getUserName(user)); - xnatPipelineLauncher.setParameter("adminemail", AdminUtils.getAdminEmailId()); + xnatPipelineLauncher.setParameter("adminemail", XDAT.getSiteConfigPreferences().getAdminEmail()); xnatPipelineLauncher.setParameter("xnatserver", TurbineUtils.GetSystemName()); - xnatPipelineLauncher.setParameter("mailhost", AdminUtils.getMailServer()); + xnatPipelineLauncher.setParameter("mailhost", XDAT.getSiteConfigPreferences().getSmtpServer().get("host")); xnatPipelineLauncher.setParameter("sessionType", expt.getXSIType()); xnatPipelineLauncher.setParameter("xnat_project", expt.getProject()); diff --git a/src/main/java/org/nrg/xnat/restlet/extensions/AuthenticationRestlet.java b/src/main/java/org/nrg/xnat/restlet/extensions/AuthenticationRestlet.java index cbd2dada77272f247ad4419a2e19cc80404195f6..b7f938051b9359e8e826f92eedb8486b1663e448 100644 --- a/src/main/java/org/nrg/xnat/restlet/extensions/AuthenticationRestlet.java +++ b/src/main/java/org/nrg/xnat/restlet/extensions/AuthenticationRestlet.java @@ -14,7 +14,6 @@ import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nrg.xdat.XDAT; -import org.nrg.xft.XFT; import org.nrg.xnat.restlet.XnatRestlet; import org.nrg.xnat.security.XnatProviderManager; import org.restlet.Context; @@ -76,7 +75,7 @@ public class AuthenticationRestlet extends Resource { _log.debug("Passing a representation of the verify extensions restlet."); } - if (XFT.GetRequireLogin() && (StringUtils.isBlank(_username) || StringUtils.isBlank(_password))) { + if (XDAT.getSiteConfigPreferences().getRequireLogin() && (StringUtils.isBlank(_username) || StringUtils.isBlank(_password))) { fail(); return; } diff --git a/src/main/java/org/nrg/xnat/restlet/guard/XnatSecureGuard.java b/src/main/java/org/nrg/xnat/restlet/guard/XnatSecureGuard.java index 6ca69473a091f45a35c29e331ed882b1328910f7..ea38961e584bb21f4d09d90e623e87ceac47b279 100644 --- a/src/main/java/org/nrg/xnat/restlet/guard/XnatSecureGuard.java +++ b/src/main/java/org/nrg/xnat/restlet/guard/XnatSecureGuard.java @@ -17,7 +17,6 @@ import org.nrg.xdat.security.Authenticator; import org.nrg.xdat.security.helpers.Users; import org.nrg.xdat.services.AliasTokenService; import org.nrg.xdat.turbine.modules.actions.SecureAction; -import org.nrg.xft.XFT; import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.representations.RESTLoginRepresentation; import org.nrg.xnat.restlet.util.BrowserDetector; @@ -114,7 +113,7 @@ public class XnatSecureGuard extends Filter { return true; } } - else if (!XFT.GetRequireLogin()) { + else if (!XDAT.getSiteConfigPreferences().getRequireLogin()) { try { HttpSession session = httpRequest.getSession(); session.removeAttribute("loggedin"); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProjectAccessibilityResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ProjectAccessibilityResource.java index 3c698e68b6b615c169aefdf095543d7d8ba5e9b3..723063c17d47d0aa80ac47341eeddbd68856ded0 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectAccessibilityResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectAccessibilityResource.java @@ -74,19 +74,7 @@ public class ProjectAccessibilityResource extends SecureResource { WorkflowUtils.complete(wrk, c); } } - - getResponse().setEntity(getRepresentation(getVariants().get(0))); - Representation selectedRepresentation = getResponse().getEntity(); - if (getRequest().getConditions().hasSome()) { - final Status status = getRequest().getConditions() - .getStatus(getRequest().getMethod(), - selectedRepresentation); - - if (status != null) { - getResponse().setStatus(status); - getResponse().setEntity(null); - } - } + returnDefaultRepresentation(); } catch (Exception e) { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProjectGroupResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ProjectGroupResource.java index 87a625ec3ce5d54b2ceedb2d8a7d3d19ba8a9553..ac0b747a2cfb22ff704a3a3f621bff01595ab2e4 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectGroupResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectGroupResource.java @@ -8,6 +8,7 @@ import java.util.Map; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; +import org.nrg.xdat.XDAT; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.security.ElementSecurity; import org.nrg.xdat.security.PermissionCriteria; @@ -261,7 +262,7 @@ public class ProjectGroupResource extends SecureResource { if(props.containsKey("src")){ this.getResponse().setStatus(Status.REDIRECTION_SEE_OTHER); - this.getResponse().redirectSeeOther(XFT.GetSiteURL()+"/data/projects/"+group.getTag() + "?format=html"); + this.getResponse().redirectSeeOther(XDAT.getSiteConfigPreferences().getSiteUrl() + "/data/projects/" + group.getTag() + "?format=html"); }else{ returnDefaultRepresentation(); } @@ -279,7 +280,7 @@ public class ProjectGroupResource extends SecureResource { @Override - public Representation getRepresentation(Variant variant) { + public Representation represent(Variant variant) { XFTTable table=null; if(proj!=null){ if(group==null){ diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProjectListResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ProjectListResource.java index 59122f5ca4649e27bd1096c5d90c8c3addea2f2a..17390dca051d666c6407ddb36357f83925d68563 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectListResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectListResource.java @@ -14,6 +14,7 @@ import com.google.common.base.Joiner; import com.google.common.collect.Lists; import org.apache.commons.lang3.StringUtils; import org.nrg.action.ActionException; +import org.nrg.xdat.XDAT; import org.nrg.xdat.om.XdatStoredSearch; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.om.base.BaseXnatProjectdata; @@ -25,7 +26,6 @@ import org.nrg.xdat.security.helpers.Permissions; import org.nrg.xdat.security.helpers.Roles; import org.nrg.xdat.security.helpers.UserHelper; import org.nrg.xdat.security.services.UserHelperServiceI; -import org.nrg.xft.XFT; import org.nrg.xft.XFTItem; import org.nrg.xft.XFTTable; import org.nrg.xft.db.ViewManager; @@ -56,7 +56,6 @@ public class ProjectListResource extends QueryOrganizerResource { private static final String DATA_READABLE = "readable"; private static final String DATA_WRITABLE = "writable"; private static final List<String> PERMISSIONS = Arrays.asList(SecurityManager.ACTIVATE, SecurityManager.CREATE, SecurityManager.DELETE, SecurityManager.EDIT, SecurityManager.READ); - private XFTTable table = null; public ProjectListResource(Context context, Request request, Response response) { super(context, request, response); @@ -111,7 +110,7 @@ public class ProjectListResource extends QueryOrganizerResource { } if (item.getCurrentDBVersion() == null) { - if (XFT.getBooleanProperty("UI.allow-non-admin-project-creation", true) || Roles.isSiteAdmin(user)) { + if (XDAT.getSiteConfigPreferences().getUiAllowNonAdminProjectCreation() || Roles.isSiteAdmin(user)) { this.returnSuccessfulCreateFromList(BaseXnatProjectdata.createProject(project, user, allowDataDeletion, false, newEventInstance(EventUtils.CATEGORY.PROJECT_ADMIN), getQueryVariable("accessibility"))); } else { this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, "User account doesn't have permission to edit this project."); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProjectMemberResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ProjectMemberResource.java index 6bdefecc7d4ed731d33e4fbb9f7e34f4cd4a24c9..3292ce80832b1ec697418a8d851a2067503f282c 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectMemberResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectMemberResource.java @@ -14,13 +14,14 @@ import com.noelios.restlet.ext.servlet.ServletCall; import org.apache.commons.lang3.StringUtils; import org.apache.velocity.VelocityContext; import org.nrg.action.ActionException; +import org.nrg.xdat.XDAT; import org.nrg.xdat.display.DisplayManager; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.security.UserGroupI; import org.nrg.xdat.security.helpers.Groups; import org.nrg.xdat.security.helpers.Permissions; import org.nrg.xdat.security.helpers.Users; -import org.nrg.xdat.turbine.utils.AdminUtils; +import org.nrg.xdat.security.user.exceptions.UserNotFoundException; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.XFTTable; import org.nrg.xft.event.EventMetaI; @@ -49,8 +50,8 @@ import java.util.List; public class ProjectMemberResource extends SecureResource { XnatProjectdata proj=null; UserGroupI group=null; - ArrayList<UserI> newUsers= new ArrayList<UserI>(); - ArrayList<String> unknown= new ArrayList<String>(); + ArrayList<UserI> newUsers= new ArrayList<>(); + ArrayList<String> unknown= new ArrayList<>(); String gID=null; boolean displayHiddenUsers = false; @@ -61,12 +62,12 @@ public class ProjectMemberResource extends SecureResource { this.getVariants().add(new Variant(MediaType.TEXT_HTML)); this.getVariants().add(new Variant(MediaType.TEXT_XML)); - String pID= (String)getUrlEncodedParameter(request,"PROJECT_ID"); + String pID= getUrlEncodedParameter(request, "PROJECT_ID"); if(pID!=null){ proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); } - gID =(String)getUrlEncodedParameter(request,"GROUP_ID"); + gID = getUrlEncodedParameter(request, "GROUP_ID"); group=Groups.getGroup(gID); @@ -90,44 +91,44 @@ public class ProjectMemberResource extends SecureResource { String tempValue =(String)getParameter(request,"USER_ID"); try { - String[] ids=null; - if(tempValue.indexOf(",")>-1){ + String[] ids; + if(tempValue.contains(",")){ ids=tempValue.split(","); }else{ ids=new String[]{tempValue}; } - - for(int i=0;i<ids.length;i++){ - String uID=ids[i].trim(); - Integer xdat_user_id= null; + + for (final String id : ids) { + String uID = id.trim(); + Integer xdat_user_id = null; try { - xdat_user_id=Integer.parseInt(uID); - } catch (NumberFormatException e) { - + xdat_user_id = Integer.parseInt(uID); + } catch (NumberFormatException ignored) { + } - - - if (xdat_user_id==null){ + + + if (xdat_user_id == null) { //login or email - UserI newUser=null; + UserI newUser = null; try { newUser = Users.getUser(uID); - } catch (Exception e) { + } catch (UserNotFoundException ignored) { } - if (newUser==null){ + if (newUser == null) { //by email - List<UserI> items =Users.getUsersByEmail(uID); - if(items.size()>0){ + List<UserI> items = Users.getUsersByEmail(uID); + if (items.size() > 0) { newUsers.addAll(items); - }else{ + } else { unknown.add(uID); } - }else{ + } else { newUsers.add(newUser); } - }else{ + } else { UserI tempUser = Users.getUser(xdat_user_id); - if (tempUser!=null){ + if (tempUser != null) { newUsers.add(tempUser); } } @@ -167,9 +168,6 @@ public class ProjectMemberResource extends SecureResource { }else{ getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); } - } catch (InvalidItemException e) { - logger.error("",e); - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } catch (Exception e) { logger.error("",e); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); @@ -196,7 +194,7 @@ public class ProjectMemberResource extends SecureResource { context.put("process","Transfer to the archive."); context.put("system",TurbineUtils.GetSystemName()); context.put("access_level",gID); - context.put("admin_email",AdminUtils.getAdminEmailId()); + context.put("admin_email",XDAT.getSiteConfigPreferences().getAdminEmail()); context.put("projectOM",proj); //SEND email to user final PersistentWorkflowI wrk=PersistentWorkflowUtils.getOrCreateWorkflowData(null, user, XnatProjectdata.SCHEMA_ELEMENT_NAME, proj.getId(), proj.getId(), newEventInstance(EventUtils.CATEGORY.PROJECT_ACCESS, EventUtils.INVITE_USER_TO_PROJECT + " (" + uID + ")")); @@ -224,31 +222,27 @@ public class ProjectMemberResource extends SecureResource { for(UserI newUser: newUsers){ final PersistentWorkflowI wrk=PersistentWorkflowUtils.getOrCreateWorkflowData(null, user, Users.getUserDataType(),newUser.getID().toString(),proj.getId(),newEventInstance(EventUtils.CATEGORY.PROJECT_ACCESS, EventUtils.ADD_USER_TO_PROJECT)); EventMetaI c=wrk.buildEvent(); - - try { - proj.addGroupMember(group.getId(), newUser, user,WorkflowUtils.setStep(wrk, "Add " + newUser.getLogin())); - WorkflowUtils.complete(wrk, c); - - if (sendmail){ - try { - VelocityContext context = new VelocityContext(); - - context.put("user",user); - context.put("server",TurbineUtils.GetFullServerPath(request)); - context.put("process","Transfer to the archive."); - context.put("system",TurbineUtils.GetSystemName()); - context.put("access_level","member"); - context.put("admin_email",AdminUtils.getAdminEmailId()); - context.put("projectOM",proj); - org.nrg.xnat.turbine.modules.actions.ProcessAccessRequest.SendAccessApprovalEmail(context, newUser.getEmail(), user, TurbineUtils.GetSystemName() + " Access Granted for " + proj.getName()); - } catch (Throwable e) { - logger.error("",e); - } - } - } catch (Exception e) { - throw e; - } - } + + proj.addGroupMember(group.getId(), newUser, user,WorkflowUtils.setStep(wrk, "Add " + newUser.getLogin())); + WorkflowUtils.complete(wrk, c); + + if (sendmail){ + try { + VelocityContext context = new VelocityContext(); + + context.put("user",user); + context.put("server",TurbineUtils.GetFullServerPath(request)); + context.put("process","Transfer to the archive."); + context.put("system",TurbineUtils.GetSystemName()); + context.put("access_level","member"); + context.put("admin_email", XDAT.getSiteConfigPreferences().getAdminEmail()); + context.put("projectOM",proj); + org.nrg.xnat.turbine.modules.actions.ProcessAccessRequest.SendAccessApprovalEmail(context, newUser.getEmail(), user, TurbineUtils.GetSystemName() + " Access Granted for " + proj.getName()); + } catch (Throwable e) { + logger.error("",e); + } + } + } } }else{ getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); @@ -268,26 +262,23 @@ public class ProjectMemberResource extends SecureResource { } @Override - public Representation getRepresentation(Variant variant) { + public Representation represent(Variant variant) { XFTTable table=null; if(proj!=null){ try { - StringBuffer query = new StringBuffer("SELECT g.id AS \"GROUP_ID\", displayname,login,firstname,lastname,email FROM xdat_userGroup g RIGHT JOIN xdat_user_Groupid map ON g.id=map.groupid RIGHT JOIN xdat_user u ON map.groups_groupid_xdat_user_xdat_user_id=u.xdat_user_id WHERE tag='").append(proj.getId()).append("' "); + StringBuilder query = new StringBuilder("SELECT g.id AS \"GROUP_ID\", displayname,login,firstname,lastname,email FROM xdat_userGroup g RIGHT JOIN xdat_user_Groupid map ON g.id=map.groupid RIGHT JOIN xdat_user u ON map.groups_groupid_xdat_user_xdat_user_id=u.xdat_user_id WHERE tag='").append(proj.getId()).append("' "); if(!displayHiddenUsers){ query.append(" and enabled = 1 "); } query.append(" ORDER BY g.id DESC;"); table = XFTTable.Execute(query.toString(), user.getDBName(), user.getLogin()); - } catch (SQLException e) { - logger.error("",e); - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } catch (DBPoolException e) { + } catch (SQLException | DBPoolException e) { logger.error("",e); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } } - Hashtable<String,Object> params=new Hashtable<String,Object>(); + Hashtable<String,Object> params=new Hashtable<>(); params.put("title", "Projects"); MediaType mt = overrideVariant(variant); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProjectPipelineListResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ProjectPipelineListResource.java index d39440c5619a0955326a55f8cc2991b89697e070..648d4e2160dbfe6bf34ef8f660885d3b8120d628 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectPipelineListResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectPipelineListResource.java @@ -13,6 +13,7 @@ package org.nrg.xnat.restlet.resources; import org.nrg.pipeline.PipelineRepositoryManager; import org.nrg.xdat.om.ArcProject; +import org.nrg.xdat.om.PipePipelinerepository; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.security.helpers.Permissions; import org.nrg.xft.XFTTable; @@ -58,111 +59,87 @@ public class ProjectPipelineListResource extends SecureResource { if (proj != null) { String pathToPipeline = null; String datatype = null; - pathToPipeline = this.getQueryVariable("path"); - datatype = this.getQueryVariable("datatype"); - if (pathToPipeline != null && datatype != null) { - pathToPipeline = pathToPipeline.trim(); - datatype=datatype.trim(); - boolean isUserAuthorized = isUserAuthorized(); - if (isUserAuthorized) { - try { + pathToPipeline = this.getQueryVariable("path"); + datatype = this.getQueryVariable("datatype"); + if (pathToPipeline != null && datatype != null) { + pathToPipeline = pathToPipeline.trim(); + datatype = datatype.trim(); + + boolean isUserAuthorized = false; + try { + isUserAuthorized = Permissions.canDelete(user, proj); + } catch (Exception e) { + e.printStackTrace(); + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, "Encountered exception " + e.getMessage()); + return; + } + + if (isUserAuthorized) { + try { ArcProject arcProject = ArcSpecManager.GetFreshInstance().getProjectArc(proj.getId()); boolean success = PipelineRepositoryManager.GetInstance().delete(arcProject, pathToPipeline, datatype, user); if (!success) { getLogger().log(getLogger().getLevel(), "Couldnt delete the pipeline " + pathToPipeline + " for the project " + proj.getId()); - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, " Couldnt succesfully save Project Specification" ); + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, " Couldn't successfully save Project Specification"); return; - }else { + } else { ArcSpecManager.Reset(); - getResponse().setEntity(getRepresentation(getVariants().get(0))); - Representation selectedRepresentation = getResponse().getEntity(); - if (getRequest().getConditions().hasSome()) { - final Status status = getRequest().getConditions() - .getStatus(getRequest().getMethod(), - selectedRepresentation); - - if (status != null) { - getResponse().setStatus(status); - getResponse().setEntity(null); - } - } + returnDefaultRepresentation(); //Send a 200 OK message back //getResponse().setStatus(Status.SUCCESS_OK,"Pipeline has been removed from project " + _project.getId()); } - }catch(Exception e) { - e.printStackTrace(); - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, "Encountered exception " + e.getMessage()); - } - }else { - getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, "User unauthroized to remove pipeline from project"); + } catch (Exception e) { + e.printStackTrace(); + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, "Encountered exception " + e.getMessage()); } + } else { + getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, "User unauthorized to remove pipeline from project"); } - }else { + } else { getResponse().setStatus(Status.CLIENT_ERROR_EXPECTATION_FAILED, "Expecting path and datatype as query parameters"); } - } - - - - - private boolean isUserAuthorized() { - boolean isUserAuthorized = false; - try { - isUserAuthorized = Permissions.canDelete(user,proj); - }catch(Exception e) { - e.printStackTrace(); - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } - return isUserAuthorized; } @Override public Representation getRepresentation(Variant variant) { - //Document xmldoc = null; - boolean isUserAuthorized = isUserAuthorized(); - ArcProject arcProject = ArcSpecManager.GetFreshInstance().getProjectArc(proj.getId()); - String comment = "existing"; + boolean isUserAuthorized; + try { + isUserAuthorized = Permissions.canRead(user, proj); + } catch (Exception e) { + e.printStackTrace(); + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, "Encountered exception " + e.getMessage()); + return null; + } if (isUserAuthorized) { - boolean additional=this.isQueryVariableTrue("additional"); - - //Check to see if the Project already has an entry in the ArcSpec. - //If yes, then return that entry. If not then construct a new ArcProject element and insert an attribute to say that it's an already existing - //entry or not - try { - if (arcProject == null) { // No Project pipelines set in the archive specification - if (additional) { - arcProject = PipelineRepositoryManager.GetInstance().createNewArcProject(proj); - comment = "new"; - }else { - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, "No archive spec entry for project " + proj.getId()); - } - }else { - if (additional) { //Return all the pipelines that are applicable to the project but not selected - arcProject = PipelineRepositoryManager.GetInstance().getAdditionalPipelines(proj); - comment = "additional"; - }else { - //XFTItem hack = arcProject.getCurrentDBVersion(true); - //arcProject.setItem(hack); - } - } - //xmldoc = arcProject.toXML(); - //Comment commentNode = xmldoc.createComment(comment); - //xmldoc.appendChild(commentNode); - }catch(Exception e) { - e.printStackTrace(); - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } - MediaType mt = overrideVariant(variant); - if (mt.equals(MediaType.TEXT_XML)) { - return representItem(arcProject.getItem(), mt, null,false, true); - }else if (mt.equals(MediaType.APPLICATION_JSON)) { - XFTTable table = PipelineRepositoryManager.GetInstance().toTable(arcProject); - - return representTable(table, mt,null); - }else { - return null; + ArcProject arcProject = ArcSpecManager.GetFreshInstance().getProjectArc(proj.getId()); + boolean additional = this.isQueryVariableTrue("additional"); + + //Check to see if the Project already has an entry in the ArcSpec. + //If yes, then return that entry. If not then construct a new ArcProject element and insert an attribute to say that it's an already existing + //entry or not + try { + if (additional) { + PipePipelinerepository repository = PipelineRepositoryManager.GetInstance(); + arcProject = arcProject == null ? repository.createNewArcProject(proj) : repository.getAdditionalPipelines(proj); + } else { + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, "No archive spec entry for project " + proj.getId()); } - }else { + } catch(Exception e) { + e.printStackTrace(); + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); + } + MediaType mt = overrideVariant(variant); + if (mt.equals(MediaType.TEXT_XML)) { + return representItem(arcProject.getItem(), mt, null, false, true); + } else if (mt.equals(MediaType.APPLICATION_JSON)) { + XFTTable table = PipelineRepositoryManager.GetInstance().toTable(arcProject); + + return representTable(table, mt,null); + } else { + return null; + } + } else { getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); } return null; diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProjectResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ProjectResource.java index 285997498b1aa4f2d12b7884f5b169fcf23e3aac..a819f9fca0d2d4ded17fb690f2d6d47a8c66c959 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectResource.java @@ -19,7 +19,6 @@ import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.om.base.BaseXnatProjectdata; import org.nrg.xdat.security.helpers.Permissions; import org.nrg.xdat.security.helpers.Roles; -import org.nrg.xft.XFT; import org.nrg.xft.XFTItem; import org.nrg.xft.db.PoolDBUtils; import org.nrg.xft.event.EventMetaI; @@ -179,10 +178,10 @@ public class ProjectResource extends ItemResource { } catch (NumberFormatException e) { switch (qc) { case "true": - ap.setQuarantineCode(new Integer(1)); + ap.setQuarantineCode(1); break; case "false": - ap.setQuarantineCode(new Integer(0)); + ap.setQuarantineCode(0); break; default: getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Prearchive code must be an integer."); @@ -204,10 +203,10 @@ public class ProjectResource extends ItemResource { } catch (NumberFormatException e) { switch (qc) { case "true": - ap.setPrearchiveCode(new Integer(1)); + ap.setPrearchiveCode(1); break; case "false": - ap.setPrearchiveCode(new Integer(0)); + ap.setPrearchiveCode(0); break; default: getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Prearchive code must be an integer."); @@ -267,7 +266,7 @@ public class ProjectResource extends ItemResource { } } - if (XFT.getBooleanProperty("UI.allow-non-admin-project-creation", true) || Roles.isSiteAdmin(user)) { + if (XDAT.getSiteConfigPreferences().getUiAllowNonAdminProjectCreation() || Roles.isSiteAdmin(user)) { project.preSave(); BaseXnatProjectdata.createProject(project, user, allowDataDeletion, true, newEventInstance(EventUtils.CATEGORY.PROJECT_ADMIN), getQueryVariable("accessibility")); } else { diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProjtExptPipelineResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ProjtExptPipelineResource.java index f82bb483fa8daa66ce538349502ae605425c888d..7ebc5b72a3344a70966ca45f7a217eb7dc36168c 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjtExptPipelineResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjtExptPipelineResource.java @@ -11,14 +11,6 @@ package org.nrg.xnat.restlet.resources; -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.commons.lang3.StringUtils; import org.apache.xmlbeans.XmlOptions; import org.nrg.pipeline.XnatPipelineLauncher; @@ -27,15 +19,11 @@ import org.nrg.pipeline.xmlbeans.ParameterData; import org.nrg.pipeline.xmlbeans.ParameterData.Values; import org.nrg.pipeline.xmlbeans.ParametersDocument; import org.nrg.pipeline.xmlbeans.ParametersDocument.Parameters; +import org.nrg.xdat.XDAT; import org.nrg.xdat.model.ArcPipelinedataI; import org.nrg.xdat.model.ArcPipelineparameterdataI; -import org.nrg.xdat.om.ArcPipelinedata; -import org.nrg.xdat.om.ArcProject; -import org.nrg.xdat.om.XnatExperimentdata; -import org.nrg.xdat.om.XnatImagesessiondata; -import org.nrg.xdat.om.XnatProjectdata; +import org.nrg.xdat.om.*; import org.nrg.xdat.security.helpers.Permissions; -import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.XFTItem; import org.nrg.xft.event.EventMetaI; @@ -58,6 +46,10 @@ import org.restlet.resource.Representation; import org.restlet.resource.Variant; import org.xml.sax.SAXException; +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.*; + public class ProjtExptPipelineResource extends SecureResource { XnatProjectdata proj=null; XnatExperimentdata expt=null; @@ -282,9 +274,9 @@ public class ProjtExptPipelineResource extends SecureResource { hasParams.add("useremail"); xnatPipelineLauncher.setParameter("userfullname", XnatPipelineLauncher.getUserName(user)); hasParams.add("userfullname"); - xnatPipelineLauncher.setParameter("adminemail", AdminUtils.getAdminEmailId()); + xnatPipelineLauncher.setParameter("adminemail", XDAT.getSiteConfigPreferences().getAdminEmail()); hasParams.add("adminemail"); - xnatPipelineLauncher.setParameter("mailhost", AdminUtils.getMailServer()); + xnatPipelineLauncher.setParameter("mailhost", XDAT.getSiteConfigPreferences().getSmtpServer().get("host")); hasParams.add("mailhost"); xnatPipelineLauncher.setParameter("xnatserver", TurbineUtils.GetSystemName()); hasParams.add("xnatserver"); @@ -396,8 +388,8 @@ public class ProjtExptPipelineResource extends SecureResource { xnatPipelineLauncher.setSupressNotification(true); xnatPipelineLauncher.setParameter("useremail", user.getEmail()); xnatPipelineLauncher.setParameter("userfullname", XnatPipelineLauncher.getUserName(user)); - xnatPipelineLauncher.setParameter("adminemail", AdminUtils.getAdminEmailId()); - xnatPipelineLauncher.setParameter("mailhost", AdminUtils.getMailServer()); + xnatPipelineLauncher.setParameter("adminemail", XDAT.getSiteConfigPreferences().getAdminEmail()); + xnatPipelineLauncher.setParameter("mailhost", XDAT.getSiteConfigPreferences().getSmtpServer().get("host")); xnatPipelineLauncher.setParameter("xnatserver", TurbineUtils.GetSystemName()); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/SecureResource.java b/src/main/java/org/nrg/xnat/restlet/resources/SecureResource.java index d83c4ee370ccf78e620a3a79d68b74b968826b66..b4980f643d507d2b30d91c18aa6f4faa27344b50 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/SecureResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/SecureResource.java @@ -151,7 +151,7 @@ public abstract class SecureResource extends Resource { // expects that the user exists in the session (either via traditional // session or set via the XnatSecureGuard user = XDAT.getUserDetails(); - if(user==null && !XFT.GetRequireLogin()){ + if(user==null && !XDAT.getSiteConfigPreferences().getRequireLogin()){ try { user = Users.getGuest(); XDAT.setUserDetails(user); @@ -510,8 +510,8 @@ public abstract class SecureResource extends Resource { return getRequest().getResourceRef().getPath(); } - public void returnDefaultRepresentation() { - getResponse().setEntity(getRepresentation(getVariants().get(0))); + public void returnRepresentation(Representation representation) { + getResponse().setEntity(representation); Representation selectedRepresentation = getResponse().getEntity(); if (getRequest().getConditions().hasSome()) { final Status status = getRequest().getConditions().getStatus(getRequest().getMethod(), selectedRepresentation); @@ -523,6 +523,10 @@ public abstract class SecureResource extends Resource { } } + public void returnDefaultRepresentation() { + returnRepresentation(getRepresentation(getVariants().get(0))); + } + public Representation representItem(XFTItem item, MediaType mt, Hashtable<String, Object> metaFields, boolean allowDBAccess, boolean allowSchemaLocation) { if (item != null) { if (mt.equals(MediaType.TEXT_XML)) { @@ -635,7 +639,7 @@ public abstract class SecureResource extends Resource { public FileRepresentation representFile(File f, MediaType mt) { mt = buildMediaType(mt, f.getName()); - if (mt.getName().startsWith("APPLICATION") || !XFT.getBooleanProperty("security.allow-HTML-resource-rendering", true)) { + if (mt.getName().startsWith("APPLICATION") || !XDAT.getSiteConfigPreferences().getAllowHtmlResourceRendering()) { setContentDisposition(f.getName()); } @@ -901,16 +905,7 @@ public abstract class SecureResource extends Resource { targetRef = targetRef.substring(0, targetRef.indexOf("?")); } - getResponse().setEntity(new StringRepresentation(targetRef)); - Representation selectedRepresentation = getResponse().getEntity(); - if (getRequest().getConditions().hasSome()) { - final Status status = getRequest().getConditions().getStatus(getRequest().getMethod(), selectedRepresentation); - - if (status != null) { - getResponse().setStatus(status); - getResponse().setEntity(null); - } - } + returnRepresentation(new StringRepresentation(targetRef)); } public void returnString(String message, Status status) { @@ -927,16 +922,7 @@ public abstract class SecureResource extends Resource { } public void returnXML(XFTItem item) { - getResponse().setEntity(representItem(item, MediaType.TEXT_XML)); - Representation selectedRepresentation = getResponse().getEntity(); - if (getRequest().getConditions().hasSome()) { - final Status status = getRequest().getConditions().getStatus(getRequest().getMethod(), selectedRepresentation); - - if (status != null) { - getResponse().setStatus(status); - getResponse().setEntity(null); - } - } + returnRepresentation(representItem(item, MediaType.TEXT_XML)); } protected void setResponseHeader(String key, String value) { diff --git a/src/main/java/org/nrg/xnat/restlet/resources/VersionRepresentation.java b/src/main/java/org/nrg/xnat/restlet/resources/VersionRepresentation.java deleted file mode 100644 index 253558813c74c09748fecb16a0138c2d028f4bea..0000000000000000000000000000000000000000 --- a/src/main/java/org/nrg/xnat/restlet/resources/VersionRepresentation.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * org.nrg.xnat.restlet.resources.VersionRepresentation - * 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.xnat.restlet.resources; - -import org.nrg.xnat.utils.FileUtils; -import org.restlet.Context; -import org.restlet.data.MediaType; -import org.restlet.data.Request; -import org.restlet.data.Response; -import org.restlet.resource.Representation; -import org.restlet.resource.Resource; -import org.restlet.resource.StringRepresentation; -import org.restlet.resource.Variant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; - -public class VersionRepresentation extends Resource { - private final Logger logger = LoggerFactory.getLogger(VersionRepresentation.class); - - public VersionRepresentation(Context context, Request request, Response response) { - super(context, request, response); - this.getVariants().add(new Variant(MediaType.ALL)); - } - - @Override - public Representation represent(Variant variant) { - if (logger.isDebugEnabled()) { - logger.debug("Getting XNAT version from the default configuration folder"); - } - try { - return new StringRepresentation(FileUtils.getXNATVersion()); - } catch (IOException exception) { - return new StringRepresentation("[Error: check system logs]"); - } - } -} diff --git a/src/main/java/org/nrg/xnat/restlet/services/SettingsRestlet.java b/src/main/java/org/nrg/xnat/restlet/services/SettingsRestlet.java deleted file mode 100644 index 75477a76ee1e473a1b9e55537474b645637d44d9..0000000000000000000000000000000000000000 --- a/src/main/java/org/nrg/xnat/restlet/services/SettingsRestlet.java +++ /dev/null @@ -1,940 +0,0 @@ -/* - * org.nrg.xnat.restlet.services.SettingsRestlet - * XNAT http://www.xnat.org - * Copyright (c) 2014, Washington University School of Medicine - * All Rights Reserved - * - * Released under the Simplified BSD. - * - * Last modified 1/27/14 11:54 AM - */ -package org.nrg.xnat.restlet.services; - -import org.apache.commons.lang3.StringUtils; -import org.hibernate.PropertyNotFoundException; -import org.json.JSONObject; -import org.nrg.config.entities.Configuration; -import org.nrg.config.exceptions.ConfigServiceException; -import org.nrg.dicomtools.filters.*; -import org.nrg.framework.exceptions.NrgServiceError; -import org.nrg.framework.exceptions.NrgServiceRuntimeException; -import org.nrg.framework.utilities.Patterns; -import org.nrg.mail.api.NotificationType; -import org.nrg.notify.api.CategoryScope; -import org.nrg.notify.api.SubscriberType; -import org.nrg.notify.entities.*; -import org.nrg.notify.exceptions.DuplicateSubscriberException; -import org.nrg.notify.services.NotificationService; -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; -import org.nrg.xft.XFT; -import org.nrg.xft.XFTItem; -import org.nrg.xft.event.EventUtils; -import org.nrg.xft.security.UserI; -import org.nrg.xnat.restlet.representations.ItemXMLRepresentation; -import org.nrg.xnat.restlet.resources.RestMockCallMapRestlet; -import org.nrg.xnat.restlet.resources.SecureResource; -import org.nrg.xnat.security.FilterSecurityInterceptorBeanPostProcessor; -import org.nrg.xnat.security.XnatExpiredPasswordFilter; -import org.nrg.xnat.turbine.utils.ArcSpecManager; -import org.nrg.xnat.utils.BuildDirScriptRunnerOutputAdapter; -import org.nrg.xnat.utils.XnatHttpUtils; -import org.restlet.Context; -import org.restlet.data.*; -import org.restlet.resource.Representation; -import org.restlet.resource.ResourceException; -import org.restlet.resource.StringRepresentation; -import org.restlet.resource.Variant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.util.*; -import java.util.regex.Matcher; - -public class SettingsRestlet extends SecureResource { - - public SettingsRestlet(Context context, Request request, Response response) throws IOException { - super(context, request, response); - - setModifiable(true); - - getVariants().add(new Variant(MediaType.APPLICATION_JSON)); - getVariants().add(new Variant(MediaType.TEXT_XML)); - - _filterService = XDAT.getContextService().getBean(DicomFilterService.class); - - _arcSpec = ArcSpecManager.GetInstance(); - _property = (String) getRequest().getAttributes().get("PROPERTY"); - - if (!StringUtils.isBlank(_property)) { - if (_property.equals("initialize")) { - if (_arcSpec != null && _arcSpec.isComplete()) { - throw new RuntimeException("You can't initialize an already initialized system!"); - } - } else { - if (_arcSpec == null) { - throw new RuntimeException("You haven't yet initialized the system, so I can't return any values!"); - } - _value = (String) getRequest().getAttributes().get("VALUE"); - } - } else { - if (_arcSpec == null) { - throw new RuntimeException("You haven't yet initialized the system, so I can't return any values!"); - } - } - if (!Roles.isSiteAdmin(user)) { - response.setStatus(Status.CLIENT_ERROR_FORBIDDEN, "Only site admins can retrieve the system settings."); - } else if (request.isEntityAvailable()) { - convertFormDataToMap(request.getEntity().getText()); - } - } - - @Override - public Representation represent(Variant variant) throws ResourceException { - final MediaType mediaType = overrideVariant(variant); - - try { - if (StringUtils.isBlank(_property)) { - return mediaType == MediaType.TEXT_XML ? - new ItemXMLRepresentation(_arcSpec.getItem(), mediaType) : - new StringRepresentation("{\"ResultSet\":{\"Result\":" + new JSONObject(getArcSpecAsMap()) + ", \"title\": \"Settings\"}}"); - } else { - if (!getArcSpecAsMap().containsKey(_property)) { - throw new PropertyNotFoundException(String.format("Setting '%s' was not found in the system.", _property)); - } - Object propertyValue = getArcSpecAsMap().get(_property); - - if (mediaType == MediaType.TEXT_XML) { - String xml = "<" + _property + ">" + propertyValue.toString() + "</" + _property + ">"; - return new StringRepresentation(xml, mediaType); - } else { - return new StringRepresentation("{\"ResultSet\":{\"Result\":" + toJson(propertyValue) + ", \"title\": \"" + _property + "\"}}"); - } - } - } catch (PropertyNotFoundException exception) { - respondToException(exception, Status.CLIENT_ERROR_BAD_REQUEST); - } catch (IOException | ConfigServiceException exception) { - throw new NrgServiceRuntimeException(NrgServiceError.Unknown, "Something went wrong converting filters to JSON.", exception); - } - return null; - } - - 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", preferences.getSiteId()); - final String siteUrl = StringUtils.isBlank(_arcSpec.getSiteUrl()) ? XnatHttpUtils.getServerRoot(getHttpServletRequest()) : _arcSpec.getSiteUrl(); - settings.put("siteUrl", siteUrl); - settings.put("siteAdminEmail", _arcSpec.getSiteAdminEmail()); - settings.put("smtpHost", _arcSpec.getSmtpHost()); - settings.put("requireLogin", _arcSpec.getRequireLogin()); - settings.put("enableNewRegistrations", _arcSpec.getEnableNewRegistrations()); - settings.put("emailVerification", XDAT.getSiteConfigurationProperty("emailVerification")); - settings.put("archivePath", _arcSpec.getGlobalArchivePath()); - settings.put("prearchivePath", _arcSpec.getGlobalPrearchivePath()); - settings.put("cachePath", _arcSpec.getGlobalCachePath()); - settings.put("buildPath", _arcSpec.getGlobalBuildPath()); - settings.put("ftpPath", _arcSpec.getGlobalpaths().getFtppath()); - settings.put("pipelinePath", _arcSpec.getGlobalpaths().getPipelinepath()); - // MIGRATION: This needs to go away when there's a proper DICOM SCP edit page. - settings.put("dcmPort", 8104); - settings.put("dcmAe", "XNAT"); - settings.put("enableCsrfToken", _arcSpec.getEnableCsrfToken()); - settings.put("error", getSubscribersForEvent(NotificationType.Error)); - settings.put("issue", getSubscribersForEvent(NotificationType.Issue)); - settings.put("newUser", getSubscribersForEvent(NotificationType.NewUser)); - settings.put("update", getSubscribersForEvent(NotificationType.Update)); - settings.put("anonScript", emptyStringIfNull(XDAT.getConfigService().getConfigContents("anon", "script"))); - settings.put("anonEnabled", Configuration.ENABLED_STRING.equals(XDAT.getConfigService().getStatus("anon", "script"))); - settings.put("tracerList", emptyStringIfNull(XDAT.getConfigService().getConfigContents("tracers", "tracers"))); - settings.put("appletScript", emptyStringIfNull(XDAT.getConfigService().getConfigContents("applet", "settings"))); - settings.put("restMockCallMap", getFormattedRestMockCallMap()); - final Map<String, String> filterAsMap = getSeriesImportFilterAsMap(); - if (filterAsMap != null && filterAsMap.size() > 0) { - settings.putAll(filterAsMap); - } - - return settings; - } - - private String emptyStringIfNull(final String configContents) { - return configContents == null ? "" : configContents; - } - - private DicomFilterService getDicomFilterService() { - return _filterService; - } - - private SeriesImportFilter getSeriesImportFilter() { - if (_seriesImportFilter == null) { - _seriesImportFilter = getDicomFilterService().getSeriesImportFilter(); - } - return _seriesImportFilter; - } - - private Map<String, String> getSeriesImportFilterAsMap() { - final SeriesImportFilter filter = getSeriesImportFilter(); - return filter == null ? null : filter.toQualifiedMap(); - } - - private String getFormattedRestMockCallMap() { - Map<String, String> map = RestMockCallMapRestlet.getRestMockCallMap(); - if (map == null || map.size() == 0) { - return StringUtils.EMPTY; - } - StringBuilder formattedMap = new StringBuilder(); - for (Map.Entry<String, String> call : map.entrySet()) { - formattedMap.append(call.getKey()).append("|").append(call.getValue()).append("\n"); - } - return formattedMap.toString(); - } - - private String getUnformattedRestMockCallMap(String raw) { - if (StringUtils.isBlank(raw)) { - return StringUtils.EMPTY; - } - BufferedReader reader = new BufferedReader(new StringReader(raw)); - Map<String, String> map = new HashMap<>(); - String line; - try { - while ((line = reader.readLine()) != null) { - String[] atoms = line.split("\\|"); - map.put(atoms[0], atoms[1]); - } - - return toJson(map); - } catch (IOException ignored) { - // We're not reading from a file, so we shouldn't encounter this. - } - - return StringUtils.EMPTY; - } - - // TODO: Gross. - private static final String ADMIN_USERNAME_FOR_SUBSCRIPTION = "admin"; - - /** - * This returns the current subscriber or subscribers to a particular <i>site-wide</i> event. If the event doesn't - * already exist, the event will be created with the default user set to the site administrator's email address. - * - * @param event The event to be created or retrieved. - */ - private synchronized String getSubscribersForEvent(NotificationType event) { - Category category; - Definition definition; - - synchronized (_log) { - category = getSiteEventCategory(event); - definition = getSiteEventDefinition(category); - } - - Map<Subscriber, Subscription> subscriptions = getNotificationService().getSubscriptionService().getSubscriberMapOfSubscriptionsForDefinition(definition); - if (subscriptions != null && subscriptions.size() > 0) { - return createCommaSeparatedList(subscriptions.keySet()); - } else { - Subscriber adminUser = getNotificationService().getSubscriberService().getSubscriberByName(ADMIN_USERNAME_FOR_SUBSCRIPTION); - if (adminUser == null) { - try { - adminUser = getNotificationService().getSubscriberService().createSubscriber(ADMIN_USERNAME_FOR_SUBSCRIPTION, _arcSpec.getSiteAdminEmail()); - } catch (DuplicateSubscriberException exception) { - // This shouldn't happen, since we just checked for the subscriber's existence. - } - } - - getNotificationService().subscribe(adminUser, SubscriberType.User, definition, XDAT.getHtmlMailChannel()); - assert adminUser != null; - return adminUser.getEmails(); - } - } - - private synchronized Category getSiteEventCategory(NotificationType event) { - Category category = getNotificationService().getCategoryService().getCategoryByScopeAndEvent(CategoryScope.Site, event.toString()); - if (category == null) { - category = initializeSiteEventCategory(event); - } - return category; - } - - private synchronized Definition getSiteEventDefinition(Category category) { - Definition definition; - List<Definition> definitions = getNotificationService().getDefinitionService().getDefinitionsForCategory(category); - if (definitions == null || definitions.size() == 0) { - definition = initializeSiteEventDefinition(category); - } else { - definition = definitions.get(0); - } - return definition; - } - - private String createCommaSeparatedList(final Set<Subscriber> subscribers) { - if (subscribers == null || subscribers.size() == 0) { - return ""; - } - boolean isFirst = true; - StringBuilder buffer = new StringBuilder(); - for (Subscriber subscriber : subscribers) { - if (isFirst) { - isFirst = false; - } else { - buffer.append(", "); - } - buffer.append(subscriber.getEmails()); - } - return buffer.toString(); - } - - @Override - public void handlePost() { - setProperties(); - } - - @Override - public void handlePut() { - setProperties(); - } - - @Override - public void handleDelete() { - _log.warn("Got a request to delete property with ID: " + _property + " from user: " + user.getLogin()); - returnDefaultRepresentation(); - } - - private void setProperties() { - if (!Roles.isSiteAdmin(user)) { - getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, "You must be an administrator to modify the site settings."); - return; - } - try { - if (!StringUtils.isBlank(_property) && !_property.equals("initialize")) { - setDiscreteProperty(); - checkNotifications(); - returnDefaultRepresentation(); - } else if (!StringUtils.isBlank(_property)) { - // We will only enter this if _property is "initialize", so that means we need to set up the arc spec entry. - initializeArcSpec(); - checkNotifications(); - setPropertiesFromMap(_data); - // Do not return a representation if we are initializing, it will attempt (and fail) to find a property called "initialize" - } else { - setPropertiesFromMap(_data); - returnDefaultRepresentation(); - } - } catch (ConfigServiceException exception) { - throw new NrgServiceRuntimeException(NrgServiceError.Unknown, "Something went wrong retrieving site properties.", exception); - } catch (Exception exception) { - respondToException(exception, Status.CLIENT_ERROR_BAD_REQUEST); - } - } - - private void setPropertiesFromMap(Map<String, String> map) throws Exception { - _log.debug("Setting arc spec property from body string: " + _form); - boolean dirtied = false; - boolean dirtiedNotifications = false; - final Map<String, String> notifications = new HashMap<>(); - final Map<String, String> filter = new HashMap<>(); - for (String property : map.keySet()) { - if (property.equals("siteId")) { - final String siteId = map.get("siteId"); - _arcSpec.setSiteId(siteId); - XFT.SetSiteID(siteId); - dirtied = true; - } else if (property.equals("siteUrl")) { - final String siteUrl = map.get("siteUrl"); - _arcSpec.setSiteUrl(siteUrl); - XFT.SetSiteURL(siteUrl); - dirtied = true; - } else if (property.equals("siteAdminEmail")) { - final String siteAdminEmail = map.get("siteAdminEmail"); - _arcSpec.setSiteAdminEmail(siteAdminEmail); - XFT.SetAdminEmail(siteAdminEmail); - dirtied = true; - } else if (property.equals("smtpHost")) { - final String smtpHost = map.get("smtpHost"); - _arcSpec.setSmtpHost(smtpHost); - XFT.SetAdminEmailHost(smtpHost); - dirtied = true; - } else if (property.equals("requireLogin")) { - final String requireLogin = map.get("requireLogin"); - _arcSpec.setRequireLogin(requireLogin); - XFT.SetRequireLogin(requireLogin); - updateSecurityFilter(Boolean.parseBoolean(requireLogin)); - dirtied = true; - } else if (property.equals("enableNewRegistrations")) { - final String enableNewRegistrations = map.get("enableNewRegistrations"); - _arcSpec.setEnableNewRegistrations(enableNewRegistrations); - XFT.SetUserRegistration(enableNewRegistrations); - dirtied = true; - } else if (property.equals("archivePath")) { - final String archivePath = map.get("archivePath"); - _arcSpec.getGlobalpaths().setArchivepath(archivePath); - XFT.SetArchiveRootPath(archivePath); - dirtied = true; - } else if (property.equals("prearchivePath")) { - final String prearchivePath = map.get("prearchivePath"); - _arcSpec.getGlobalpaths().setPrearchivepath(prearchivePath); - XFT.SetPrearchivePath(prearchivePath); - dirtied = true; - } else if (property.equals("cachePath")) { - final String cachePath = map.get("cachePath"); - _arcSpec.getGlobalpaths().setCachepath(cachePath); - XFT.SetCachePath(cachePath); - dirtied = true; - } else if (property.equals("buildPath")) { - final String buildPath = map.get("buildPath"); - _arcSpec.getGlobalpaths().setBuildpath(buildPath); - XFT.setBuildPath(buildPath); - dirtied = true; - } else if (property.equals("ftpPath")) { - final String ftpPath = map.get("ftpPath"); - _arcSpec.getGlobalpaths().setFtppath(ftpPath); - XFT.setFtpPath(ftpPath); - dirtied = true; - } else if (property.equals("pipelinePath")) { - final String pipelinePath = map.get("pipelinePath"); - _arcSpec.getGlobalpaths().setPipelinepath(pipelinePath); - XFT.SetPipelinePath(pipelinePath); - dirtied = true; - } else if (property.equals("dcmPort")) { - _arcSpec.setDcm_dcmPort(map.get("dcmPort")); - dirtied = true; - } else if (property.equals("dcmAe")) { - _arcSpec.setDcm_dcmAe(map.get("dcmAe")); - dirtied = true; - } else if (property.equals("enableCsrfToken")) { - final String enableCsrfToken = map.get("enableCsrfToken"); - _arcSpec.setEnableCsrfToken(enableCsrfToken); - XFT.SetEnableCsrfToken(enableCsrfToken); - dirtied = true; - } else if (property.equals("error") || property.equals("issue") || property.equals("newUser") || property.equals("update")) { - if (!dirtiedNotifications) { - dirtiedNotifications = true; - clearArcSpecNotifications(); - } - notifications.put(property, map.get(property)); - } else if (property.equals("anonScript")) { - final String anonScript = map.get("anonScript"); - try { - XDAT.getConfigService().replaceConfig(user.getUsername(), "Updating the site-wide anonymization script", "anon", "script", anonScript); - } catch (ConfigServiceException exception) { - throw new Exception("Error setting the site-wide anonymization script", exception); - } - dirtied = true; - } else if (property.equals("tracerList")) { - final String tracerList = map.get("tracerList"); - try { - XDAT.getConfigService().replaceConfig(user.getUsername(), "Updating the site-wide list of PET tracers", "tracers", "tracers", tracerList); - } catch (ConfigServiceException exception) { - throw new Exception("Error setting the site-wide list of PET tracers", exception); - } - dirtied = true; - } else if (property.equals("appletScript")) { - final String appletScript = map.get("appletScript"); - try { - XDAT.getConfigService().replaceConfig(user.getUsername(), "Updating the site-wide applet settings", "applet", "settings", appletScript); - } catch (ConfigServiceException exception) { - throw new Exception("Error setting the site-wide applet settings", exception); - } - dirtied = true; - } else if (property.equals("restMockCallMap")) { - final String callMap = map.get("restMockCallMap"); - try { - XDAT.getConfigService().replaceConfig(user.getUsername(), "Updating the REST service mock call map", "rest", "mockCallMap", getUnformattedRestMockCallMap(callMap)); - } catch (ConfigServiceException exception) { - throw new Exception("Error setting the REST service mock call map", exception); - } - dirtied = true; - } else if (property.equals("enableProjectAppletScript")) { - final String enableProjectAppletScript = map.get("enableProjectAppletScript"); - try { - XDAT.setSiteConfigurationProperty("enableProjectAppletScript", enableProjectAppletScript); - } catch (ConfigServiceException exception) { - throw new Exception("Error setting the enableProjectAppletScript site info property", exception); - } - dirtied = true; - } else if (property.equals("emailVerification")) { - final String emailVerification = map.get("emailVerification"); - try { - XDAT.setSiteConfigurationProperty("emailVerification", emailVerification); - } catch (ConfigServiceException exception) { - throw new Exception("Error setting the emailVerification site info property", exception); - } - dirtied = true; - } else if (property.startsWith("passwordExpiration")) { - try { - final String current = XDAT.getSiteConfigurationProperty(property); - final String value = map.get(property); - if (!StringUtils.equals(current, value)) { - dirtied = true; - XDAT.getContextService().getBean(XnatExpiredPasswordFilter.class).setPasswordExpirationDirtied(true); - XDAT.setSiteConfigurationProperty(property, value); - } - } catch (ConfigServiceException exception) { - throw new Exception(String.format("Error getting the '%s' site info property", property), exception); - } - } else if (property.startsWith("seriesImportFilter")) { - switch (property) { - case "seriesImportFilterList": - filter.put("contents", map.get(property).trim()); - break; - case "seriesImportFilterMode": - filter.put("mode", map.get(property).trim()); - break; - case "seriesImportFilterEnabled": - filter.put("enabled", map.get(property).trim()); - break; - } - } else { - try { - XDAT.setSiteConfigurationProperty(property, map.get(property)); - } catch (ConfigServiceException exception) { - throw new Exception(String.format("Error setting the '%s' site info property", property), exception); - } - dirtied = true; - } - } - if (filter.size() > 0) { - final boolean enabled = Boolean.parseBoolean(filter.get("enabled")); - final SeriesImportFilterMode mode = SeriesImportFilterMode.mode(filter.get("mode")); - final SeriesImportFilter seriesImportFilter; - if (mode == SeriesImportFilterMode.ModalityMap) { - seriesImportFilter = new ModalityMapSeriesImportFilter(filter.get("contents"), enabled); - } else { - seriesImportFilter = new RegExBasedSeriesImportFilter(filter.get("contents"), mode, enabled); - } - if (!seriesImportFilter.equals(getSeriesImportFilter())) { - _seriesImportFilter = null; - getDicomFilterService().commit(seriesImportFilter, userName, "Updated site-wide series import filter from administrator UI."); - } - } - if (dirtied || dirtiedNotifications) { - if (notifications.size() > 0) { - boolean allowNonuserSubscribers = XDAT.getBoolSiteConfigurationProperty("emailAllowNonuserSubscribers", false); - for (Map.Entry<String, String> notification : notifications.entrySet()) { - configureEventSubscriptions(NotificationType.valueOf(StringUtils.capitalize(notification.getKey())), notification.getValue(), allowNonuserSubscribers); - } - } - ArcSpecManager.save(_arcSpec, user, newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN, "Modified archive specification")); - } - if (map.containsKey("anonEnabled")) { - boolean anonymize = map.get("anonEnabled").equals("true"); - boolean anonScriptCurrentlyEnabled = XDAT.getConfigService().getConfig("anon", "script").isEnabled(); - if (anonymize && !anonScriptCurrentlyEnabled) { - try { - XDAT.getConfigService().enable(user.getUsername(), "Enabling the site-wide anonymization script", "anon", "script"); - } catch (ConfigServiceException e) { - e.printStackTrace(); - } - } - if (!anonymize && anonScriptCurrentlyEnabled) { - try { - XDAT.getConfigService().disable(user.getUsername(), "Disabling the site-wide anonymization script", "anon", "script"); - } catch (ConfigServiceException e) { - e.printStackTrace(); - } - } - } - } - - private void updateSecurityFilter(final boolean requireLogin) { - FilterSecurityInterceptor interceptor = XDAT.getContextService().getBean(FilterSecurityInterceptor.class); - FilterSecurityInterceptorBeanPostProcessor postProcessor = XDAT.getContextService().getBean(FilterSecurityInterceptorBeanPostProcessor.class); - assert interceptor != null; - assert postProcessor != null; - - interceptor.setSecurityMetadataSource(postProcessor.getMetadataSource(requireLogin)); - } - - /** - * Sets up the subscriptions for the indicated events. - * - * @param notificationType The type of notification for which to configure subscriptions. - * @param userIds The IDs of the users to be subscribed to the indicated notification. - * @param allowNonuserSubscribers Indicates whether email addresses that are not associated with system users - * should be allowed for subscription addresses. - */ - private void configureEventSubscriptions(final NotificationType notificationType, final String userIds, final boolean allowNonuserSubscribers) throws Exception { - Definition definition = retrieveSiteEventDefinition(notificationType); - List<Subscriber> subscribers = getSubscribersFromAddresses(userIds, allowNonuserSubscribers); - Map<Subscriber, Subscription> subscriptions = getNotificationService().getSubscriptionService().getSubscriberMapOfSubscriptionsForDefinition(definition); - Channel channel = XDAT.getHtmlMailChannel(); - - for (Subscriber subscriber : subscribers) { - // If we don't have a subscription for this notification... - if (!subscriptions.containsKey(subscriber)) { - // Create one. - getNotificationService().subscribe(subscriber, SubscriberType.User, definition, channel); - // But if we do have a subscription for this notification... - } else { - // Remove it from the map. - subscriptions.remove(subscriber); - } - } - - // If there are any left-over subscriptions... - if (subscriptions.size() > 0) { - // Those are no longer wanted (they weren't specified in the submitted list), so let's remove those subscriptions. - for (Subscription subscription : subscriptions.values()) { - getNotificationService().getSubscriptionService().delete(subscription); - } - } - - configureArcSpecNotificationType(_arcSpec, notificationType, subscriptions.values()); - } - - /** - * @param type The type for which the definition and its associated category should be created or retrieved. - * @return The existing or newly created definition. - */ - private synchronized Definition retrieveSiteEventDefinition(NotificationType type) { - Category category = getNotificationService().getCategoryService().getCategoryByScopeAndEvent(CategoryScope.Site, type.toString()); - if (category == null) { - category = initializeSiteEventCategory(type.toString()); - } - List<Definition> definitions = getNotificationService().getDefinitionService().getDefinitionsForCategory(category); - Definition definition; - if (definitions == null || definitions.size() == 0) { - definition = initializeSiteEventDefinition(category); - } else { - definition = definitions.get(0); - } - return definition; - } - - /** - * @param event The event for which a category should be created. - * @return The newly created category object. - */ - private synchronized Category initializeSiteEventCategory(NotificationType event) { - return initializeSiteEventCategory(event.toString()); - } - - /** - * @param event The event for which a category should be created. - * @return The newly created category object. - */ - private synchronized Category initializeSiteEventCategory(String event) { - Category category = getNotificationService().getCategoryService().newEntity(); - category.setScope(CategoryScope.Site); - category.setEvent(event); - getNotificationService().getCategoryService().create(category); - return category; - } - - /** - * @param category The category for which a definition should be created. - * @return The newly created definition object. - */ - private synchronized Definition initializeSiteEventDefinition(Category category) { - Definition definition = getNotificationService().getDefinitionService().newEntity(); - definition.setCategory(category); - getNotificationService().getDefinitionService().create(definition); - return definition; - } - - /** - * Takes a comma-separated list of "email addresses" (which actually may include {@link UserI#getEmail() email addresses}, - * {@link UserI#getLogin() XDAT user names}, and a combination of the two in the format: - * <p/> - * <code><i>username</i> <<i>email</i>></code> - * <p/> - * So for example, you may have something like this: - * <p/> - * <code>user1 <user1@@xnat.org>, user2, user3@xnat.org</code> - * <p/> - * Note that if any of the users aren't found, this method currently will have no indication other than returning fewer - * users than are specified in the <b>emailAddresses</b> parameter. - * - * @param addressList The comma-separated list of usernames, email addressList, and combined IDs. - * @param allowNonuserSubscribers Indicates whether email addresses that are not associated with system users - * should be allowed for subscription addresses. - * @return A list of {@link Subscriber} objects representing those users. - */ - private List<Subscriber> getSubscribersFromAddresses(String addressList, final boolean allowNonuserSubscribers) throws Exception { - final String[] addresses = addressList.split("[\\s]*,[\\s]*"); - if (addresses.length == 0) { - throw new Exception("Submitted text couldn't be parsed into a list of addresses: " + addressList); - } - - List<Subscriber> subscribers = new ArrayList<>(); - List<String> nonuserAddresses = new ArrayList<>(); - for (String address : addresses) { - String username = null; - String email = null; - if (Patterns.USERNAME.matcher(address).matches()) { - // Handle this as a username. - UserI user = null; - try { - user = Users.getUser(address); - } catch (Exception ignored) { - } - if (user != null) { - username = address; - email = user.getEmail(); - } - } else if (Patterns.EMAIL.matcher(address).matches()) { - // Handle this as an email. - List<UserI> users = Users.getUsersByEmail(address); - if (users != null && users.size() > 0) { - if (users.size() == 1) { - username = users.get(0).getLogin(); - } else { - for (UserI user : users) { - username = user.getLogin(); - if (Roles.isSiteAdmin(user)) { - break; - } - } - } - email = address; - } else if (allowNonuserSubscribers) { - // If we allow non-user subscribers, then we'll just make the username and email address be the same. - username = email = address; - } - } else { - Matcher combinedMatcher = Patterns.COMBINED.matcher(address); - if (combinedMatcher.matches()) { - // Handle this as a combined. username will match first capture, email second capture (0 capture in regex is full expression). - username = combinedMatcher.group(1); - email = combinedMatcher.group(2); - } - } - - // If there's no username, this is a non-user address on a system that doesn't allow non-user subscribers; - // continue so we can harvest ALL the non-user addresses, then handle them appropriately later. - if (username == null) { - nonuserAddresses.add(address); - continue; - } - - // If we don't have any non-user addresses, get the subscriber. If we do have any non-user addresses, we - // have a valid user but we'll skip getting the subscriber to save ourselves the work. - if (nonuserAddresses.size() == 0) { - Subscriber subscriber = getNotificationService().getSubscriberService().getSubscriberByName(username); - if (subscriber == null) { - try { - subscriber = getNotificationService().getSubscriberService().createSubscriber(username, email); - } catch (DuplicateSubscriberException exception) { - // This shouldn't happen, since we just checked for the subscriber's existence. - } - } - - assert subscriber != null; - if (!subscriber.getEmails().equalsIgnoreCase(email)) { - subscriber.setEmails(email); - getNotificationService().getSubscriberService().update(subscriber); - } - subscribers.add(subscriber); - } - } - - if (nonuserAddresses.size() > 0) { - throw new Exception(getBadAddressErrorMessage(nonuserAddresses)); - } - - return subscribers; - } - - private String getBadAddressErrorMessage(final List<String> badAddresses) { - StringBuilder buffer = new StringBuilder("<p>The following addresses were not valid usernames or emails of users of this XNAT server:</p><ul>"); - for (String address : badAddresses) { - buffer.append("<li>").append(address).append("</li>"); - } - buffer.append("</ul>"); - return buffer.toString(); - } - - private void initializeArcSpec() throws Exception { - PopulateItem populator = new PopulateItem(copyDataToXmlPath(), user, "arc:ArchiveSpecification", true); - XFTItem item = populator.getItem(); - item.setUser(user); - ArcSpecManager.save(new ArcArchivespecification(item), user, newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN, "Initialized archive specification")); - _arcSpec = ArcSpecManager.GetInstance(); - BuildDirScriptRunnerOutputAdapter adapter = XDAT.getContextService().getBean(BuildDirScriptRunnerOutputAdapter.class); - adapter.setPath(_arcSpec.getGlobalBuildPath()); - } - - private void setDiscreteProperty() throws Exception { - if (getRequest().getMethod() != Method.POST) { - if (_log.isDebugEnabled()) { - _log.debug("Setting arc spec property: [" + _property + "] = " + _value); - } - if (!getArcSpecAsMap().containsKey(_property)) { - throw new PropertyNotFoundException(String.format("Setting '%s' was not found in the system.", _property)); - } - } else if (_log.isInfoEnabled()) { - _log.info("Requested POST to property: [" + _property + "] = " + _value); - } - if (null == _value) { - throw new NullPointerException(String.format("Setting '%s' cannot be set to NULL.", _property)); - } else { - Map<String, String> map = new HashMap<>(1); - map.put(_property, _value); - setPropertiesFromMap(map); - } - } - - private Map<String, String> copyDataToXmlPath() { - Map<String, String> data = new HashMap<>(_data.size()); - addSpecifiedProperty(data, "arc:archivespecification/site_id", "siteId"); - addSpecifiedProperty(data, "arc:archivespecification/site_url", "siteUrl"); - addSpecifiedProperty(data, "arc:archivespecification/site_admin_email", "siteAdminEmail"); - addSpecifiedProperty(data, "arc:archivespecification/smtp_host", "smtpHost"); - addSpecifiedProperty(data, "arc:archivespecification/globalpaths/archivepath", "archivePath"); - addSpecifiedProperty(data, "arc:archivespecification/globalpaths/prearchivepath", "prearchivePath"); - addSpecifiedProperty(data, "arc:archivespecification/globalpaths/cachepath", "cachePath"); - addSpecifiedProperty(data, "arc:archivespecification/globalpaths/ftppath", "ftpPath"); - addSpecifiedProperty(data, "arc:archivespecification/globalpaths/buildpath", "buildPath"); - addSpecifiedProperty(data, "arc:archivespecification/globalpaths/pipelinepath", "pipelinePath"); - addSpecifiedProperty(data, "arc:archivespecification/require_login", "requireLogin"); - addSpecifiedProperty(data, "arc:archivespecification/enable_new_registrations", "enableNewRegistrations"); - addSpecifiedProperty(data, "arc:archivespecification/dcm/dcm_ae", "dcmAe"); - addSpecifiedProperty(data, "arc:archivespecification/dcm/dcm_port", "dcmPort"); - addSpecifiedProperty(data, "arc:archivespecification/enable_csrf_token", "enableCsrfToken"); - return data; - } - - /** - * Checks whether the {@link #_data} map contains the specified key and whether the corresponding value is blank. - * If the key exists and the value is not blank, this method puts the value into the submitted data map using the - * submitted <b>xmlPath</b> as the key. - * - * @param data The data map to be populated with existing non-blank values. - * @param xmlPath The key to use for storage in the data map. - * @param key The key to check in the parsed data map. - */ - private void addSpecifiedProperty(final Map<String, String> data, final String xmlPath, final String key) { - if (_data.containsKey(key)) { - String value = _data.get(key); - if (!StringUtils.isBlank(value)) { - data.put(xmlPath, value); - } - } - } - - private void convertFormDataToMap(String text) { - _form = text; - _data = new HashMap<>(); - String[] entries = text.split("&"); - for (String entry : entries) { - String[] atoms = entry.split("=", 2); - if (atoms.length > 0) { - if (atoms.length == 1) { - _data.put(atoms[0], ""); - } else { - try { - _data.put(atoms[0], URLDecoder.decode(atoms[1], "UTF-8")); - } catch (UnsupportedEncodingException e) { - // This is the dumbest exception in the history of humanity: the form of this method that doesn't - // specify an encoding is deprecated, so you have to specify an encoding. But the form of the method - // that takes an encoding (http://bit.ly/yX56fe) has an note that emphasizes that you should only - // use UTF-8 because "[n]ot doing so may introduce incompatibilities." Got it? You have to specify - // it, but it should always be the same thing. Oh, and BTW? You have to catch an exception for - // unsupported encodings because you may specify that one acceptable encoding or... something. - // - // I hate them. - } - } - } - } - } - - /** - * Checks whether site-side notifications exist and initializes them if not. - * - * @throws Exception - */ - private void checkNotifications() throws Exception { - // Check whether any notification types already exist and clear them if so. - clearArcSpecNotifications(); - - for (NotificationType type : NotificationType.values()) { - Definition definition = retrieveSiteEventDefinition(type); - List<Subscription> subscriptions = getNotificationService().getSubscriptionService().getSubscriptionsForDefinition(definition); - configureArcSpecNotificationType(_arcSpec, type, subscriptions); - } - } - - private void configureArcSpecNotificationType(final ArcArchivespecification arcSpec, final NotificationType type, final Collection<Subscription> subscriptions) throws Exception { - ArcArchivespecificationNotificationTypeI typeObj = new ArcArchivespecificationNotificationType(); - typeObj.setNotificationType(type.id()); - if (subscriptions == null || subscriptions.size() == 0) { - typeObj.setEmailAddresses(getSiteAdminAccount(arcSpec) + " <" + arcSpec.getSiteAdminEmail() + ">"); - } else { - StringBuilder buffer = new StringBuilder(); - boolean isFirst = true; - for (Subscription subscription : subscriptions) { - if (isFirst) { - isFirst = false; - } else { - buffer.append(", "); - } - buffer.append(subscription.getSubscriber()); - } - typeObj.setEmailAddresses(buffer.toString()); - } - arcSpec.addNotificationTypes_notificationType(typeObj); - } - - /** - * Clears the arc spec notification listings. - */ - private void clearArcSpecNotifications() { - List<ArcArchivespecificationNotificationTypeI> notificationTypes; - while ((notificationTypes = _arcSpec.getNotificationTypes_notificationType()) != null && notificationTypes.size() > 0) { - _arcSpec.removeNotificationTypes_notificationType(0); - } - } - - /** - * Gets the notification service instance. - * - * @return The notification service instance. - */ - private NotificationService getNotificationService() { - if (_notificationService == null) { - _notificationService = XDAT.getNotificationService(); - } - return _notificationService; - } - - /** - * Gets the site admin account name. - * - * @param arcSpec The arc spec from which the admin account can be retrieved. - * @return The site admin account name. - */ - private String getSiteAdminAccount(ArcArchivespecification arcSpec) { - List<UserI> users = Users.getUsersByEmail(arcSpec.getSiteAdminEmail()); - if (users == null || users.size() == 0) { - throw new RuntimeException("Can't find anything for the site admin email account! It must be associated with a user account: " + arcSpec.getSiteAdminEmail()); - } - return users.get(0).getLogin(); - } - - private static final Logger _log = LoggerFactory.getLogger(SettingsRestlet.class); - - private final DicomFilterService _filterService; - - private NotificationService _notificationService; - private ArcArchivespecification _arcSpec; - private SeriesImportFilter _seriesImportFilter; - private String _property; - private String _value; - private String _form; - private Map<String, String> _data; -} diff --git a/src/main/java/org/nrg/xnat/restlet/services/mail/MailRestlet.java b/src/main/java/org/nrg/xnat/restlet/services/mail/MailRestlet.java index 113758c079cfd9f9410817966113d430b0153039..b12052286a58b969040e19215d509db46e711b05 100644 --- a/src/main/java/org/nrg/xnat/restlet/services/mail/MailRestlet.java +++ b/src/main/java/org/nrg/xnat/restlet/services/mail/MailRestlet.java @@ -78,7 +78,7 @@ public class MailRestlet extends SecureResource { MailMessage message = new MailMessage(); // When receiving email send requests through the REST service, the from address is always the admin, with the mail sent on behalf of the validating user. - message.setFrom(AdminUtils.getAdminEmailId()); + message.setFrom(XDAT.getSiteConfigPreferences().getAdminEmail()); message.setOnBehalfOf(user.getEmail()); // Handle all the addresses. diff --git a/src/main/java/org/nrg/xnat/security/XnatInitCheckFilter.java b/src/main/java/org/nrg/xnat/security/XnatInitCheckFilter.java index cd2826f9b4c75d8918e599d4894842864aefc73e..1960e057270a5954e951e0ea662ac613953b4f9c 100644 --- a/src/main/java/org/nrg/xnat/security/XnatInitCheckFilter.java +++ b/src/main/java/org/nrg/xnat/security/XnatInitCheckFilter.java @@ -10,25 +10,23 @@ */ package org.nrg.xnat.security; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; +import org.nrg.xdat.XDAT; +import org.nrg.xdat.security.helpers.Roles; +import org.nrg.xft.security.UserI; +import org.nrg.xnat.utils.XnatHttpUtils; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.web.filter.GenericFilterBean; +import javax.inject.Inject; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.nrg.xdat.XDAT; -import org.nrg.xdat.om.ArcArchivespecification; -import org.nrg.xdat.security.helpers.Roles; -import org.nrg.xdat.turbine.utils.TurbineUtils; -import org.nrg.xft.security.UserI; -import org.nrg.xnat.turbine.utils.ArcSpecManager; -import org.nrg.xnat.utils.XnatHttpUtils; -import org.springframework.web.filter.GenericFilterBean; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; public class XnatInitCheckFilter extends GenericFilterBean { @@ -37,11 +35,11 @@ public class XnatInitCheckFilter extends GenericFilterBean { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; - // MIGRATION: Get rid of the arcspec!!! - final ArcArchivespecification arcSpec = ArcSpecManager.GetInstance(); - - if (arcSpec != null && arcSpec.isComplete()) { - //If arc spec has already been set, do not redirect. + // In this case, the count of siteUrl is a proxy for whether the system has been initialized. + @SuppressWarnings({"SqlDialectInspection", "SqlNoDataSourceInspection"}) + final boolean initialized = _template.queryForObject("select count(*) from xhbm_preference p, xhbm_tool t where t.tool_id = 'siteConfig' and p.tool = t.id and p.name = 'siteUrl';", Integer.class) > 0; + if (initialized) { + // If the site URL has already been set, do not redirect. chain.doFilter(req, res); } else { final UserI user = XDAT.getUserDetails(); @@ -50,7 +48,8 @@ public class XnatInitCheckFilter extends GenericFilterBean { if (user == null) { String header = request.getHeader("Authorization"); if (header != null && header.startsWith("Basic ") && !uri.contains(_initializationPath)) { - //Users that authenticated using basic authentication receive an error message informing them that the arc spec is not set. + // Users that authenticated using basic authentication receive an error message informing + // them that the system is not yet initialized. response.sendError(HttpServletResponse.SC_FORBIDDEN, "Site has not yet been configured."); return; } @@ -66,25 +65,20 @@ public class XnatInitCheckFilter extends GenericFilterBean { // the request is not for another page (preventing the user from navigating away from the Configuration page via the menu bar). chain.doFilter(req, res); } else { - try { - if(user == null) { - // user not authenticated, let another filter handle the redirect - // (NB: I tried putting this check up with the basic auth check, - // but you get this weird redirect with 2 login pages on the same screen. Seems to work here). - chain.doFilter(req, res); + if(user == null) { + // user not authenticated, let another filter handle the redirect + // (NB: I tried putting this check up with the basic auth check, + // but you get this weird redirect with 2 login pages on the same screen. Seems to work here). + chain.doFilter(req, res); + } else { + final String serverPath = XnatHttpUtils.getServerRoot(request); + if (Roles.isSiteAdmin(user)) { + //Otherwise, if the user has administrative permissions, direct the user to the configuration page. + response.sendRedirect(serverPath + _configurationPath); } else { - final String serverPath = XnatHttpUtils.getServerRoot(request); - if (Roles.isSiteAdmin(user)) { - //Otherwise, if the user has administrative permissions, direct the user to the configuration page. - response.sendRedirect(serverPath + _configurationPath); - } else { - //The arc spec is not set but the user does not have administrative permissions. Direct the user to an error page. - response.sendRedirect(serverPath + _nonAdminErrorPath); - } + //The system is not initialized but the user does not have administrative permissions. Direct the user to an error page. + response.sendRedirect(serverPath + _nonAdminErrorPath); } - } catch (Exception e) { - logger.error("Error checking user role in the Arc Spec Filter.", e); - response.sendRedirect(TurbineUtils.GetFullServerPath() + _nonAdminErrorPath); } } } @@ -116,6 +110,9 @@ public class XnatInitCheckFilter extends GenericFilterBean { return false; } + @Inject + private JdbcTemplate _template; + private String _initializationPath = ""; private String _configurationPath = ""; private String _nonAdminErrorPath = ""; diff --git a/src/main/java/org/nrg/xnat/security/XnatLogoutSuccessHandler.java b/src/main/java/org/nrg/xnat/security/XnatLogoutSuccessHandler.java index 5ec60f38e26c022e76a2897a6bc1d6e85b804b7e..4c17d3538632cf47be8777c643854be0c7b130b1 100644 --- a/src/main/java/org/nrg/xnat/security/XnatLogoutSuccessHandler.java +++ b/src/main/java/org/nrg/xnat/security/XnatLogoutSuccessHandler.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.xft.XFT; +import org.nrg.xdat.XDAT; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; @@ -39,7 +39,7 @@ public class XnatLogoutSuccessHandler extends AbstractAuthenticationTargetUrlReq } private String getRequiredLogoutSuccessUrl() { - final boolean requireLogin = XFT.GetRequireLogin(); + final boolean requireLogin = XDAT.getSiteConfigPreferences().getRequireLogin(); final String returnUrl = requireLogin ? _securedXnatLogoutSuccessUrl : _openXnatLogoutSuccessUrl; if (_log.isDebugEnabled()) { diff --git a/src/main/java/org/nrg/xnat/services/messaging/file/MoveStoredFileRequestListener.java b/src/main/java/org/nrg/xnat/services/messaging/file/MoveStoredFileRequestListener.java index 25cd46d5d2fcd8b633aa283305fd200c6d1c5d4a..d25ec48d401d20e035f0e236cc3ac4c57aa34452 100644 --- a/src/main/java/org/nrg/xnat/services/messaging/file/MoveStoredFileRequestListener.java +++ b/src/main/java/org/nrg/xnat/services/messaging/file/MoveStoredFileRequestListener.java @@ -77,7 +77,7 @@ public class MoveStoredFileRequestListener { } try { - XDAT.getMailService().sendHtmlMessage(AdminUtils.getAdminEmailId(), request.getNotifyList(), subject, message); + XDAT.getMailService().sendHtmlMessage(XDAT.getSiteConfigPreferences().getAdminEmail(), request.getNotifyList(), subject, message); } catch (MessagingException e) { log.error("Failed to send email.", e); } diff --git a/src/main/java/org/nrg/xnat/turbine/modules/actions/AddProject.java b/src/main/java/org/nrg/xnat/turbine/modules/actions/AddProject.java index 6aae275a9734616b24e7a3c3da3256dc1d1e1f45..4bf7e85358218c1b6d382d2b7c0dd4f5136a8715 100755 --- a/src/main/java/org/nrg/xnat/turbine/modules/actions/AddProject.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/actions/AddProject.java @@ -14,16 +14,19 @@ import org.apache.commons.lang3.StringUtils; import org.apache.turbine.modules.ScreenLoader; import org.apache.turbine.util.RunData; import org.apache.velocity.context.Context; +import org.nrg.xdat.XDAT; import org.nrg.xdat.om.ArcProject; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.om.base.BaseXnatProjectdata; -import org.nrg.xdat.security.helpers.*; +import org.nrg.xdat.security.helpers.Groups; +import org.nrg.xdat.security.helpers.Permissions; +import org.nrg.xdat.security.helpers.Roles; +import org.nrg.xdat.security.helpers.UserHelper; import org.nrg.xdat.turbine.modules.actions.SecureAction; import org.nrg.xdat.turbine.modules.screens.EditScreenA; import org.nrg.xdat.turbine.utils.PopulateItem; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.ItemI; -import org.nrg.xft.XFT; import org.nrg.xft.XFTItem; import org.nrg.xft.db.PoolDBUtils; import org.nrg.xft.event.EventMetaI; @@ -54,7 +57,7 @@ public class AddProject extends SecureAction { context.put("tag", TurbineUtils.GetPassedParameter("tag", data)); } - if (!XFT.getBooleanProperty("UI.allow-non-admin-project-creation", true) && !Roles.isSiteAdmin(user)) { + if (!XDAT.getSiteConfigPreferences().getUiAllowNonAdminProjectCreation() && !Roles.isSiteAdmin(user)) { displayProjectEditError("Invalid permissions for this operation", data, null); return; } diff --git a/src/main/java/org/nrg/xnat/turbine/modules/actions/ConfirmRegister.java b/src/main/java/org/nrg/xnat/turbine/modules/actions/ConfirmRegister.java index 069a156e7f8428f5d0bcce02e7055198e1fe88c5..c56bcf28846779df379682f09e0e81fea9a72473 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/actions/ConfirmRegister.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/actions/ConfirmRegister.java @@ -10,18 +10,18 @@ */ package org.nrg.xnat.turbine.modules.actions; -import java.util.List; - import org.apache.commons.lang3.StringUtils; import org.apache.turbine.util.RunData; import org.apache.velocity.context.Context; +import org.nrg.xdat.XDAT; import org.nrg.xdat.security.helpers.Users; import org.nrg.xdat.turbine.modules.actions.SecureAction; import org.nrg.xdat.turbine.modules.screens.SecureScreen; -import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.security.UserI; +import java.util.List; + public class ConfirmRegister extends SecureAction { @Override @@ -38,7 +38,7 @@ public class ConfirmRegister extends SecureAction { if(!StringUtils.isEmpty(par)){ context.put("par", par); } - if (!StringUtils.isEmpty(nextAction) && nextAction.indexOf("XDATLoginUser")==-1 && !nextAction.equals(org.apache.turbine.Turbine.getConfiguration().getString("action.login"))){ + if (!StringUtils.isEmpty(nextAction) && !nextAction.contains("XDATLoginUser") && !nextAction.equals(org.apache.turbine.Turbine.getConfiguration().getString("action.login"))){ context.put("nextAction", nextAction); }else if (!StringUtils.isEmpty(nextPage) && !nextPage.equals(org.apache.turbine.Turbine.getConfiguration().getString("template.home")) ) { context.put("nextPage", nextPage); @@ -50,7 +50,7 @@ public class ConfirmRegister extends SecureAction { if (current==null) { //allowed to have multiple accounts with the admin email address - if(!StringUtils.equals(newUser.getEmail(),AdminUtils.getAdminEmailId())) + if(!StringUtils.equals(newUser.getEmail(), XDAT.getSiteConfigPreferences().getAdminEmail())) { List<UserI> match=Users.getUsersByEmail(newUser.getEmail()); if(match.size()>0){ @@ -72,7 +72,7 @@ public class ConfirmRegister extends SecureAction { data.setMessage("Username (" + newUser.getEmail() + ") already exists."); data.setScreenTemplate("ForgotLogin.vm"); } - } catch (Exception e) { + } catch (Exception ignored) { } } diff --git a/src/main/java/org/nrg/xnat/turbine/modules/actions/ManagePipeline.java b/src/main/java/org/nrg/xnat/turbine/modules/actions/ManagePipeline.java index aeed0589e099186e5837fbe2a633189699cb1a4e..0ac76f4e3336e9f9f513b2c4f0dde5dc2b680a8c 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/actions/ManagePipeline.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/actions/ManagePipeline.java @@ -11,12 +11,6 @@ package org.nrg.xnat.turbine.modules.actions; -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.Hashtable; - import org.apache.turbine.modules.ScreenLoader; import org.apache.turbine.util.RunData; import org.apache.velocity.context.Context; @@ -30,17 +24,11 @@ import org.nrg.pipeline.xmlbeans.ParameterData; import org.nrg.pipeline.xmlbeans.ParameterData.Values; import org.nrg.pipeline.xmlbeans.ParametersDocument; import org.nrg.pipeline.xmlbeans.ParametersDocument.Parameters; +import org.nrg.xdat.XDAT; import org.nrg.xdat.model.ArcPipelinedataI; -import org.nrg.xdat.om.ArcProject; -import org.nrg.xdat.om.ArcProjectDescendant; -import org.nrg.xdat.om.ArcProjectDescendantPipeline; -import org.nrg.xdat.om.ArcProjectPipeline; -import org.nrg.xdat.om.PipePipelinedetails; -import org.nrg.xdat.om.PipePipelinerepository; -import org.nrg.xdat.om.XnatProjectdata; +import org.nrg.xdat.om.*; import org.nrg.xdat.turbine.modules.actions.SecureAction; import org.nrg.xdat.turbine.modules.screens.EditScreenA; -import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xdat.turbine.utils.PopulateItem; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.XFTItem; @@ -61,6 +49,12 @@ import org.nrg.xnat.utils.WorkflowUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Hashtable; + public class ManagePipeline extends SecureAction { @@ -386,8 +380,8 @@ public class ManagePipeline extends SecureAction { xnatPipelineLauncher.setSupressNotification(true); xnatPipelineLauncher.setParameter("useremail", user.getEmail()); xnatPipelineLauncher.setParameter("userfullname", XnatPipelineLauncher.getUserName(user)); - xnatPipelineLauncher.setParameter("adminemail", AdminUtils.getAdminEmailId()); - xnatPipelineLauncher.setParameter("mailhost", AdminUtils.getMailServer()); + xnatPipelineLauncher.setParameter("adminemail", XDAT.getSiteConfigPreferences().getAdminEmail()); + xnatPipelineLauncher.setParameter("mailhost", XDAT.getSiteConfigPreferences().getSmtpServer().get("host")); xnatPipelineLauncher.setParameter("xnatserver", TurbineUtils.GetSystemName()); xnatPipelineLauncher.setPipelineName(pipeline_path); String exptLabel = item.getStringProperty("label"); @@ -433,7 +427,7 @@ public class ManagePipeline extends SecureAction { for (int i = 0; i < totalParams; i++) { String name = ((String)org.nrg.xdat.turbine.utils.TurbineUtils.GetPassedParameter("param[" + i + "].name",data)); int rowcount = TurbineUtils.GetPassedInteger("param[" + i + "].name.rowcount", data); - ArrayList<String> formvalues = new ArrayList<String>(); + ArrayList<String> formvalues = new ArrayList<>(); for (int j = 0; j < rowcount; j++) { String formfieldname = "param[" + i + "][" + j + "].value"; if (TurbineUtils.HasPassedParameter(formfieldname, data)) //formvalues.add(data.getParameters().get(formfieldname)); diff --git a/src/main/java/org/nrg/xnat/turbine/modules/actions/ManageProjectAccess.java b/src/main/java/org/nrg/xnat/turbine/modules/actions/ManageProjectAccess.java index feba56fc7a2db917e3e7a20c8db6db6e5b900ca6..470659ef681990098851b88201e0618fa4738ac2 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/actions/ManageProjectAccess.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/actions/ManageProjectAccess.java @@ -92,7 +92,7 @@ public class ManageProjectAccess extends SecureAction { context.put("process", "Transfer to the archive."); context.put("system", TurbineUtils.GetSystemName()); context.put("access_level", "owner"); - context.put("admin_email", AdminUtils.getAdminEmailId()); + context.put("admin_email", XDAT.getSiteConfigPreferences().getAdminEmail()); context.put("projectOM", project); org.nrg.xnat.turbine.modules.actions.ProcessAccessRequest.SendAccessApprovalEmail(context, newOwner, TurbineUtils.getUser(data), TurbineUtils.GetSystemName() + " Access Granted for " + project.getName()); } @@ -126,7 +126,7 @@ public class ManageProjectAccess extends SecureAction { context.put("process", "Transfer to the archive."); context.put("system", TurbineUtils.GetSystemName()); context.put("access_level", "member"); - context.put("admin_email", AdminUtils.getAdminEmailId()); + context.put("admin_email", XDAT.getSiteConfigPreferences().getAdminEmail()); context.put("projectOM", project); org.nrg.xnat.turbine.modules.actions.ProcessAccessRequest.SendAccessApprovalEmail(context, newMember, TurbineUtils.getUser(data), TurbineUtils.GetSystemName() + " Access Granted for " + project.getName()); } @@ -160,7 +160,7 @@ public class ManageProjectAccess extends SecureAction { context.put("process", "Transfer to the archive."); context.put("system", TurbineUtils.GetSystemName()); context.put("access_level", "collaborator"); - context.put("admin_email", AdminUtils.getAdminEmailId()); + context.put("admin_email", XDAT.getSiteConfigPreferences().getAdminEmail()); context.put("projectOM", project); org.nrg.xnat.turbine.modules.actions.ProcessAccessRequest.SendAccessApprovalEmail(context, newMember, TurbineUtils.getUser(data), TurbineUtils.GetSystemName() + " Access Granted for " + project.getName()); } diff --git a/src/main/java/org/nrg/xnat/turbine/modules/actions/MatchPrearchiveSessions.java b/src/main/java/org/nrg/xnat/turbine/modules/actions/MatchPrearchiveSessions.java index ecccb7c4dc72791787eed62dfa966a2e1e2a6a02..13bcaaf64e76cc16d08e2e428349956ad3688a29 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/actions/MatchPrearchiveSessions.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/actions/MatchPrearchiveSessions.java @@ -10,15 +10,13 @@ */ package org.nrg.xnat.turbine.modules.actions; -import java.io.File; - import org.apache.turbine.util.RunData; import org.apache.velocity.context.Context; +import org.nrg.xdat.XDAT; import org.nrg.xdat.base.BaseElement; import org.nrg.xdat.om.XnatImagescandata; import org.nrg.xdat.om.XnatImagesessiondata; import org.nrg.xdat.turbine.modules.actions.SecureAction; -import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.XFTItem; import org.nrg.xft.schema.Wrappers.XMLWrapper.SAXReader; @@ -26,6 +24,8 @@ import org.nrg.xft.security.UserI; import org.nrg.xnat.archive.BatchTransfer; import org.nrg.xnat.turbine.utils.ArcSpecManager; +import java.io.File; + public class MatchPrearchiveSessions extends SecureAction { /* (non-Javadoc) @@ -33,14 +33,14 @@ public class MatchPrearchiveSessions extends SecureAction { */ @Override public void doPerform(RunData data, Context context) throws Exception { - Integer num= ((Integer)org.nrg.xdat.turbine.utils.TurbineUtils.GetPassedInteger("num_sessions",data)); - BatchTransfer bt = new BatchTransfer(TurbineUtils.GetFullServerPath(),TurbineUtils.GetSystemName(),AdminUtils.getAdminEmailId()); + Integer num= TurbineUtils.GetPassedInteger("num_sessions", data); + BatchTransfer bt = new BatchTransfer(TurbineUtils.GetFullServerPath(), TurbineUtils.GetSystemName(), XDAT.getSiteConfigPreferences().getAdminEmail()); UserI user =TurbineUtils.getUser(data); - bt.setUser((UserI)user); + bt.setUser(user); String project = (String)TurbineUtils.GetPassedParameter("project", data); if (num !=null) { - for (int h=0;h<=num.intValue();h++) + for (int h = 0; h <= num; h++) { String sessionFolder = ((String)org.nrg.xdat.turbine.utils.TurbineUtils.GetPassedParameter("session" + h,data)); String match = ((String)org.nrg.xdat.turbine.utils.TurbineUtils.GetPassedParameter("match" + h,data)); @@ -82,7 +82,7 @@ public class MatchPrearchiveSessions extends SecureAction { SAXReader reader = new SAXReader(TurbineUtils.getUser(data)); XFTItem item = reader.parse(xml.getAbsolutePath()); - XnatImagesessiondata mr = (XnatImagesessiondata)XnatImagesessiondata.getXnatImagesessiondatasById(match, user, false); + XnatImagesessiondata mr = XnatImagesessiondata.getXnatImagesessiondatasById(match, user, false); int k = 0; while(TurbineUtils.HasPassedParameter("match" + h + ".scan" + k + "_id", data)){ @@ -90,10 +90,10 @@ public class MatchPrearchiveSessions extends SecureAction { String use = (String)TurbineUtils.GetPassedParameter("match" + h + ".scan" + k + "_use", data); String t = (String)TurbineUtils.GetPassedParameter("match" + h + ".scan" + k + "_type", data); - XnatImagescandata scan = (XnatImagescandata) mr.getScanById(id); + XnatImagescandata scan = mr.getScanById(id); if (scan==null){ XnatImagesessiondata tempMR= (XnatImagesessiondata)BaseElement.GetGeneratedItem(item); - scan =(XnatImagescandata)tempMR.getScanById(id); + scan = tempMR.getScanById(id); if (scan!=null){ mr.setScans_scan(scan); } diff --git a/src/main/java/org/nrg/xnat/turbine/modules/actions/PipelineActions.java b/src/main/java/org/nrg/xnat/turbine/modules/actions/PipelineActions.java index 942200b051ffcaa4582040e6315272e310e0881f..dc2d33e1201b41f9efc719c0646bf816b1f8a22f 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/actions/PipelineActions.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/actions/PipelineActions.java @@ -25,6 +25,7 @@ import org.apache.turbine.util.RunData; import org.apache.velocity.context.Context; import org.nrg.pipeline.PipelineManager; import org.nrg.pipeline.XnatPipelineLauncher; +import org.nrg.xdat.XDAT; import org.nrg.xdat.model.ArcPipelineparameterdataI; import org.nrg.xdat.om.WrkWorkflowdata; import org.nrg.xdat.turbine.modules.actions.SecureAction; @@ -108,7 +109,7 @@ public class PipelineActions extends SecureAction{ private XnatPipelineLauncher getGenericCommonParameters(RunData data, Context context, String projectId, String step, ItemI item) throws Exception { XnatPipelineLauncher xnatPipelineLauncher = new XnatPipelineLauncher(data,context); - xnatPipelineLauncher.setAdmin_email(AdminUtils.getAdminEmailId()); + xnatPipelineLauncher.setAdmin_email(XDAT.getSiteConfigPreferences().getAdminEmail()); xnatPipelineLauncher.setAlwaysEmailAdmin(ArcSpecManager.GetInstance().getEmailspecifications_pipeline()); UserI user = TurbineUtils.getUser(data); xnatPipelineLauncher.setNeedsBuildDir(true); @@ -185,7 +186,7 @@ public class PipelineActions extends SecureAction{ } } catch (Exception e){ logger.error("",e); - data.setMessage("<p><img src=\"/fcon/images/error.gif\">The build process failed to launch. Please contact the <a href=\"mailto:" + AdminUtils.getAdminEmailId() + "?subject=Failed to launch build \">NRG techdesk</a>"); + data.setMessage("<p><img src=\"/fcon/images/error.gif\">The build process failed to launch. Please contact the <a href=\"mailto:" + XDAT.getSiteConfigPreferences().getAdminEmail() + "?subject=Failed to launch build \">NRG techdesk</a>"); data.setScreenTemplate("Error.vm"); } } @@ -193,7 +194,7 @@ public class PipelineActions extends SecureAction{ private XnatPipelineLauncher getCommonParameters(RunData data, Context context, String projectId, String pipelineName, String step) throws Exception { XnatPipelineLauncher xnatPipelineLauncher = new XnatPipelineLauncher(data,context); - xnatPipelineLauncher.setAdmin_email(AdminUtils.getAdminEmailId()); + xnatPipelineLauncher.setAdmin_email(XDAT.getSiteConfigPreferences().getAdminEmail()); xnatPipelineLauncher.setAlwaysEmailAdmin(ArcSpecManager.GetInstance().getEmailspecifications_pipeline()); xnatPipelineLauncher.setPipelineName(pipelineName); UserI user = TurbineUtils.getUser(data); @@ -203,9 +204,9 @@ public class PipelineActions extends SecureAction{ xnatPipelineLauncher.setDataType("xnat:mrSessionData"); xnatPipelineLauncher.setParameter("useremail", user.getEmail()); xnatPipelineLauncher.setParameter("userfullname", XnatPipelineLauncher.getUserName(user)); - xnatPipelineLauncher.setParameter("adminemail", AdminUtils.getAdminEmailId()); + xnatPipelineLauncher.setParameter("adminemail", XDAT.getSiteConfigPreferences().getAdminEmail()); xnatPipelineLauncher.setParameter("xnatserver", TurbineUtils.GetSystemName()); - xnatPipelineLauncher.setParameter("mailhost", AdminUtils.getMailServer()); + xnatPipelineLauncher.setParameter("mailhost", XDAT.getSiteConfigPreferences().getSmtpServer().get("host")); String emailsStr = ((String)org.nrg.xdat.turbine.utils.TurbineUtils.GetPassedParameter("emailField",data)); if (emailsStr != null) { diff --git a/src/main/java/org/nrg/xnat/turbine/modules/actions/ProcessAccessRequest.java b/src/main/java/org/nrg/xnat/turbine/modules/actions/ProcessAccessRequest.java index c927eca91e4d87ff8b55854667e50abe9cb3cd1c..73d77bda5d7ff9af0b43c80246ef770a9911a9d1 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/actions/ProcessAccessRequest.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/actions/ProcessAccessRequest.java @@ -89,18 +89,18 @@ public class ProcessAccessRequest extends SecureAction { context.put("user",user); context.put("server",TurbineUtils.GetFullServerPath()); context.put("system",TurbineUtils.GetSystemName()); - context.put("admin_email",AdminUtils.getAdminEmailId()); + context.put("admin_email",XDAT.getSiteConfigPreferences().getAdminEmail()); context.put("projectOM",project); StringWriter sw = new StringWriter(); Template template =Velocity.getTemplate("/screens/RequestProjectAccessDenialEmail.vm"); template.merge(context,sw); String message= sw.toString(); - String from = AdminUtils.getAdminEmailId(); + String from = XDAT.getSiteConfigPreferences().getAdminEmail(); String subject = TurbineUtils.GetSystemName() + " Access Request for " + project.getName() + " Denied"; try { - XDAT.getMailService().sendHtmlMessage(from, other.getEmail(), user.getEmail(), AdminUtils.getAdminEmailId(), subject, message); + XDAT.getMailService().sendHtmlMessage(from, other.getEmail(), user.getEmail(), XDAT.getSiteConfigPreferences().getAdminEmail(), subject, message); } catch (Exception e) { logger.error("Unable to send mail",e); throw e; @@ -174,11 +174,11 @@ public class ProcessAccessRequest extends SecureAction { context.put("process","Transfer to the archive."); context.put("system",TurbineUtils.GetSystemName()); context.put("access_level",access_level); - context.put("admin_email",AdminUtils.getAdminEmailId()); + context.put("admin_email",XDAT.getSiteConfigPreferences().getAdminEmail()); context.put("projectOM",project); final ArrayList<String> ownerEmails = project.getOwnerEmails(); String[] projectOwnerEmails = ownerEmails.toArray(new String[ownerEmails.size()]); - SendAccessApprovalEmail(context,AdminUtils.getAdminEmailId(),new String[]{other.getEmail()},projectOwnerEmails,new String[]{AdminUtils.getAdminEmailId()},TurbineUtils.GetSystemName() + " Access Request for " + project.getName() + " Approved"); + SendAccessApprovalEmail(context,XDAT.getSiteConfigPreferences().getAdminEmail(),new String[]{other.getEmail()},projectOwnerEmails,new String[]{XDAT.getSiteConfigPreferences().getAdminEmail()},TurbineUtils.GetSystemName() + " Access Request for " + project.getName() + " Approved"); } //data.setScreenTemplate("XDATScreen_manage_xnat_projectData.vm"); //data.setScreenTemplate("/xnat_projectData/xnat_projectData_summary_management.vm"); @@ -188,7 +188,7 @@ public class ProcessAccessRequest extends SecureAction { } public static void SendAccessApprovalEmail(Context context, String otherEmail, UserI user, String subject) throws Exception { - String admin = AdminUtils.getAdminEmailId(); + String admin = XDAT.getSiteConfigPreferences().getAdminEmail(); SendAccessApprovalEmail(context, admin, new String[]{otherEmail}, new String[]{user.getEmail()}, new String[]{admin}, subject); } diff --git a/src/main/java/org/nrg/xnat/turbine/modules/actions/QDECAction.java b/src/main/java/org/nrg/xnat/turbine/modules/actions/QDECAction.java index a42b5801ba0f62963de1ec1aa53f4c5c831564e8..8d7262a6b1e097de386f91dded72f2086ac5ebbd 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/actions/QDECAction.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/actions/QDECAction.java @@ -32,6 +32,7 @@ import org.nrg.pipeline.xmlbeans.ParameterData; import org.nrg.pipeline.xmlbeans.ParameterData.Values; import org.nrg.pipeline.xmlbeans.ParametersDocument; import org.nrg.pipeline.xmlbeans.ParametersDocument.Parameters; +import org.nrg.xdat.XDAT; import org.nrg.xdat.search.DisplaySearch; import org.nrg.xdat.turbine.modules.actions.ListingAction; import org.nrg.xdat.turbine.utils.AdminUtils; @@ -106,7 +107,7 @@ public class QDECAction extends ListingAction{ //Launch the job String pipelineName = ((String)org.nrg.xdat.turbine.utils.TurbineUtils.GetPassedParameter("hdn_pipelinename",data)); XnatPipelineLauncher xnatPipelineLauncher = new XnatPipelineLauncher(data,context); - xnatPipelineLauncher.setAdmin_email(AdminUtils.getAdminEmailId()); + xnatPipelineLauncher.setAdmin_email(XDAT.getSiteConfigPreferences().getAdminEmail()); xnatPipelineLauncher.setAlwaysEmailAdmin(ArcSpecManager.GetInstance().getEmailspecifications_pipeline()); xnatPipelineLauncher.setPipelineName(pipelineName); xnatPipelineLauncher.setId(id); @@ -122,13 +123,13 @@ public class QDECAction extends ListingAction{ data.setMessage( "<p><b>Your QDEC analysis was successfully launched. Status email will be sent to you upon its completion.</b></p>"); data.setScreenTemplate("ClosePage.vm"); }catch(Exception e) { - data.setMessage("<p><b>The QDEC Analysis process could not be launched. Please contact <A HREF=\"mailto:"+AdminUtils.getAdminEmailId()+"?subject=Error: Performing QDEC Group Analysis" + "\">Report Error to" +TurbineUtils.GetSystemName() + " Techdesk</A></b></p>"); + data.setMessage("<p><b>The QDEC Analysis process could not be launched. Please contact <A HREF=\"mailto:"+XDAT.getSiteConfigPreferences().getAdminEmail()+"?subject=Error: Performing QDEC Group Analysis" + "\">Report Error to" +TurbineUtils.GetSystemName() + " Techdesk</A></b></p>"); data.setScreenTemplate("Error.vm"); } } private ArrayList<String> removeSpaces(ArrayList<String> inList) { - ArrayList<String> rtn = new ArrayList<String>(); + ArrayList<String> rtn = new ArrayList<>(); for (String aStr: inList) { rtn.add(StringUtils.deleteWhitespace(aStr)); } @@ -200,7 +201,7 @@ public class QDECAction extends ListingAction{ param = parameters.addNewParameter(); param.setName("adminemail"); - param.addNewValues().setUnique(AdminUtils.getAdminEmailId()); + param.addNewValues().setUnique(XDAT.getSiteConfigPreferences().getAdminEmail()); param = parameters.addNewParameter(); param.setName("xnatserver"); @@ -209,7 +210,7 @@ public class QDECAction extends ListingAction{ param = parameters.addNewParameter(); param.setName("mailhost"); - param.addNewValues().setUnique( AdminUtils.getMailServer()); + param.addNewValues().setUnique( XDAT.getSiteConfigPreferences().getSmtpServer().get("host")); return parameters; diff --git a/src/main/java/org/nrg/xnat/turbine/modules/actions/ReportIssue.java b/src/main/java/org/nrg/xnat/turbine/modules/actions/ReportIssue.java index 1a0582049fab4e51623f7296bb63b20096ed5dad..17dd0e7262d0f4275bf1d9b211e3018b00c7aa88 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/actions/ReportIssue.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/actions/ReportIssue.java @@ -48,7 +48,7 @@ public class ReportIssue extends SecureAction { @Override public void doPerform(RunData data, Context context) throws Exception { - final String adminEmail = XFT.GetAdminEmail(); + final String adminEmail = XDAT.getSiteConfigPreferences().getAdminEmail(); final UserI user = TurbineUtils.getUser(data); final ParameterParser parameters = data.getParameters(); diff --git a/src/main/java/org/nrg/xnat/turbine/modules/actions/RequestAccess.java b/src/main/java/org/nrg/xnat/turbine/modules/actions/RequestAccess.java index 8d6165a450ca2f2978ab042cf50ec54883960956..a769213b7db1808663707e604ff8c035f50c5e81 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/actions/RequestAccess.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/actions/RequestAccess.java @@ -49,7 +49,7 @@ public class RequestAccess extends SecureAction { context.put("server",TurbineUtils.GetFullServerPath()); context.put("process","Transfer to the archive."); context.put("system",TurbineUtils.GetSystemName()); - context.put("admin_email",AdminUtils.getAdminEmailId()); + context.put("admin_email",XDAT.getSiteConfigPreferences().getAdminEmail()); context.put("projectOM",project); context.put("access_level",access_level); context.put("comments",comments); @@ -81,10 +81,10 @@ public class RequestAccess extends SecureAction { String[] bcc = null; if(ArcSpecManager.GetInstance().getEmailspecifications_projectAccess()){ - bcc = new String[] { AdminUtils.getAdminEmailId() }; + bcc = new String[] { XDAT.getSiteConfigPreferences().getAdminEmail() }; } - String from = AdminUtils.getAdminEmailId(); + String from = XDAT.getSiteConfigPreferences().getAdminEmail(); String subject = TurbineUtils.GetSystemName() + " Access Request for " + project.getName(); try { diff --git a/src/main/java/org/nrg/xnat/turbine/modules/actions/SampleBuild.java b/src/main/java/org/nrg/xnat/turbine/modules/actions/SampleBuild.java index aae9fcdb7f1700e563185df7f74dd5130b314ade..79eef6cde872160d3026d5483c5a8aff9a1e65e8 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/actions/SampleBuild.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/actions/SampleBuild.java @@ -15,9 +15,9 @@ import org.apache.log4j.Logger; import org.apache.turbine.util.RunData; import org.apache.velocity.context.Context; import org.nrg.pipeline.XnatPipelineLauncher; +import org.nrg.xdat.XDAT; import org.nrg.xdat.om.XnatMrsessiondata; import org.nrg.xdat.turbine.modules.actions.SecureAction; -import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.ItemI; import org.nrg.xnat.turbine.utils.ArcSpecManager; @@ -37,17 +37,18 @@ public class SampleBuild extends SecureAction } String xnat = ((String)org.nrg.xdat.turbine.utils.TurbineUtils.GetPassedParameter("xnat",data)); XnatPipelineLauncher pipelineLauncher = new XnatPipelineLauncher(data,context); - pipelineLauncher.setAdmin_email(AdminUtils.getAdminEmailId()); + pipelineLauncher.setAdmin_email(XDAT.getSiteConfigPreferences().getAdminEmail()); pipelineLauncher.setAlwaysEmailAdmin(ArcSpecManager.GetInstance().getEmailspecifications_pipeline()); pipelineLauncher.setId(mr.getId()); pipelineLauncher.setDataType("xnat:mrSessionData"); pipelineLauncher.setPipelineName(pipelineName); pipelineLauncher.setParameter("sessionId",mr.getId()); pipelineLauncher.setParameter("xnat",xnat); - String emailsStr = TurbineUtils.getUser(data).getEmail() + "," + ((String)org.nrg.xdat.turbine.utils.TurbineUtils.GetPassedParameter("emailField",data)); + String emailsStr = XDAT.getUserDetails().getEmail() + "," + TurbineUtils.GetPassedParameter("emailField", data); String[] emails = emailsStr.trim().split(","); - for (int i = 0 ; i < emails.length; i++) - pipelineLauncher.notify(emails[i]); + for (final String email : emails) { + pipelineLauncher.notify(email); + } boolean success = pipelineLauncher.launch(); if (success) { data.setMessage("Build was launched successfully"); diff --git a/src/main/java/org/nrg/xnat/turbine/modules/actions/XDATRegisterUser.java b/src/main/java/org/nrg/xnat/turbine/modules/actions/XDATRegisterUser.java index ce98b18771f2b2458f751ebf0a9a161090d0bddf..b61c959281a8ef13a7567c88ec9bf8d04ab9862a 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/actions/XDATRegisterUser.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/actions/XDATRegisterUser.java @@ -94,13 +94,13 @@ public class XDATRegisterUser extends org.nrg.xdat.turbine.modules.actions.XDATR context.put("user", user); action.doPerform(data, context); } else if (!StringUtils.isEmpty(nextAction) && !nextAction.contains("XDATLoginUser") && !nextAction.equals(Turbine.getConfiguration().getString("action.login"))) { - if (XFT.GetUserRegistration() & !XDAT.verificationOn()) { + if (XDAT.getSiteConfigPreferences().getUserRegistration() & !XDAT.verificationOn()) { data.setAction(nextAction); VelocityAction action = (VelocityAction) ActionLoader.getInstance().getInstance(nextAction); action.doPerform(data, context); } } else if (!StringUtils.isEmpty(nextPage) && !nextPage.equals(Turbine.getConfiguration().getString("template.home"))) { - if (XFT.GetUserRegistration() && !XDAT.verificationOn()) { + if (XDAT.getSiteConfigPreferences().getUserRegistration() && !XDAT.verificationOn()) { data.setScreenTemplate(nextPage); } } diff --git a/src/main/java/org/nrg/xnat/turbine/modules/screens/BuildPipelineParameters.java b/src/main/java/org/nrg/xnat/turbine/modules/screens/BuildPipelineParameters.java index a93e8e809d5a151575ba5b5e6da21b47aedf9970..709dd0bb80be4d4597947e4952251f33d857ca4b 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/screens/BuildPipelineParameters.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/screens/BuildPipelineParameters.java @@ -13,14 +13,13 @@ package org.nrg.xnat.turbine.modules.screens; import org.apache.turbine.util.RunData; import org.apache.velocity.context.Context; +import org.nrg.xdat.XDAT; import org.nrg.xdat.om.XnatMrsessiondata; import org.nrg.xdat.turbine.modules.screens.SecureReport; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.XFT; -public class BuildPipelineParameters extends SecureReport -{ - +public class BuildPipelineParameters extends SecureReport { public void preProcessing(RunData data, Context context) { TurbineUtils.InstanciatePassedItemForScreenUse(data,context); @@ -55,7 +54,7 @@ public class BuildPipelineParameters extends SecureReport return; }catch(Exception e) { String errorString = "<img src=\"/cnda1/images/error.gif\"> Error in the Build Spec file document for the pipeline " + context.get("pipelineName") ; - errorString += "<p>Please contact the <a href=\"mailto:"+XFT.GetAdminEmail()+"?subject=Error in Build Spec file for " + mr.getSessionType() + " pipeline " + pipelineName + "\">CNL techdesk</a> to resolve the error.</p>"; + errorString += "<p>Please contact the <a href=\"mailto:"+XDAT.getSiteConfigPreferences().getAdminEmail()+"?subject=Error in Build Spec file for " + mr.getSessionType() + " pipeline " + pipelineName + "\">CNL techdesk</a> to resolve the error.</p>"; data.setMessage(errorString); data.getParameters().add("exception",e.getMessage()); data.setScreenTemplate("Error.vm"); diff --git a/src/main/java/org/nrg/xnat/turbine/modules/screens/DefaultPipelineScreen.java b/src/main/java/org/nrg/xnat/turbine/modules/screens/DefaultPipelineScreen.java index db9a989c8034e9e9306182acdf8541a25e9cac6d..91d8afebd4ca08e77feb7fae0aaea0ae8426f815 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/screens/DefaultPipelineScreen.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/screens/DefaultPipelineScreen.java @@ -303,15 +303,7 @@ public abstract class DefaultPipelineScreen extends SecureReport { Configuration config = XDAT.getConfigService().getConfig(toolName, fileName, Scope.Project, project); if (config != null && config.getContents() != null) { - String scanTypeCsv = config.getContents().trim(); - List<String> scanTypeList = Lists.transform(Lists.newArrayList(scanTypeCsv.split(",")), new Function<String, String>() { - @Override - public String apply(String input) { - return input.trim(); - } - }); - - return ((XnatImagesessiondata) om).getScansByTypeList(scanTypeList); + return ((XnatImagesessiondata) om).getScansByTypeCsv(config.getContents().trim()); } else { return Lists.newArrayList(); } diff --git a/src/main/java/org/nrg/xnat/turbine/modules/screens/PipelineScreen.java b/src/main/java/org/nrg/xnat/turbine/modules/screens/PipelineScreen.java index adf02c39a2cbc606a9d91a7df714f84828a56dfb..73ecbe0b7c4df1f27f4ce8a09b835b715f62835f 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/screens/PipelineScreen.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/screens/PipelineScreen.java @@ -16,6 +16,7 @@ import org.apache.turbine.util.RunData; import org.apache.velocity.app.FieldMethodizer; import org.apache.velocity.context.Context; import org.nrg.pipeline.PipelineManager; +import org.nrg.xdat.XDAT; import org.nrg.xdat.base.BaseElement; import org.nrg.xdat.model.ArcProjectPipelineI; import org.nrg.xdat.model.WrkAbstractexecutionenvironmentI; @@ -252,7 +253,7 @@ public abstract class PipelineScreen extends SecureReport { } } if (rtn == null) { - message = "Pipeline with step id " + pipeline_step + " is not defined. Please contact your site administrator <a href=\"mailto:" +XFT.GetAdminEmail() +"?subject=Invalid Pipeline Step " + pipeline_step + " for " + item.getXSIType() + "\">Report problem</A>"; + message = "Pipeline with step id " + pipeline_step + " is not defined. Please contact your site administrator <a href=\"mailto:" + XDAT.getSiteConfigPreferences().getAdminEmail() + "?subject=Invalid Pipeline Step " + pipeline_step + " for " + item.getXSIType() + "\">Report problem</A>"; } return rtn; } diff --git a/src/main/java/org/nrg/xnat/turbine/modules/screens/PipelineScreen_set_site_parameters.java b/src/main/java/org/nrg/xnat/turbine/modules/screens/PipelineScreen_set_site_parameters.java index 3745e506f4811fb26f04e84e2bd31e8b1c2a6dbe..d53b11b3be94338bf511d9c202e74377c72fb6ca 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/screens/PipelineScreen_set_site_parameters.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/screens/PipelineScreen_set_site_parameters.java @@ -19,12 +19,12 @@ import org.nrg.pipeline.xmlbeans.PipelineData.Documentation.InputParameters; import org.nrg.pipeline.xmlbeans.PipelineData.Documentation.InputParameters.Parameter; import org.nrg.pipeline.xmlbeans.PipelineData.Documentation.InputParameters.Parameter.Values; import org.nrg.pipeline.xmlbeans.PipelineDocument; +import org.nrg.xdat.XDAT; import org.nrg.xdat.om.PipePipelinedetails; import org.nrg.xdat.om.PipePipelinedetailsParameter; import org.nrg.xdat.om.PipePipelinerepository; import org.nrg.xdat.turbine.modules.screens.AdminEditScreenA; import org.nrg.xdat.turbine.utils.TurbineUtils; -import org.nrg.xft.XFT; import org.nrg.xft.event.EventUtils; import org.nrg.xft.security.UserI; import org.nrg.xft.utils.SaveItemHelper; @@ -81,14 +81,14 @@ public class PipelineScreen_set_site_parameters extends AdminEditScreenA{ data.setMessage("The pipeline has been added to the repository"); data.setScreenTemplate("ClosePage.vm"); } catch (Exception e) { - data.setMessage("The pipeline could not be added to the repository. Please contact " + XFT.GetAdminEmail() ); + data.setMessage("The pipeline could not be added to the repository. Please contact " + XDAT.getSiteConfigPreferences().getAdminEmail() ); data.setScreenTemplate("Error.vm"); } } }catch(Exception e) { logger.error(e); e.printStackTrace(); - data.setMessage("The pipeline could not be added to the repository. Please contact " + XFT.GetAdminEmail() ); + data.setMessage("The pipeline could not be added to the repository. Please contact " + XDAT.getSiteConfigPreferences().getAdminEmail()); data.setScreenTemplate("Error.vm"); } } diff --git a/src/main/java/org/nrg/xnat/turbine/modules/screens/XDATScreen_UpdateUser.java b/src/main/java/org/nrg/xnat/turbine/modules/screens/XDATScreen_UpdateUser.java index c524493f5cb5c42517d7a85d86707f1601f11887..bbe5853cbcf632eb7aba1d6c8ccc8ffeb74eaf8e 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/screens/XDATScreen_UpdateUser.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/screens/XDATScreen_UpdateUser.java @@ -46,22 +46,14 @@ public class XDATScreen_UpdateUser extends SecureScreen { } c.put("user", XDAT.getUserDetails()); - if (TurbineUtils.GetPassedParameter("popup", data) != null) { - if (((String) TurbineUtils.GetPassedParameter("popup", data)).equalsIgnoreCase("true")) { - c.put("popup", "true"); - } else { - c.put("popup", "false"); - } - } else { - c.put("popup", "false"); - } + checkForPopup(data, c); c.put("displayManager", DisplayManager.GetInstance()); c.put("systemName", TurbineUtils.GetSystemName()); c.put("esc", new EscapeTool()); - c.put("showReason", XFT.getShowChangeJustification()); - c.put("requireReason", XFT.getRequireChangeJustification()); + c.put("showReason", XDAT.getSiteConfigPreferences().getShowChangeJustification()); + c.put("requireReason", XDAT.getSiteConfigPreferences().getRequireChangeJustification()); try{ c.put("siteConfig", XDAT.getSiteConfiguration()); }catch(ConfigServiceException ignored){ diff --git a/src/main/java/org/nrg/xnat/turbine/utils/ArcSpecManager.java b/src/main/java/org/nrg/xnat/turbine/utils/ArcSpecManager.java index 53820e7e6e35ef2302d3a05678fcbf98e496faca..c39e128942e2ea2c4644712e08926c1c9ea141b7 100644 --- a/src/main/java/org/nrg/xnat/turbine/utils/ArcSpecManager.java +++ b/src/main/java/org/nrg/xnat/turbine/utils/ArcSpecManager.java @@ -61,131 +61,129 @@ public class ArcSpecManager { logger.info("Initializing ArcSpec..."); arcSpec = GetFreshInstance(); - if (arcSpec!=null){ - - if (arcSpec.getSiteAdminEmail()!=null && !arcSpec.getSiteAdminEmail().equals("")){ - XFT.SetAdminEmail(arcSpec.getSiteAdminEmail()); - }else{ - arcSpec.setSiteAdminEmail(XFT.GetAdminEmail()); - } - - if (arcSpec.getSiteUrl()!=null && !arcSpec.getSiteUrl().equals("")){ - XFT.SetSiteURL(arcSpec.getSiteUrl()); - }else{ - arcSpec.setSiteUrl(XFT.GetSiteURL()); - } - - if (arcSpec.getSiteId()!=null && !arcSpec.getSiteId().equals("")){ - XFT.SetSiteID(arcSpec.getSiteId()); - }else{ - arcSpec.setSiteId(""); - } - - if (arcSpec.getSmtpHost()!=null && !arcSpec.getSmtpHost().equals("")){ - XFT.SetAdminEmailHost(arcSpec.getSmtpHost()); - }else{ - arcSpec.setSmtpHost(XFT.GetAdminEmailHost()); - } - - if (arcSpec.getEnableNewRegistrations()!=null){ - XFT.SetUserRegistration(arcSpec.getEnableNewRegistrations().toString()); - }else{ - arcSpec.setEnableNewRegistrations(XFT.GetUserRegistration()); - } - - if (arcSpec.getRequireLogin()!=null){ - XFT.SetRequireLogin(arcSpec.getRequireLogin().toString()); - }else{ - arcSpec.setRequireLogin(XFT.GetRequireLogin()); - } - - if (arcSpec.getGlobalpaths()!=null && arcSpec.getGlobalpaths().getPipelinepath()!=null){ - XFT.SetPipelinePath(arcSpec.getGlobalpaths().getPipelinepath()); - }else{ - if (arcSpec.getGlobalpaths()!=null){ - arcSpec.getGlobalpaths().setPipelinepath(XFT.GetPipelinePath()); - } - } - - if (arcSpec.getGlobalpaths()!=null && arcSpec.getGlobalpaths().getArchivepath()!=null){ - XFT.SetArchiveRootPath(arcSpec.getGlobalpaths().getArchivepath()); - }else{ - if (arcSpec.getGlobalpaths()!=null && XFT.GetArchiveRootPath()!=null){ - arcSpec.getGlobalpaths().setArchivepath(XFT.GetArchiveRootPath()); - } - } - - if (arcSpec.getGlobalpaths()!=null && arcSpec.getGlobalpaths().getCachepath()!=null){ - XFT.SetCachePath(arcSpec.getGlobalpaths().getCachepath()); - }else{ - if (arcSpec.getGlobalpaths()!=null && XFT.GetCachePath()!=null){ - arcSpec.getGlobalpaths().setCachepath(XFT.GetCachePath()); - } - } - - if (arcSpec.getGlobalpaths()!=null && arcSpec.getGlobalpaths().getFtppath()!=null){ - XFT.setFtpPath(arcSpec.getGlobalpaths().getFtppath()); - }else{ - if (arcSpec.getGlobalpaths()!=null && XFT.getFtpPath()!=null){ - arcSpec.getGlobalpaths().setFtppath(XFT.getFtpPath()); - } - } - - if (arcSpec.getGlobalpaths()!=null && arcSpec.getGlobalpaths().getBuildpath()!=null){ - XFT.setFtpPath(arcSpec.getGlobalpaths().getBuildpath()); - }else{ - if (arcSpec.getGlobalpaths()!=null && XFT.getBuildPath()!=null){ - arcSpec.getGlobalpaths().setBuildpath(XFT.getBuildPath()); - } - } - - if (arcSpec.getGlobalpaths()!=null && arcSpec.getGlobalpaths().getPrearchivepath()!=null){ - XFT.SetPrearchivePath(arcSpec.getGlobalpaths().getPrearchivepath()); - }else{ - if (arcSpec.getGlobalpaths()!=null && XFT.GetPrearchivePath()!=null){ - arcSpec.getGlobalpaths().setPrearchivepath(XFT.GetPrearchivePath()); - } - } - - - //set email defaults - if (arcSpec.getEmailspecifications_newUserRegistration()==null){ - arcSpec.setEmailspecifications_newUserRegistration(true); - } - if (arcSpec.getEmailspecifications_pageEmail()==null){ - arcSpec.setEmailspecifications_pageEmail(true); - } - if (arcSpec.getEmailspecifications_pipeline()==null){ - arcSpec.setEmailspecifications_pipeline(true); - } - if (arcSpec.getEmailspecifications_projectAccess()==null){ - arcSpec.setEmailspecifications_projectAccess(true); - } - if (arcSpec.getEmailspecifications_transfer()==null){ - arcSpec.setEmailspecifications_transfer(true); - } - //end email defaults - - if (arcSpec.getEmailspecifications_newUserRegistration()!=null){ - AdminUtils.SetNewUserRegistrationsEmail(arcSpec.getEmailspecifications_newUserRegistration()); - } - - if (arcSpec.getEmailspecifications_pageEmail()!=null){ - AdminUtils.SetPageEmail(arcSpec.getEmailspecifications_pageEmail()); - } - - if (arcSpec.getDcm_appletLink()==null){ - arcSpec.setDcm_appletLink(Boolean.TRUE); - } - - if (arcSpec.getEnableCsrfToken()!=null){ - XFT.SetEnableCsrfToken(arcSpec.getEnableCsrfToken().toString()); - }else{ - arcSpec.setEnableCsrfToken(XFT.GetEnableCsrfToken()); - } - - - } +// if (arcSpec!=null){ +// +// if (arcSpec.getSiteAdminEmail()!=null && !arcSpec.getSiteAdminEmail().equals("")){ +// XFT.SetAdminEmail(arcSpec.getSiteAdminEmail()); +// }else{ +// arcSpec.setSiteAdminEmail(XDAT.getSiteConfigPreferences().getAdminEmail()); +// } +// +// if (arcSpec.getSiteUrl()!=null && !arcSpec.getSiteUrl().equals("")){ +// XFT.SetSiteURL(arcSpec.getSiteUrl()); +// }else{ +// arcSpec.setSiteUrl(XDAT.getSiteConfigPreferences().getSiteUrl()); +// } +// +// if (arcSpec.getSiteId()!=null && !arcSpec.getSiteId().equals("")){ +// XFT.SetSiteID(arcSpec.getSiteId()); +// }else{ +// arcSpec.setSiteId(""); +// } +// +// if (arcSpec.getSmtpHost()!=null && !arcSpec.getSmtpHost().equals("")){ +// XFT.SetAdminEmailHost(arcSpec.getSmtpHost()); +// }else{ +// arcSpec.setSmtpHost(XFT.GetAdminEmailHost()); +// } +// +// if (arcSpec.getEnableNewRegistrations()!=null){ +// XFT.SetUserRegistration(arcSpec.getEnableNewRegistrations().toString()); +// }else{ +// arcSpec.setEnableNewRegistrations(XDAT.getSiteConfigPreferences().getUserRegistration()); +// } +// +// if (arcSpec.getRequireLogin()!=null){ +// XFT.SetRequireLogin(arcSpec.getRequireLogin().toString()); +// }else{ +// arcSpec.setRequireLogin(XDAT.getSiteConfigPreferences().getRequireLogin()); +// } +// +// if (arcSpec.getGlobalpaths()!=null && arcSpec.getGlobalpaths().getPipelinepath()!=null){ +// XFT.SetPipelinePath(arcSpec.getGlobalpaths().getPipelinepath()); +// }else{ +// if (arcSpec.getGlobalpaths()!=null){ +// arcSpec.getGlobalpaths().setPipelinepath(XDAT.getSiteConfigPreferences().getAdminEmail()); +// } +// } +// +// if (arcSpec.getGlobalpaths()!=null && arcSpec.getGlobalpaths().getArchivepath()!=null){ +// XFT.SetArchiveRootPath(arcSpec.getGlobalpaths().getArchivepath()); +// }else{ +// if (arcSpec.getGlobalpaths()!=null && XFT.GetArchiveRootPath()!=null){ +// arcSpec.getGlobalpaths().setArchivepath(XFT.GetArchiveRootPath()); +// } +// } +// +// if (arcSpec.getGlobalpaths()!=null && arcSpec.getGlobalpaths().getCachepath()!=null){ +// XFT.SetCachePath(arcSpec.getGlobalpaths().getCachepath()); +// }else{ +// if (arcSpec.getGlobalpaths()!=null && XDAT.getSiteConfigPreferences().getCachePath()!=null){ +// arcSpec.getGlobalpaths().setCachepath(XDAT.getSiteConfigPreferences().getCachePath()); +// } +// } +// +// if (arcSpec.getGlobalpaths()!=null && arcSpec.getGlobalpaths().getFtppath()!=null){ +// XFT.setFtpPath(arcSpec.getGlobalpaths().getFtppath()); +// }else{ +// if (arcSpec.getGlobalpaths()!=null && XFT.getFtpPath()!=null){ +// arcSpec.getGlobalpaths().setFtppath(XFT.getFtpPath()); +// } +// } +// +// if (arcSpec.getGlobalpaths()!=null && arcSpec.getGlobalpaths().getBuildpath()!=null){ +// XFT.setFtpPath(arcSpec.getGlobalpaths().getBuildpath()); +// }else{ +// if (arcSpec.getGlobalpaths()!=null && XFT.getBuildPath()!=null){ +// arcSpec.getGlobalpaths().setBuildpath(XFT.getBuildPath()); +// } +// } +// +// if (arcSpec.getGlobalpaths()!=null && arcSpec.getGlobalpaths().getPrearchivepath()!=null){ +// XFT.SetPrearchivePath(arcSpec.getGlobalpaths().getPrearchivepath()); +// }else{ +// if (arcSpec.getGlobalpaths()!=null && XFT.GetPrearchivePath()!=null){ +// arcSpec.getGlobalpaths().setPrearchivepath(XFT.GetPrearchivePath()); +// } +// } +// +// +// //set email defaults +// if (arcSpec.getEmailspecifications_newUserRegistration()==null){ +// arcSpec.setEmailspecifications_newUserRegistration(true); +// } +// if (arcSpec.getEmailspecifications_pageEmail()==null){ +// arcSpec.setEmailspecifications_pageEmail(true); +// } +// if (arcSpec.getEmailspecifications_pipeline()==null){ +// arcSpec.setEmailspecifications_pipeline(true); +// } +// if (arcSpec.getEmailspecifications_projectAccess()==null){ +// arcSpec.setEmailspecifications_projectAccess(true); +// } +// if (arcSpec.getEmailspecifications_transfer()==null){ +// arcSpec.setEmailspecifications_transfer(true); +// } +// //end email defaults +// +// if (arcSpec.getEmailspecifications_newUserRegistration()!=null){ +// AdminUtils.SetNewUserRegistrationsEmail(arcSpec.getEmailspecifications_newUserRegistration()); +// } +// +// if (arcSpec.getEmailspecifications_pageEmail()!=null){ +// AdminUtils.SetPageEmail(arcSpec.getEmailspecifications_pageEmail()); +// } +// +// if (arcSpec.getDcm_appletLink()==null){ +// arcSpec.setDcm_appletLink(Boolean.TRUE); +// } +// +// if (arcSpec.getEnableCsrfToken()!=null){ +// XFT.SetEnableCsrfToken(arcSpec.getEnableCsrfToken().toString()); +// }else{ +// arcSpec.setEnableCsrfToken(XDAT.getSiteConfigPreferences().getEnableCsrfToken()); +// } +// } try { if (arcSpec!=null){ @@ -228,45 +226,45 @@ public class ArcSpecManager { public synchronized static ArcArchivespecification initialize(UserI user) throws XFTInitException, ElementNotFoundException, FieldNotFoundException, InvalidValueException { arcSpec = new ArcArchivespecification(user); - if (XFT.GetAdminEmail()!=null && !XFT.GetAdminEmail().equals("")) { - arcSpec.setSiteAdminEmail(XFT.GetAdminEmail()); + if (XDAT.getSiteConfigPreferences().getAdminEmail()!=null && !XDAT.getSiteConfigPreferences().getAdminEmail().equals("")) { + arcSpec.setSiteAdminEmail(XDAT.getSiteConfigPreferences().getAdminEmail()); } - if (XFT.GetSiteURL()!=null && !XFT.GetSiteURL().equals("")) { - arcSpec.setSiteUrl(XFT.GetSiteURL()); + if (XDAT.getSiteConfigPreferences().getSiteUrl()!=null && !XDAT.getSiteConfigPreferences().getSiteUrl().equals("")) { + arcSpec.setSiteUrl(XDAT.getSiteConfigPreferences().getSiteUrl()); } - if (XFT.GetAdminEmailHost()!=null && !XFT.GetAdminEmailHost().equals("")) { - arcSpec.setSmtpHost(XFT.GetAdminEmailHost()); - } - - arcSpec.setEnableNewRegistrations(XFT.GetUserRegistration()); - - arcSpec.setRequireLogin(XFT.GetRequireLogin()); - if (XFT.GetPipelinePath()!=null && !XFT.GetPipelinePath().equals("")) { - arcSpec.setProperty("globalPaths/pipelinePath", XFT.GetPipelinePath()); - } - - if (XFT.GetArchiveRootPath()!=null && !XFT.GetArchiveRootPath().equals("")) { - arcSpec.setProperty("globalPaths/archivePath", XFT.GetArchiveRootPath()); - } - - if (XFT.GetPrearchivePath()!=null && !XFT.GetPrearchivePath().equals("")) { - arcSpec.setProperty("globalPaths/prearchivePath", XFT.GetPrearchivePath()); - } - - if (XFT.GetCachePath()!=null && !XFT.GetCachePath().equals("")) { - arcSpec.setProperty("globalPaths/cachePath", XFT.GetCachePath()); - } - - if (XFT.getFtpPath()!=null && !XFT.getFtpPath().equals("")) { - arcSpec.setProperty("globalPaths/ftpPath", XFT.getFtpPath()); - } - - if (XFT.getBuildPath()!=null && !XFT.getBuildPath().equals("")) { - arcSpec.setProperty("globalPaths/buildPath", XFT.getBuildPath()); - } - arcSpec.setEnableCsrfToken(XFT.GetEnableCsrfToken()); +// if (XFT.GetAdminEmailHost()!=null && !XFT.GetAdminEmailHost().equals("")) { +// arcSpec.setSmtpHost(XFT.GetAdminEmailHost()); +// } +// +// arcSpec.setEnableNewRegistrations(XDAT.getSiteConfigPreferences().getUserRegistration()); +// +// arcSpec.setRequireLogin(XDAT.getSiteConfigPreferences().getRequireLogin()); +// if (XDAT.getSiteConfigPreferences().getAdminEmail()!=null && !XDAT.getSiteConfigPreferences().getAdminEmail().equals("")) { +// arcSpec.setProperty("globalPaths/pipelinePath", XDAT.getSiteConfigPreferences().getAdminEmail()); +// } +// +// if (XFT.GetArchiveRootPath()!=null && !XFT.GetArchiveRootPath().equals("")) { +// arcSpec.setProperty("globalPaths/archivePath", XFT.GetArchiveRootPath()); +// } +// +// if (XFT.GetPrearchivePath()!=null && !XFT.GetPrearchivePath().equals("")) { +// arcSpec.setProperty("globalPaths/prearchivePath", XFT.GetPrearchivePath()); +// } +// +// if (XDAT.getSiteConfigPreferences().getCachePath()!=null && !XDAT.getSiteConfigPreferences().getCachePath().equals("")) { +// arcSpec.setProperty("globalPaths/cachePath", XDAT.getSiteConfigPreferences().getCachePath()); +// } +// +// if (XFT.getFtpPath()!=null && !XFT.getFtpPath().equals("")) { +// arcSpec.setProperty("globalPaths/ftpPath", XFT.getFtpPath()); +// } +// +// if (XFT.getBuildPath()!=null && !XFT.getBuildPath().equals("")) { +// arcSpec.setProperty("globalPaths/buildPath", XFT.getBuildPath()); +// } +// arcSpec.setEnableCsrfToken(XFT.GetEnableCsrfToken()); return arcSpec; } diff --git a/src/main/java/org/nrg/xnat/turbine/utils/IDGenerator.java b/src/main/java/org/nrg/xnat/turbine/utils/IDGenerator.java index a1a066810915a5d8867963a3b50a37bd5dd972fd..d71c1d7d92b67625ffa55fc8a7df7e8453de7d60 100644 --- a/src/main/java/org/nrg/xnat/turbine/utils/IDGenerator.java +++ b/src/main/java/org/nrg/xnat/turbine/utils/IDGenerator.java @@ -11,7 +11,7 @@ package org.nrg.xnat.turbine.utils; import org.apache.commons.lang3.StringUtils; -import org.nrg.xft.XFT; +import org.nrg.xdat.XDAT; import org.nrg.xft.XFTTable; import org.nrg.xft.identifier.IDGeneratorI; import org.nrg.xnat.services.impl.hibernate.HibernateHostInfoService; @@ -53,7 +53,7 @@ public class IDGenerator implements IDGeneratorI { } /** The claimed i ds. */ - private static List<String> claimedIDs=new ArrayList<String>(); + private static List<String> claimedIDs= new ArrayList<>(); /** The Constant lock. */ private static final Object lock=new Object(); @@ -80,7 +80,7 @@ public class IDGenerator implements IDGeneratorI { site +="_V"; } - String temp_id=null; + String temp_id; XFTTable table = org.nrg.xft.search.TableSearch.Execute("SELECT DISTINCT " + column + " FROM (SELECT " + column + " FROM " + tableName + " WHERE " + column + " LIKE '" + site + "%' UNION SELECT DISTINCT " + column + " FROM " + tableName + "_history WHERE " + column + " LIKE '" + site + "%') SRCH;", null, null); ArrayList al =table.convertColumnToArrayList(column.toLowerCase()); @@ -171,7 +171,7 @@ public class IDGenerator implements IDGeneratorI { * @return the site id */ private String getSiteID(){ - String site_id = XFT.GetSiteID(); + String site_id = XDAT.getSiteConfigPreferences().getSiteId(); site_id = StringUtils.replace(site_id, " ", ""); site_id = StringUtils.replace(site_id, "-", "_"); site_id = StringUtils.replace(site_id, "\"", ""); diff --git a/src/main/java/org/nrg/xnat/turbine/utils/ProjectAccessRequest.java b/src/main/java/org/nrg/xnat/turbine/utils/ProjectAccessRequest.java index 08d261b0ba7af174a1471c8accd3096c46e4d4f9..660bb8c04853765661e93c76d8285af02dc5c1f0 100644 --- a/src/main/java/org/nrg/xnat/turbine/utils/ProjectAccessRequest.java +++ b/src/main/java/org/nrg/xnat/turbine/utils/ProjectAccessRequest.java @@ -486,10 +486,10 @@ public class ProjectAccessRequest { String bcc = null; if (ArcSpecManager.GetInstance().getEmailspecifications_projectAccess()) { - bcc = AdminUtils.getAdminEmailId(); + bcc = XDAT.getSiteConfigPreferences().getAdminEmail(); } - String from = AdminUtils.getAdminEmailId(); + String from = XDAT.getSiteConfigPreferences().getAdminEmail(); try { XDAT.getMailService().sendHtmlMessage(from, invitee, user.getEmail(), bcc, subject, writer.toString()); diff --git a/src/main/java/org/nrg/xnat/utils/FileUtils.java b/src/main/java/org/nrg/xnat/utils/FileUtils.java index 1234010afc69c4b7df6767774ca236a100b2dd6c..d7c11066ea1b93394de2d8af094fa54516f0b79f 100644 --- a/src/main/java/org/nrg/xnat/utils/FileUtils.java +++ b/src/main/java/org/nrg/xnat/utils/FileUtils.java @@ -13,6 +13,7 @@ package org.nrg.xnat.utils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.nrg.xdat.XDAT; import org.nrg.xft.XFT; import java.io.BufferedReader; @@ -27,7 +28,7 @@ public class FileUtils { public static void moveToCache(final String project, final String subdir, final File src) throws IOException { // should include a timestamp in folder name if (src.exists()) { - final File cache = (StringUtils.isBlank(subdir)) ? new File(XFT.GetCachePath(), project) : new File(new File(XFT.GetCachePath(), project), subdir); + final File cache = (StringUtils.isBlank(subdir)) ? new File(XDAT.getSiteConfigPreferences().getCachePath(), project) : new File(new File(XDAT.getSiteConfigPreferences().getCachePath(), project), subdir); final File dest = new File(cache, org.nrg.xft.utils.FileUtils.renameWTimestamp(src.getName(), Calendar.getInstance().getTime())); @@ -38,7 +39,7 @@ public class FileUtils { public static File buildCachepath(String project, final String subdir, final String destName) { if (project == null) project = "Unknown"; - final File cache = (StringUtils.isEmpty(subdir)) ? new File(XFT.GetCachePath(), project) : new File(new File(XFT.GetCachePath(), project), subdir); + final File cache = (StringUtils.isEmpty(subdir)) ? new File(XDAT.getSiteConfigPreferences().getCachePath(), project) : new File(new File(XDAT.getSiteConfigPreferences().getCachePath(), project), subdir); return new File(cache, org.nrg.xft.utils.FileUtils.renameWTimestamp(destName, Calendar.getInstance().getTime())); } @@ -144,7 +145,7 @@ public class FileUtils { @SafeVarargs public static <T extends String> File buildCacheSubDir(T... directories) { - File last = new File(XFT.GetCachePath()); + File last = new File(XDAT.getSiteConfigPreferences().getCachePath()); for (final String dir : directories) { if (!StringUtils.isEmpty(dir)) { diff --git a/src/main/resources/META-INF/xnat/spawner/site-admin-elements.yaml b/src/main/resources/META-INF/xnat/spawner/site-admin-elements.yaml index a36dea2ddd51796e2f1cfcfca33354f2dd334e0e..84bcb3dc5c485cf07665a5e522e0b8152492207d 100644 --- a/src/main/resources/META-INF/xnat/spawner/site-admin-elements.yaml +++ b/src/main/resources/META-INF/xnat/spawner/site-admin-elements.yaml @@ -16,10 +16,10 @@ siteId: label: Site ID validation: required id onblur description: "The id used to refer to this site (also used to generate database ids). The Site ID must start with a letter and contain only letters, numbers and underscores. It should be a short, one-word name or acronym which describes your site. No spaces or non-alphanumeric characters." -siteDescriptionOption: +siteDescriptionType: kind: panel.display # make this a radio button group - id: siteDescriptionOption - name: siteDescriptionOption + id: siteDescriptionType + name: siteDescriptionType label: Site Description value: Select a site description option below # onchange: # some javascript that toggles display of the elements below appropriately @@ -31,10 +31,10 @@ siteDescriptionOptionPage: kind: panel.input.checkbox # make this a radio button group id: siteDescriptionOptionPage label: "Page" -siteDescriptionFile: +siteDescriptionPage: kind: panel.input.text - id: siteDescriptionFile - name: siteDescriptionFile + id: siteDescriptionPage + name: siteDescriptionPage label: " " description: "Specify a velocity template file to display on the login page" siteDescriptionText: @@ -43,6 +43,26 @@ siteDescriptionText: name: siteDescriptionText label: " " description: "Specify a simple text description of this site" +siteLoginLanding: + kind: panel.input.text + id: siteLoginLanding + name: siteLoginLanding + label: Site Login Landing +siteLandingLayout: + kind: panel.input.text + id: siteLandingLayout + name: siteLandingLayout + label: Site Landing Layout +siteHome: + kind: panel.input.text + id: siteHome + name: siteHome + label: Site Home +siteHomeLayout: + kind: panel.input.text + id: siteHomeLayout + name: siteHomeLayout + label: Site Home Layout siteUrl: kind: panel.input.text id: siteUrl @@ -120,6 +140,11 @@ dataFolders: label: Data Folders validation: required id onblur description: "" +zipExtensions: + kind: panel.input.text + id: zipExtensions + name: zipExtensions + label: Zip Extensions siteInfo: kind: panel.form @@ -133,11 +158,15 @@ siteInfo: contents: ${siteId} ${siteUrl} - ${siteDescriptionOption} + ${siteDescriptionType} ${siteDescriptionOptionText} ${siteDescriptionOptionPage} - ${siteDescriptionFile} + ${siteDescriptionPage} ${siteDescriptionText} + ${siteLoginLanding} + ${siteLandingLayout} + ${siteHome} + ${siteHomeLayout} adminInfo: kind: panel.form @@ -154,7 +183,7 @@ generalSecuritySettings: securityChannel: kind: panel.select.single id: securityChannel - name: security.channel + name: securityChannel label: Security Channel value: https options: @@ -167,7 +196,7 @@ generalSecuritySettings: requireUserLogin: kind: panel.input.checkbox id: requireUserLogin - name: require_login + name: requireLogin label: Require User Login description: "If checked, then only registered users will be able to access your site. If false, anyone visiting your site will automatically be logged in as 'guest' with access to public data." @@ -184,7 +213,7 @@ userLoginsSessionControls: sessionTimeout: kind: panel.input.number id: sessionTimeout - name: security.token_timeout + name: aliasTokenTimeout label: Session Timeout value: 15 description: "Interval for timing out alias tokens. Uses PostgreSQL interval notation: http://www.postgresql.org/docs/9.0/static/functions-datetime.html" @@ -226,17 +255,22 @@ userLoginsSessionControls: failedLoginLockoutDuration: kind: panel.input.number id: failedLoginLockoutDuration - name: security.max_failed_logins_lockout_duration + name: maxFailedLoginsLockoutDuration label: Failed Login Lockout Duration value: 0 description: Number of milliseconds to lock user accounts that have exceeded the max_failed_logins count. Select (3600000 for 1 hour, 86400000 for 24 hours) userInactivityLockout: kind: panel.input.number id: userInactivityLockout - name: security.inactivity_before_lockout + name: inactivityBeforeLockout label: User Inactivity Lockout value: 31556926 description: Number of seconds of inactivity before an account is disabled (31556926 for 1 year) + inactivityBeforeLockoutSchedule: + kind: panel.input.text + id: inactivityBeforeLockoutSchedule + name: inactivityBeforeLockoutSchedule + label: "User Inactivity Before Lockout Schedule" passwords: kind: panel.form @@ -268,6 +302,19 @@ passwords: label: Password History (Duration) value: -1 description: "-1 to disable" + passwordExpirationType: + kind: panel.select.single + id: passwordExpirationType + name: passwordExpirationType + label: passwordExpirationType + value: Interval + options: + Interval: + label: Interval + value: Interval + Date: + label: Date + value: Date passwordExpirationInterval: kind: panel.input.number id: passwordExpirationInterval @@ -320,24 +367,49 @@ auditTrail: enableAuditTrail: kind: panel.input.checkbox id: enableAuditTrail - name: audit.enable + name: enableAuditTrail label: Enable Audit Trail? value: true allowUserJustificationForChanges: kind: panel.input.checkbox id: allowUserJustificationForChanges - name: audit.show_change_justification + name: allowUserJustificationForChanges label: Allow User Justification For Changes value: true description: "Allow users to enter change justifications when modifying data" requireUserJustificationForChanges: kind: panel.input.checkbox id: requireUserJustificationForChanges - name: audit.require_change_justification + name: requireUserJustificationForChanges label: Require User Justification For Changes value: false description: "Force users to enter change justifications when modifying data" +securityServices: + kind: panel.form + name: securityServices + label: Security Services + contents: + securityServicesFeatureDefault: + kind: panel.input.text + id: securityServicesFeatureDefault + name: security.services.feature.default + label: Feature Default + securityServicesFeatureRepoDefault: + kind: panel.input.text + id: securityServicesFeatureRepoDefault + name: security.services.featureRepository.default + label: Feature Repository Default + securityServicesRoleDefault: + kind: panel.input.text + id: securityServicesRoleDefault + name: security.services.role.default + label: Role Default + securityServicesRoleRepositoryDefault: + kind: panel.input.text + id: securityServicesRoleRepositoryDefault + name: security.services.roleRepository.default + label: Role Repository Default emailServerSettings: kind: panel.form @@ -352,6 +424,13 @@ emailServerSettings: name: emailServerSettings label: Mail Server Settings contents: + smtpEnabled: + kind: panel.input.checkbox + id: smtpEnabled + name: smtp.enabled + label: "Enable SMTP?" + #value: true + checked: true hostname: kind: panel.input.text name: host @@ -409,6 +488,12 @@ emailServerSettings: value: '' element: placeholder: localhost + emailPrefix: + kind: panel.input.text + name: emailPrefix + label: Email Prefix + element: + placeholder: XNAT notifications: kind: panel.form @@ -441,62 +526,61 @@ notifications: notifyAdminUserRegistration: kind: panel.input.checkbox id: notifyAdminUserRegistration - name: "email:new_user_registration" + name: notifyAdminUserRegistration label: "Notify Admin on User Registration" value: true description: "Whether to cc admin user on new user emails. Requires valid admin email address." notifyAdminPipelineEmails: kind: panel.input.checkbox id: notifyAdminPipelineEmails - name: "email:pipeline" + name: notifyAdminPipelineEmails label: "Notify Admin on Pipeline Emails" value: false description: "Whether to cc admin user on pipeline processing submit. Requires valid admin email address." notifyAdminProjectAccessRequest: kind: panel.input.checkbox id: notifyAdminProjectAccessRequest - name: "email:project_access" + name: notifyAdminProjectAccessRequest label: "Notify Admin on Project Access Request" value: false description: "Whether to cc admin user on user project access request. Requires valid admin email address." notifyAdminSessionTransfer: kind: panel.input.checkbox id: notifyAdminSessionTransfer - name: "email:transfer" + name: notifyAdminSessionTransfer label: "Notify Admin on Session Transfer" value: false description: "Whether to cc admin user on session transfer by user. Requires valid admin email address." emailRecipientErrorMessages: kind: panel.input.email id: emailRecipientErrorMessages - name: "Notifications:Error" + name: emailRecipientErrorMessages label: "Email Recipient: Error Messages" description: "What email address should receive error emails" emailRecipientIssueReports: kind: panel.input.email id: emailRecipientIssueReports - name: "Notifications:Issues" + name: emailRecipientIssueReports label: "Email Recipient: Issue Reports" description: "What email address should receive issue reports" emailRecipientNewUserAlert: kind: panel.input.email id: emailRecipientNewUserAlert - name: "Notifications:NewUser" + name: emailRecipientNewUserAlert label: "Email Recipient: New User Alert" description: "What email address should receive New User Registration emails" emailRecipientUpdate: kind: panel.input.email id: emailRecipientUpdate - name: "Notifications:Update" + name: emailRecipientUpdate label: "Email Recipient: Updates" description: "What email address should receive update emails" - notifyAdminSessionTransfer: + emailAllowNonuserSubscribers: kind: panel.input.checkbox - id: notifyAdminSessionTransfer - name: "email:transfer" - label: "Notify Admin on Session Transfer" - value: false - description: "Whether to cc admin user on session transfer by user. Requires valid admin email address." + id: emailAllowNonuserSubscribers + name: emailAllowNonuserSubscribers + label: "Allow Nonuser Subscribers" + value: true themeManagement: kind: panel @@ -537,9 +621,7 @@ themeManagement: label: Upload a theme package description: Upload a zipped theme package for selection above. className: themeUploader - - authenticationMethods: kind: panel.form name: authenticationMethods @@ -641,11 +723,19 @@ userRoles: label: User Roles # contents: + registrationOptions: kind: panel.form name: registrationOptions label: Registration Options contents: + requireLogin: + kind: panel.input.checkbox + id: requireLogin + name: requireLogin + label: "Require User?" + value: true + disabled: true requireEmailVerificationToRegister: kind: panel.input.checkbox id: requireEmailVerificationToRegister @@ -667,7 +757,7 @@ registrationOptions: autoEnableUserRegistration: kind: panel.input.checkbox id: autoEnableUserRegistration - name: autoEnableUserRegistration + name: userRegistration label: "Auto-enable User Registration?" value: false allowUserCommentsOnRegistration: @@ -676,18 +766,17 @@ registrationOptions: name: allowUserCommentsOnRegistration label: "Allow User Comments on Registration?" value: true - restrictAccessToUserList: + restrictUserListAccessToAdmins: kind: panel.input.checkbox - id: restrictAccessToUserList - name: restrictAccessToUserList - label: "Restrict Access to User List?" + id: restrictUserListAccessToAdmins + name: restrictUserListAccessToAdmins + label: "Restrict User List Access To Admins?" value: true dataReporting: kind: panel.form name: dataReporting label: Data Reporting - group: manageData contents: enableAdvancedSearch: kind: panel.input.checkbox @@ -696,10 +785,128 @@ dataReporting: label: "Enable Advanced Search" value: true +manageDataTypes: + kind: panel.form + name: manageDataTypes + label: Manage Data Types + method: POST + action: /xapi/siteConfig/batch + load: + lookup: XNAT.data.siteConfig + contentType: json + contents: + displayNameForGenericImageSessionSingular: + kind: panel.input.text + id: displayNameForGenericImageSessionSingular + name: displayNameForGenericImageSession.singular + label: "Singular Display Name For Generic Image Session Singular" + value: "Session" + displayNameForGenericImageSessionPlural: + kind: panel.input.text + id: displayNameForGenericImageSessionPlural + name: displayNameForGenericImageSession.plural + label: "Plural Display Name For Generic Image Session Singular" + value: "Sessions" + +anonymization: + kind: panel.form + name: Anonymization + label: "Anonymization Script (Site Wide)" + contents: + enableSitewideAnonymizationScript: + kind: panel.input.checkbox + id: enableSitewideAnonymizationScript + name: enableSitewideAnonymizationScript + label: "Enable Site-wide Anonymization Script" + value: true + editAnonymzationScript: + kind: panel.input.text #textarea + id: editAnonymzationScript + name: editAnonymzationScript + label: "Edit Anonymzation Script" + value: true + +seriesImportFilter: + kind: panel.form + name: seriesImportFilter + label: "Series Import Filter" + contents: + enableSitewideSeriesImportFilter: + kind: panel.input.checkbox + id: enableSitewideSeriesImportFilter + name: enableSitewideSeriesImportFilter + label: "Enable Site-wide Series Import Filter" + value: false + filterMode: + kind: panel.input.checkbox + id: filterMode + name: filterMode + label: Filter Mode + value: false + seriesImportFilter: + kind: panel.input.text #textarea + id: seriesImportFilter + name: seriesImportFilter + label: "Edit Series Import Filter" + +sessionUploadMethod: + kind: panel.form + name: sessionUploadMethod + label: "Session Upload Method" + contents: + selectUploadMethod: + kind: panel.select.single + id: selectUploadMethod + name: selectUploadMethod + label: "Session Upload Method" +# options: # don't know where to populate this from +# http: +# label: http +# value: http +# https: +# label: https +# value: https + showApplet: + kind: panel.input.checkbox + id: showApplet + name: showApplet + label: Show Applet + value: false + enableProjectAppletScript: + kind: panel.input.checkbox + id: enableProjectAppletScript + name: enableProjectAppletScript + label: Enable Project Applet Script + value: false + appletScript: + kind: panel.input.text #textarea + id: appletScript + name: appletScript + label: "Applet Script" + sessionXmlRebuilderRepeat: + kind: panel.input.number + id: sessionXmlRebuilderRepeat + name: sessionXmlRebuilderRepeat + label: Session Xml Rebuilder Repeat + value: 60000 + sessionXmlRebuilderInterval: + kind: panel.input.number + id: sessionXmlRebuilderInterval + name: sessionXmlRebuilderInterval + label: Session Xml Rebuilder Interval + value: 5 + + dicomScpReceivers: kind: panel.form name: dicomScpReceivers label: DICOM SCP Receivers + method: POST + action: /xapi/dicomscp + load: + url: /xapi/dicomscp +# prop: # Not set, so should get the root object + contentType: json contents: enableDicomReceiver: kind: panel.input.checkbox @@ -714,9 +921,12 @@ dicomScpReceivers: html: "Caution: Changes to this setting will take effect immediately. Before disabling the receiver, verify that there are no transmissions currently in progress." style: fontWeight: bold - # hidden form element... - # enableDicomReceiver.property.changed.listener - # org.nrg.dcm.DicomSCPSiteConfigurationListener + enableDicomReceiverPropertyChangedListener: # Should this be a hidden form element?? + kind: panel.input.text + id: enableDicomReceiverPropertyChangedListener + name: enableDicomReceiverPropertyChangedListener # Should this be "enableDicomReceiver.property.changed.listener" + label: "Enable Dicom Receiver Property Changed Listener" + value: "org.nrg.dcm.DicomSCPSiteConfigurationListener" dicomHost: kind: panel.input.text id: dicomHost @@ -741,12 +951,12 @@ dicomScpReceivers: name: services.dicom.scp.aetitle label: Default DICOM Receiver description: "AE Title for default DICOM receiver" - defaultDicomReceiverUser: + receivedFileUser: kind: panel.input.text - id: defaultDicomReceiverUser - name: services.dicom.scp.receivedfileuser + id: receivedFileUser + name: receivedFileUser label: "Default DICOM Receiver: User" - value: Login failed + value: admin description: "User account for default DICOM receiver" fileSystem: @@ -766,7 +976,37 @@ fileSystem: ${buildPath} ${pipelinePath} ${dataFolders} + ${zipExtensions} +misc: + kind: panel.form + name: misc + label: Miscellaneous + method: POST + action: /xapi/siteConfig/batch + load: + lookup: XNAT.data.siteConfig + contentType: json + contents: + checksums: + kind: panel.input.checkbox + id: checksums + name: checksums + label: Checksums? + value: true + checksumsPropertyChangedListener: + kind: panel.input.text + id: checksumsPropertyChangedListener + name: checksums.property.changed.listener + label: Checksums Property Changed Listener? + value: org.nrg.xnat.utils.ChecksumsSiteConfigurationListener + scanTypeMapping: + kind: panel.input.checkbox + id: scanTypeMapping + name: scanTypeMapping + label: Scan Type Mapping? + value: true + ################################################# #### Root Site Admin Spawner Config Object #### @@ -800,6 +1040,7 @@ siteAdmin: ${passwords} ${csrf} ${auditTrail} + ${securityServices} emailServer: kind: tab name: emailServer @@ -830,20 +1071,20 @@ siteAdmin: ${authenticationMethods} ${genericAuthenticationProvider} ${ldapAuthentication} - users: - kind: tab - name: users - label: Users - group: manageAccess - contents: - ${users} - userRoles: - kind: tab - name: userRoles - label: User Roles - group: manageAccess - contents: - ${userRoles} +# users: # enable when users table can be re-implmented in spawner, until then use old users config? +# kind: tab +# name: users +# label: Users +# group: manageAccess +# contents: +# ${users} +# userRoles: # enable when user roles table can be re-implmented in spawner, until then use old user roles config? +# kind: tab +# name: userRoles +# label: User Roles +# group: manageAccess +# contents: +# ${userRoles} registrationOptions: kind: tab name: registrationOptions @@ -858,6 +1099,22 @@ siteAdmin: group: manageData contents: ${dataReporting} + manageDataTypes: + kind: tab + name: manageDataTypes + label: Manage Data Types + group: manageData + contents: + ${manageDataTypes} + sessionUploadImportAnonymization: + kind: tab + name: sessionUploadImportAnonymization + label: "Session Upload, Import & Anonymization" + group: manageData + contents: + ${anonymization} + ${seriesImportFilter} + ${sessionUploadMethod} dicomScpReceivers: kind: tab name: dicomScpReceivers @@ -873,6 +1130,13 @@ siteAdmin: contents: ${fileSystem} ${siteIdMain} + misc: + kind: tab + name: misc + label: Miscellaneous +# group: misc # should show up under Other + contents: + ${misc} ########################################### diff --git a/src/main/webapp/WEB-INF/conf/xnat-security.xml b/src/main/webapp/WEB-INF/conf/xnat-security.xml index 0491f1fd7de06683845ad6ca0b03aec13568d29e..5ec44a3b884f4364b7b234350173e0e0a530d6c0 100644 --- a/src/main/webapp/WEB-INF/conf/xnat-security.xml +++ b/src/main/webapp/WEB-INF/conf/xnat-security.xml @@ -111,8 +111,6 @@ <value>/app/template/VerificationSent.vm*</value> <value>/app/template/VerifyEmail.vm*</value> <value>/favicon.ico</value> - <value>/data/version</value> - <value>/REST/version</value> <value>/data/JSESSION</value> <value>/REST/JSESSION</value> <value>/data/services/auth*</value> diff --git a/src/main/webapp/scripts/ezCalendar.js b/src/main/webapp/scripts/ezCalendar.js index a1e0828c1b31f9d44af3ecf713cf9f9f302d5d83..b27b9acc59718dc18ba23f4b8d51f475064c73e3 100644 --- a/src/main/webapp/scripts/ezCalendar.js +++ b/src/main/webapp/scripts/ezCalendar.js @@ -641,7 +641,7 @@ $(function(){ var $input = $(input); var format = XNAT.app.utils.getValueByClass($input,['iso','us','eu','euro']); var val = $input.val(); - if (val === ('__/__/____' || '____-__-__' || '')){ + if (val === '__/__/____' || val === '____-__-__' || val === ''){ $input.val(''); return false; } diff --git a/src/main/webapp/scripts/footer.js b/src/main/webapp/scripts/footer.js index 98590d8ac31767d4ba254ddc8eeb2f76a5764c07..46c5372245ab91414e00378904aaf158b7ae1d68 100644 --- a/src/main/webapp/scripts/footer.js +++ b/src/main/webapp/scripts/footer.js @@ -534,9 +534,13 @@ $(function(){ // add version to title attribute of XNAT logos if (typeof logged_in != 'undefined' && logged_in == true){ - $.get(serverRoot+'/data/version',function(data){ - XNAT_version = data.split(" ")[0]; - $('#xnat_power').find('a').attr('title','XNAT version ' + XNAT_version).after('<small>version ' + XNAT_version + '</small>'); + $.get(serverRoot+'/xapi/siteConfig/buildInfo',function(data){ + XNAT_version = data.version + " build: " + data.buildNumber; + var isNonRelease = /.*(SNAPSHOT|BETA|RC).*/.test(data.version); + if (isNonRelease) { + XNAT_version += " (" + data.commit + ")"; + } + $('#xnat_power').find('a').attr('title','XNAT version ' + XNAT_version).after('<small>version ' + XNAT_version + (isNonRelease ? "<br>" + data.buildDate : "") + '</small>'); $('#header_logo').attr('title','XNAT version ' + XNAT_version); XNAT.app.version = XNAT_version ; }); diff --git a/src/main/webapp/scripts/timeLeft.js b/src/main/webapp/scripts/timeLeft.js index 4239784a57d9581a21dfc0b02e51820ba1e71a33..0572060ebb0d57968a315ff6437cece0b8b9882f 100644 --- a/src/main/webapp/scripts/timeLeft.js +++ b/src/main/webapp/scripts/timeLeft.js @@ -180,7 +180,7 @@ if (typeof XNAT.app.timeout == 'undefined'){ XNAT.app.timeout={} } timeout.handleOk = function () { timeout.hideWarningDialog(timeout.warningDialog); timeout.touchCallback.startTime = new Date().getTime(); - XNAT.xhr.get(XNAT.url.restUrl('/data/version'), timeout.touchCallback); + XNAT.xhr.get(XNAT.url.restUrl('/xapi/siteConfig/buildInfo'), timeout.touchCallback); $('applet').css('visibility', 'visible'); };