diff --git a/.gitignore b/.gitignore index 6e5956be34ca49f52d3bd28d2fef9132e9d9f1db..44ff23c741683b074980da87b7c973e05c9a0734 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ gradle.properties InstanceSettings.xml src/main/resources/META-INF/xnat/auth MANIFEST.MF +/ide-bin/ diff --git a/build.gradle b/build.gradle index ec3573df40a56479ac853add71a98f0f9ab1e4bf..73dade74c8031bc8a68fbb3d8072b19d7b3bd761 100644 --- a/build.gradle +++ b/build.gradle @@ -254,6 +254,7 @@ configurations { all*.exclude group: 'servletapi' all*.exclude group: 'velocity' all*.exclude group: 'xmlrpc' + all*.exclude group: 'quartz' all*.exclude group: 'ant', module: 'ant' all*.exclude group: 'commons-email', module: 'commons-email' all*.exclude group: 'edu.ucar', module: 'netcdf' @@ -366,6 +367,7 @@ dependencies { compile "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:${vJackson}" compile "com.fasterxml.jackson.datatype:jackson-datatype-hibernate4:${vJackson}" compile "org.json:json:20151123" + compile "com.thoughtworks.xstream:xstream:1.4.9" compile "xerces:xercesImpl:2.11.0" compile "commons-beanutils:commons-beanutils:1.9.2" diff --git a/src/main/java/org/nrg/xapi/rest/XapiRestControllerAdvice.java b/src/main/java/org/nrg/xapi/rest/XapiRestControllerAdvice.java new file mode 100644 index 0000000000000000000000000000000000000000..07a3712cb27ee04f502ce0c8d5f5316eb420532d --- /dev/null +++ b/src/main/java/org/nrg/xapi/rest/XapiRestControllerAdvice.java @@ -0,0 +1,87 @@ +package org.nrg.xapi.rest; + +import org.nrg.dcm.exceptions.EnabledDICOMReceiverWithDuplicatePortException; +import org.nrg.framework.exceptions.NrgServiceError; +import org.nrg.framework.exceptions.NrgServiceException; +import org.nrg.framework.exceptions.NrgServiceRuntimeException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import java.io.FileNotFoundException; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.List; + +@ControllerAdvice +public class XapiRestControllerAdvice { + @ExceptionHandler(EnabledDICOMReceiverWithDuplicatePortException.class) + public ModelAndView handleEnabledDICOMReceiverWithDuplicatePort(final HttpServletRequest request, final EnabledDICOMReceiverWithDuplicatePortException exception) { + return handleException(request, exception.getMessage()); + } + + @ExceptionHandler(NrgServiceException.class) + public ModelAndView handleNrgServiceException(final HttpServletRequest request, final NrgServiceException exception) { + return handleException(HttpStatus.CONFLICT, request, "An NRG service error occurred.", exception); + } + + @ExceptionHandler(URISyntaxException.class) + public ModelAndView handleUriSyntaxException(final HttpServletRequest request, final URISyntaxException exception) { + final String message = "An error occurred at index " + exception.getIndex() + " when processing the URI " + exception.getInput() + ": " + exception.getMessage(); + return handleException(HttpStatus.BAD_REQUEST, request, message); + } + + @ExceptionHandler(FileNotFoundException.class) + public ModelAndView handleFileNotFoundException(final HttpServletRequest request, final FileNotFoundException exception) { + return handleException(HttpStatus.BAD_REQUEST, request, "Unable to find requested file or resource: " + exception.getMessage(), exception); + } + + private ModelAndView handleException(final HttpServletRequest request, final String message) { + return handleException(request, message, null); + } + + private ModelAndView handleException(final HttpServletRequest request, final String message, final Exception exception) { + final ResponseStatus status = AnnotationUtils.findAnnotation(exception.getClass(), ResponseStatus.class); + if (status == null) { + throw new NrgServiceRuntimeException(NrgServiceError.ConfigurationError, "Only exceptions with @ResponseStatus annotation can be handled through this method.", exception); + } + return handleException(status.value(), request, message, exception); + } + + private ModelAndView handleException(final HttpStatus status, final HttpServletRequest request, final String message) { + return handleException(status, request, message, null); + } + + private ModelAndView handleException(final HttpStatus status, final HttpServletRequest request, final String message, final Exception exception) { + @SuppressWarnings("SpringMVCViewInspection") + final ModelAndView modelAndView = new ModelAndView("error"); + modelAndView.addObject("status", status); + modelAndView.addObject("url", request.getRequestURL().toString()); + modelAndView.addObject("message", message); + if (exception != null) { + modelAndView.addObject("exception", exception); + final StackTraceElement[] stackTrace = exception.getStackTrace(); + if (stackTrace != null && stackTrace.length > 1) { + final List<String> elements = new ArrayList<>(); + for (final StackTraceElement element : stackTrace) { + elements.add(element.toString()); + if (element.toString().startsWith("javax.servlet.http.HttpServlet.service")) { + elements.add("(stack trace truncated for readability, see server logs for full "); + break; + } + } + modelAndView.addObject("stacktrace", elements); + } + } + _log.error("An exception was encountered", exception); + return modelAndView; + } + + private static final Logger _log = LoggerFactory.getLogger(XapiRestControllerAdvice.class); +} diff --git a/src/main/java/org/nrg/xapi/rest/dicomscp/DicomSCPApiAdvice.java b/src/main/java/org/nrg/xapi/rest/dicomscp/DicomSCPApiAdvice.java deleted file mode 100644 index 910e7a4008550bb7b077e47ac9bdbcbebd0dd97e..0000000000000000000000000000000000000000 --- a/src/main/java/org/nrg/xapi/rest/dicomscp/DicomSCPApiAdvice.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.nrg.xapi.rest.dicomscp; - -import org.nrg.dcm.exceptions.EnabledDICOMReceiverWithDuplicatePortException; -import org.nrg.framework.exceptions.NrgServiceException; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; - -@ControllerAdvice -public class DicomSCPApiAdvice { - @ExceptionHandler(EnabledDICOMReceiverWithDuplicatePortException.class) - public ResponseEntity<String> handleEnabledDICOMReceiverWithDuplicatePort(final EnabledDICOMReceiverWithDuplicatePortException exception) { - return new ResponseEntity<>(exception.getMessage(), HttpStatus.CONFLICT); - } - - @ExceptionHandler(NrgServiceException.class) - public ResponseEntity<String> handleNrgServiceException(final NrgServiceException exception) { - return new ResponseEntity<>(exception.getMessage(), HttpStatus.CONFLICT); - } -} diff --git a/src/main/java/org/nrg/xapi/rest/schemas/SchemaApi.java b/src/main/java/org/nrg/xapi/rest/schemas/SchemaApi.java new file mode 100644 index 0000000000000000000000000000000000000000..f2f8d38161924f4e822487148929c868415e13c0 --- /dev/null +++ b/src/main/java/org/nrg/xapi/rest/schemas/SchemaApi.java @@ -0,0 +1,81 @@ +package org.nrg.xapi.rest.schemas; + +import com.google.common.base.Joiner; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.apache.commons.io.FilenameUtils; +import org.nrg.framework.annotations.XapiRestController; +import org.nrg.framework.utilities.BasicXnatResourceLocator; +import org.nrg.xdat.rest.AbstractXapiRestController; +import org.nrg.xdat.security.services.RoleHolder; +import org.nrg.xdat.security.services.UserManagementServiceI; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.xml.sax.SAXException; + +import javax.xml.parsers.ParserConfigurationException; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +@Api(description = "XNAT Data Type Schemas API") +@XapiRestController +@RequestMapping(value = "/schemas") +public class SchemaApi extends AbstractXapiRestController { + @Autowired + public SchemaApi(final UserManagementServiceI userManagementService, final RoleHolder roleHolder) { + super(userManagementService, roleHolder); + } + + @ApiOperation(value = "Returns a list of all of the installed XNAT data-type schemas.", notes = "The strings returned from this function tell you the name of the schema and can be used with other methods on this API to retrieve the full schema document. This tells you nothing about whether the data types defined in the schemas are active or configured.", response = String.class, responseContainer = "List") + @ApiResponses({@ApiResponse(code = 200, message = "XNAT data-type schemas successfully retrieved."), + @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), + @ApiResponse(code = 500, message = "Unexpected error")}) + @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE}, method = {RequestMethod.GET}) + public ResponseEntity<List<String>> getAllDataTypeSchemas() throws IOException { + final List<String> schemas = new ArrayList<>(); + for (final Resource resource : BasicXnatResourceLocator.getResources("classpath*:schemas/*/*.xsd")) { + final Set<String> schemaPath = new LinkedHashSet<>(Arrays.asList(FilenameUtils.removeExtension(resource.getURI().toString().replaceAll("^.*/schemas/", "")).split("/"))); + schemas.add(Joiner.on("/").join(schemaPath)); + } + return new ResponseEntity<>(schemas, HttpStatus.OK); + } + + @ApiOperation(value = "Returns the requested XNAT data-type schema.", notes = "XNAT data-type schemas are most often stored on the classpath in the folder schemas/SCHEMA/SCHEMA.xsd. This function returns the schema named SCHEMA.xsd in the folder named SCHEMA. You can use the function that allows you to specify the namespace as well if the folder name differs from the schema name. This tells you nothing about whether the data types defined in the schemas are active or configured.", response = String.class) + @ApiResponses({@ApiResponse(code = 200, message = "XNAT data-type schemas successfully retrieved."), + @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), + @ApiResponse(code = 404, message = "The requested resource wasn't found."), + @ApiResponse(code = 500, message = "Unexpected error")}) + @RequestMapping(value = "{schema}", produces = {MediaType.APPLICATION_XML_VALUE}, method = {RequestMethod.GET}) + public ResponseEntity<String> getRequestedDataTypeSchema(@PathVariable("schema") final String schema) throws IOException, ParserConfigurationException, SAXException { + return getRequestedDataTypeSchema(schema, schema); + } + + @ApiOperation(value = "Returns the requested XNAT data-type schema.", notes = "XNAT data-type schemas are most often stored on the classpath in the folder schemas/SCHEMA/SCHEMA.xsd, but sometimes the folder name differs from the schema name. This function returns the schema named SCHEMA.xsd in the folder named NAMESPACE. This tells you nothing about whether the data types defined in the schemas are active or configured.", response = String.class) + @ApiResponses({@ApiResponse(code = 200, message = "XNAT data-type schemas successfully retrieved."), + @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), + @ApiResponse(code = 404, message = "The requested resource wasn't found."), + @ApiResponse(code = 500, message = "Unexpected error")}) + @RequestMapping(value = "{namespace}/{schema}", produces = {MediaType.APPLICATION_XML_VALUE}, method = {RequestMethod.GET}) + // TODO: Eventually these should return XML Document objects that are appropriately converted. Spring doesn't have a converter for that by default. + public ResponseEntity<String> getRequestedDataTypeSchema(@PathVariable("namespace") final String namespace, @PathVariable("schema") final String schema) throws IOException, ParserConfigurationException, SAXException { + final Resource resource = BasicXnatResourceLocator.getResource("classpath:schemas/" + namespace + "/" + schema + ".xsd"); + if (resource == null || !resource.exists()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + if (!resource.isReadable()) { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } + try (final InputStream input = resource.getInputStream()) { + return new ResponseEntity<>(new Scanner(input, "UTF-8").useDelimiter("\\A").next(), HttpStatus.OK); + } + } +} \ No newline at end of file diff --git a/src/main/java/org/nrg/xapi/rest/settings/XnatPluginApi.java b/src/main/java/org/nrg/xapi/rest/settings/XnatPluginApi.java new file mode 100644 index 0000000000000000000000000000000000000000..71e9471a2cacad604c878436d5d3139b8ae032f5 --- /dev/null +++ b/src/main/java/org/nrg/xapi/rest/settings/XnatPluginApi.java @@ -0,0 +1,58 @@ +package org.nrg.xapi.rest.settings; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.nrg.framework.annotations.XapiRestController; +import org.nrg.xdat.rest.AbstractXapiRestController; +import org.nrg.xdat.security.services.RoleHolder; +import org.nrg.xdat.security.services.UserManagementServiceI; +import org.nrg.xnat.services.XnatAppInfo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import java.io.IOException; +import java.util.Map; +import java.util.Properties; + +@Api(description = "XNAT Plugin API") +@XapiRestController +@RequestMapping(value = "/plugins") +public class XnatPluginApi extends AbstractXapiRestController { + @Autowired + public XnatPluginApi(final UserManagementServiceI userManagementService, final RoleHolder roleHolder, final XnatAppInfo appInfo) { + super(userManagementService, roleHolder); + _appInfo = appInfo; + } + + @ApiOperation(value = "Returns a list of all of the installed and active XNAT plugins with their properties.", notes = "The maps returned from this call include all of the properties specified in the plugin's property file.", response = String.class, responseContainer = "Map") + @ApiResponses({@ApiResponse(code = 200, message = "XNAT plugin properties successfully retrieved."), + @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), + @ApiResponse(code = 500, message = "Unexpected error")}) + @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE}, method = {RequestMethod.GET}) + public ResponseEntity<Map<String, Properties>> getAllDataTypeSchemas() throws IOException { + return new ResponseEntity<>(_appInfo.getPluginProperties(), HttpStatus.OK); + } + + @ApiOperation(value = "Returns the indicated XNAT plugin with its properties.", notes = "The map returned from this call include all of the properties specified in the plugin's property file.", response = Properties.class) + @ApiResponses({@ApiResponse(code = 200, message = "XNAT plugin properties successfully retrieved."), + @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), + @ApiResponse(code = 404, message = "The requested resource wasn't found."), + @ApiResponse(code = 500, message = "Unexpected error")}) + @RequestMapping(value = "{plugin}", produces = {MediaType.APPLICATION_JSON_VALUE}, method = {RequestMethod.GET}) + public ResponseEntity<Properties> getRequestedDataTypeSchema(@PathVariable("plugin") final String plugin) throws IOException { + final Map<String, Properties> plugins = _appInfo.getPluginProperties(); + if (!plugins.containsKey(plugin)) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + return new ResponseEntity<>(plugins.get(plugin), HttpStatus.OK); + } + + private final XnatAppInfo _appInfo; +} \ No newline at end of file diff --git a/src/main/java/org/nrg/xnat/archive/XNATSessionBuilder.java b/src/main/java/org/nrg/xnat/archive/XNATSessionBuilder.java index 722d55f72b1c565df4325465b34e35dc494e5bb1..3db2657044f3151ea75f3df4e41e64352729c25e 100644 --- a/src/main/java/org/nrg/xnat/archive/XNATSessionBuilder.java +++ b/src/main/java/org/nrg/xnat/archive/XNATSessionBuilder.java @@ -28,7 +28,10 @@ import org.nrg.xdat.turbine.utils.PropertiesHelper; import org.nrg.xft.XFT; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean; +import javax.annotation.Nonnull; import java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -185,7 +188,7 @@ public class XNATSessionBuilder implements Callable<Boolean> { * <p/> * The iteration will stop once it successfully builds an xml (or runs out of builder configs). * - * @throws IOException + * @throws IOException When something goes wrong writing the session XML. */ @SuppressWarnings("unchecked") public Boolean call() throws IOException { @@ -293,13 +296,23 @@ public class XNATSessionBuilder implements Callable<Boolean> { private static ExecutorService _executorService = null; - public static ExecutorService getExecutor() { + private static ExecutorService getExecutor() { if (_executorService == null) { - PropertiesHelper.ImplLoader<ExecutorService> loader = new PropertiesHelper.ImplLoader<>(_executorFileName, _executorIdentifier); try { - _executorService = loader.buildNoArgs(Executors.newFixedThreadPool(PropertiesHelper.GetIntegerProperty(_executorFileName, _executorIdentifier + ".size", 2))); - } catch (IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchMethodException | InvocationTargetException | InstantiationException | ConfigurationException e) { - logger.error("An error occurred trying to build the executor based on the file name " + _executorFileName + " and identifier " + _executorIdentifier, e); + final ThreadPoolExecutorFactoryBean factory = XDAT.getContextService().getBean(ThreadPoolExecutorFactoryBean.class); + if (factory != null) { + _executorService = factory.getObject(); + } + } catch (NoSuchBeanDefinitionException ignored) { + // We can just ignore this since we have a fallback method. + } + if (_executorService == null) { + final PropertiesHelper.ImplLoader<ExecutorService> loader = new PropertiesHelper.ImplLoader<>(_executorFileName, _executorIdentifier); + try { + _executorService = loader.buildNoArgs(Executors.newFixedThreadPool(PropertiesHelper.GetIntegerProperty(_executorFileName, _executorIdentifier + ".size", 2))); + } catch (IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchMethodException | InvocationTargetException | InstantiationException | ConfigurationException e) { + logger.error("An error occurred trying to build the executor based on the file name " + _executorFileName + " and identifier " + _executorIdentifier, e); + } } } @@ -311,7 +324,7 @@ public class XNATSessionBuilder implements Callable<Boolean> { protected Class c; protected Integer order; - public BuilderConfig(final String code, final Class c, final Integer order) { + BuilderConfig(final String code, final Class c, final Integer order) { if (code == null) throw new NullPointerException(); if (c == null) throw new NullPointerException(); @@ -321,10 +334,7 @@ public class XNATSessionBuilder implements Callable<Boolean> { } @Override - public int compareTo(Object object) { - if (object == null) { - throw new NullPointerException(); - } + public int compareTo(@Nonnull final Object object) { if (!BuilderConfig.class.isAssignableFrom(object.getClass())) { throw new ClassCastException("Can't cast from " + object.getClass().getName() + " to " + BuilderConfig.class.getName()); } diff --git a/src/main/java/org/nrg/xnat/configuration/ReactorConfig.java b/src/main/java/org/nrg/xnat/configuration/ReactorConfig.java index 13f555e7f76d825d7d1b446899c8b3d2ab1d1273..c12fc08069f565a2d44f740c470d00be1501c780 100755 --- a/src/main/java/org/nrg/xnat/configuration/ReactorConfig.java +++ b/src/main/java/org/nrg/xnat/configuration/ReactorConfig.java @@ -2,15 +2,11 @@ package org.nrg.xnat.configuration; import org.nrg.framework.services.NrgEventService; import org.nrg.xft.event.listeners.XftItemEventListener; -import org.nrg.xnat.event.conf.EventPackages; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import reactor.Environment; import reactor.bus.EventBus; -import java.util.Arrays; -import java.util.HashSet; - /** * The Class ReactorConfig. */ diff --git a/src/main/java/org/nrg/xnat/event/listeners/AutoRunEmailHandler.java b/src/main/java/org/nrg/xnat/event/listeners/AutoRunEmailHandler.java index 08f84f6ee7eefe17af30e49e3094baa1211d660f..811bb80c28757a94037b5136db158584765880fb 100644 --- a/src/main/java/org/nrg/xnat/event/listeners/AutoRunEmailHandler.java +++ b/src/main/java/org/nrg/xnat/event/listeners/AutoRunEmailHandler.java @@ -33,7 +33,7 @@ public class AutoRunEmailHandler extends PipelineEmailHandlerAbst implements Con @Inject public AutoRunEmailHandler(EventBus eventBus, final NotificationsPreferences preferences) { _preferences = preferences; - eventBus.on(R(WorkflowStatusEvent.class.getName() + "[.](" + PersistentWorkflowUtils.COMPLETE + "|" + PersistentWorkflowUtils.FAILED + ")"), this); + eventBus.on(R(WorkflowStatusEvent.class.getName() + "[.]?(" + PersistentWorkflowUtils.COMPLETE + "|" + PersistentWorkflowUtils.FAILED + ")"), this); } /* (non-Javadoc) diff --git a/src/main/java/org/nrg/xnat/event/listeners/DicomToNiftiEmailHandler.java b/src/main/java/org/nrg/xnat/event/listeners/DicomToNiftiEmailHandler.java index d704a327c09651bb3ac488f0a1994a003a721024..722ad0e17b7a7deff044dd0192d51b470b19f045 100644 --- a/src/main/java/org/nrg/xnat/event/listeners/DicomToNiftiEmailHandler.java +++ b/src/main/java/org/nrg/xnat/event/listeners/DicomToNiftiEmailHandler.java @@ -26,7 +26,7 @@ public class DicomToNiftiEmailHandler extends PipelineEmailHandlerAbst implement @Autowired public DicomToNiftiEmailHandler(EventBus eventBus, final NotificationsPreferences preferences){ _preferences = preferences; - eventBus.on(R(WorkflowStatusEvent.class.getName() + "[.](" + PersistentWorkflowUtils.COMPLETE + "|" + PersistentWorkflowUtils.FAILED + ")"), this); + eventBus.on(R(WorkflowStatusEvent.class.getName() + "[.]?(" + PersistentWorkflowUtils.COMPLETE + "|" + PersistentWorkflowUtils.FAILED + ")"), this); } /* (non-Javadoc) diff --git a/src/main/java/org/nrg/xnat/helpers/dicom/DicomDump.java b/src/main/java/org/nrg/xnat/helpers/dicom/DicomDump.java index 750ce6cb394f0fc5a702e19c485b9ee617291846..bcda36f9307feafbff46d4037567d4616ccd8d21 100644 --- a/src/main/java/org/nrg/xnat/helpers/dicom/DicomDump.java +++ b/src/main/java/org/nrg/xnat/helpers/dicom/DicomDump.java @@ -580,7 +580,7 @@ public final class DicomDump extends SecureResource { public Representation represent(final Variant variant) { final MediaType mt = overrideVariant(variant); try { - String file = this.env.h.retrieve(this.env, this.user); + String file = this.env.h.retrieve(this.env, getUser()); DicomHeaderDump d = new DicomHeaderDump(file, env.fields); final XFTTable t = d.render(); return this.representTable(t, mt, new Hashtable<String, Object>()); diff --git a/src/main/java/org/nrg/xnat/helpers/editscript/DicomEdit.java b/src/main/java/org/nrg/xnat/helpers/editscript/DicomEdit.java index e56aabd2956177c6fac7d43aee2793443ff259ac..ce0e22ed4a45e1ea44f163acc2b80b6905b3c554 100644 --- a/src/main/java/org/nrg/xnat/helpers/editscript/DicomEdit.java +++ b/src/main/java/org/nrg/xnat/helpers/editscript/DicomEdit.java @@ -133,6 +133,7 @@ public final class DicomEdit extends SecureResource { final MediaType mt = overrideVariant(variant); final boolean all = this.getQueryVariable("all") != null; XFTTable table = null; + final UserI user = getUser(); try { table = new ScriptOp<>(this.project, @@ -140,7 +141,7 @@ public final class DicomEdit extends SecureResource { this.scope, this.rType, this.access, - this.user, + user, new Callable<XFTTable>() { @Override public XFTTable call() throws Exception { @@ -222,23 +223,24 @@ public final class DicomEdit extends SecureResource { this.scope, this.rType, this.access, - this.user, + this.getUser(), new Callable<java.lang.Void>() { @Override public java.lang.Void call() throws Exception { try { + final UserI user = getUser(); if (rType == ResourceType.SCRIPT) { String script = getFile(); if (script != null) { if (scope == ResourceScope.SITE_WIDE) { AnonUtils.getService().setSiteWideScript(user.getLogin(), - DicomEdit.buildScriptPath(scope, project), - script); + DicomEdit.buildScriptPath(scope, project), + script); } else { // project specific AnonUtils.getService().setProjectScript(user.getLogin(), - DicomEdit.buildScriptPath(scope, project), - script, - DicomEdit.getDBId(project)); + DicomEdit.buildScriptPath(scope, project), + script, + DicomEdit.getDBId(project)); } } else { // something went wrong, but the error response status should have @@ -255,20 +257,20 @@ public final class DicomEdit extends SecureResource { if (scope == ResourceScope.SITE_WIDE) { if (activate) { AnonUtils.getService().enableSiteWide(user.getLogin(), - DicomEdit.buildScriptPath(scope, project)); + DicomEdit.buildScriptPath(scope, project)); } else { AnonUtils.getService().disableSiteWide(user.getLogin(), - DicomEdit.buildScriptPath(scope, project)); + DicomEdit.buildScriptPath(scope, project)); } } else { // project -specific if (activate) { AnonUtils.getService().enableProjectSpecific(user.getLogin(), - DicomEdit.buildScriptPath(scope, project), - DicomEdit.getDBId(project)); + DicomEdit.buildScriptPath(scope, project), + DicomEdit.getDBId(project)); } else { AnonUtils.getService().disableProjectSpecific(user.getLogin(), - DicomEdit.buildScriptPath(scope, project), - DicomEdit.getDBId(project)); + DicomEdit.buildScriptPath(scope, project), + DicomEdit.getDBId(project)); } } } else { @@ -289,7 +291,7 @@ public final class DicomEdit extends SecureResource { } }).run(); } catch (Exception exception) { - logger.error("Internal server error for user " + user.getUsername(), exception); + logger.error("Internal server error for user " + getUser().getUsername(), exception); this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, exception.getMessage()); } } diff --git a/src/main/java/org/nrg/xnat/initialization/RootConfig.java b/src/main/java/org/nrg/xnat/initialization/RootConfig.java index 87bb0676675ed8b2548f452898e193ee5d626723..03dd06e6fabf44fa2e18d0c3da90019c6357daa1 100644 --- a/src/main/java/org/nrg/xnat/initialization/RootConfig.java +++ b/src/main/java/org/nrg/xnat/initialization/RootConfig.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.core.util.DefaultIndenter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module; +import org.apache.commons.beanutils.BeanUtils; import org.nrg.framework.datacache.SerializerRegistry; import org.nrg.framework.exceptions.NrgServiceException; import org.nrg.framework.services.ContextService; @@ -24,12 +25,19 @@ import org.springframework.http.converter.json.MappingJackson2HttpMessageConvert import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.oxm.jaxb.Jaxb2Marshaller; +import org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean; import javax.servlet.ServletContext; import javax.xml.bind.Marshaller; +import java.io.BufferedReader; import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.HashMap; import java.util.Map; +import java.util.Properties; /** * Configuration for the XNAT root application context. This contains all of the basic infrastructure for initializing @@ -52,6 +60,26 @@ public class RootConfig { return ContextService.getInstance(); } + @Bean + public ThreadPoolExecutorFactoryBean threadPoolExecutorFactoryBean(final Path xnatHome) throws IOException, InvocationTargetException, IllegalAccessException { + final ThreadPoolExecutorFactoryBean bean = new ThreadPoolExecutorFactoryBean(); + + final Path executor = xnatHome.resolve("../executor.properties"); + if (executor.toFile().exists()) { + try (final BufferedReader reader = Files.newBufferedReader(executor, StandardCharsets.UTF_8)) { + final Properties properties = new Properties(); + properties.load(reader); + final Map<String, String> converted = new HashMap<>(); + for (final String key : properties.stringPropertyNames()) { + converted.put(key, properties.getProperty(key)); + } + BeanUtils.populate(bean, converted); + } + } + + return bean; + } + @Bean public PrearcConfig prearcConfig() { final PrearcConfig prearcConfig = new PrearcConfig(); diff --git a/src/main/java/org/nrg/xnat/initialization/tasks/SystemPathVerification.java b/src/main/java/org/nrg/xnat/initialization/tasks/SystemPathVerification.java index ecdf887e4849955beb8414fc2ff676af08fc95d8..a8feecceda17a158c9464c6d61635e327643195f 100644 --- a/src/main/java/org/nrg/xnat/initialization/tasks/SystemPathVerification.java +++ b/src/main/java/org/nrg/xnat/initialization/tasks/SystemPathVerification.java @@ -11,24 +11,23 @@ */ package org.nrg.xnat.initialization.tasks; +import java.io.File; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import javax.mail.MessagingException; + import org.nrg.mail.services.MailService; import org.nrg.xdat.preferences.SiteConfigPreferences; import org.nrg.xnat.services.XnatAppInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.stereotype.Component; -import javax.mail.MessagingException; -import java.io.File; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; +import com.google.common.collect.Lists; @Component public class SystemPathVerification extends AbstractInitializingTask { @@ -45,28 +44,29 @@ public class SystemPathVerification extends AbstractInitializingTask { return "System Path Verification"; } - private final static ArrayList<String> pathErrors = new ArrayList<>(); - public static String pathErrorWarning = null; + private final static List<String> pathErrors = Lists.newArrayList(); + public static String pathErrorWarning = null; @Override public void run() { if (_appInfo.isInitialized()) { try { - validatePath(_config.getArchivePath(), "Archive", true); - validatePath(_config.getCachePath(), "Archive", false); - validatePath(_config.getPipelinePath(), "Archive", false); - validatePath(_config.getPrearchivePath(), "Archive", false); + final Integer resourceCount = _template.queryForObject("SELECT COUNT(xnat_abstractresource_id) AS COUNT FROM xnat_abstractresource", Integer.class); + + validatePath(_config.getArchivePath(), "Archive", (resourceCount>0)); + validatePath(_config.getCachePath(), "Cache", false); + validatePath(_config.getPipelinePath(), "Pipeline", false); + validatePath(_config.getBuildPath(), "Build", false); + validatePath(_config.getPrearchivePath(), "Prearchive", false); - final ProjectExtractor pe = new ProjectExtractor(); - final Map<String, String> projects = _template.query("SELECT id, name FROM xnat_projectdata", pe); if (pathErrors.size() > 0) { // Send warning email to admin and issue browser notification - notifyOfPathErrors(projects.size()); + notifyOfPathErrors(resourceCount); } else { _config.setPathErrorWarning(""); } complete(); - } catch (SQLException e) { + } catch (Throwable e) { logger.error("An error occurred trying to retrieve the values for the system paths.", e); } } @@ -95,43 +95,34 @@ public class SystemPathVerification extends AbstractInitializingTask { return true; } - private static class ProjectExtractor implements ResultSetExtractor<Map<String, String>> { - @Override - public Map<String, String> extractData(final ResultSet results) throws SQLException, DataAccessException { - final Map<String, String> projects = new HashMap<>(); - while (results.next()) { - projects.put(results.getString(1), results.getString(2)); - } - return projects; + private void notifyOfPathErrors(int numResources) { + int i = 1; + String adminEmail = _config.getAdminEmail(); + String sysName = _config.getSiteId(); + String emailSubj = sysName + " " + this.getTaskName() + " Failure"; + StringBuilder sb = new StringBuilder(); + String singPlurl = " has"; + if (pathErrors.size() > 1) { + singPlurl = "s have"; } - } - - private void notifyOfPathErrors(int numProjects) { - if (numProjects > 0) { - int i = 1; - String adminEmail = _config.getAdminEmail(); - String sysName = _config.getSiteId(); - String emailSubj = sysName + " " + this.getTaskName() + " Failure"; - StringBuilder sb = new StringBuilder(); - String singPlurl = " has"; - if (numProjects > 1) { - singPlurl = "s have"; - } - sb.append("The following system path error"); - sb.append(singPlurl); - sb.append(" been discovered:"); - for (String err : pathErrors) { - sb.append("\n\t"); - sb.append(i++); - sb.append(". "); - sb.append(err); - } - _config.setPathErrorWarning(sb.toString().replace("\n", "<br>")); - pathErrorWarning = sb.insert(0, emailSubj + ": ").toString(); - logger.error(pathErrorWarning); + sb.append("The following system path error"); + sb.append(singPlurl); + sb.append(" been discovered:"); + for (String err : pathErrors) { + sb.append("\n\t"); + sb.append(i++); + sb.append(". "); + sb.append(err); + } + _config.setPathErrorWarning(sb.toString().replace("\n", "<br>")); + pathErrorWarning = sb.insert(0, emailSubj + ": ").toString(); + logger.error(pathErrorWarning); + + if (numResources > 0) { + //only send an email if the system is supposed to have resources try { _mailService.sendHtmlMessage(adminEmail, adminEmail, emailSubj, pathErrorWarning); - } catch (MessagingException e) { + } catch (Throwable e) { logger.error("", e); } } diff --git a/src/main/java/org/nrg/xnat/restlet/actions/UserSessionId.java b/src/main/java/org/nrg/xnat/restlet/actions/UserSessionId.java index 2e7bfdeaa12c896cd195b438671ab207f815d758..4f43bf7aca04421220d74eca3bc1eb1a35934eb3 100644 --- a/src/main/java/org/nrg/xnat/restlet/actions/UserSessionId.java +++ b/src/main/java/org/nrg/xnat/restlet/actions/UserSessionId.java @@ -39,6 +39,7 @@ public class UserSessionId extends SecureResource { public UserSessionId(Context context, Request request, Response response) throws Exception { super(context, request, response); + final UserI user = getUser(); userID = (String) getParameter(request, "USER_ID"); if (!Roles.isSiteAdmin(user) && !user.getLogin().equals(userID)) { _log.error("User " + user.getLogin() + " attempted to access session list for user " + userID); diff --git a/src/main/java/org/nrg/xnat/restlet/extensions/IpWhitelist.java b/src/main/java/org/nrg/xnat/restlet/extensions/IpWhitelist.java index 86de46539cea0c8c261c2f6f86877922e1fbbbd5..2205697c0f50e26f61f123641f52169b5c0d6c99 100644 --- a/src/main/java/org/nrg/xnat/restlet/extensions/IpWhitelist.java +++ b/src/main/java/org/nrg/xnat/restlet/extensions/IpWhitelist.java @@ -36,7 +36,7 @@ public class IpWhitelist extends SecureResource { public IpWhitelist(Context context, Request request, Response response) { super(context, request, response); - if (!Roles.isSiteAdmin(user)) { + if (!Roles.isSiteAdmin(getUser())) { getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); } else if (request.getMethod() == Method.PUT && !request.isEntityAvailable()) { getResponse().setStatus(Status.CLIENT_ERROR_PRECONDITION_FAILED, "You must provide a configuration for whitelisted IP addresses."); @@ -52,7 +52,7 @@ public class IpWhitelist extends SecureResource { } try { - return new StringRepresentation(XDAT.getWhitelistConfiguration(user)); + return new StringRepresentation(XDAT.getWhitelistConfiguration(getUser())); } catch (ConfigServiceException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e); } @@ -67,13 +67,13 @@ public class IpWhitelist extends SecureResource { public void handlePut() { try { String whitelist = getRequest().getEntity().getText(); - List<String> addresses = new ArrayList<String>(Arrays.asList(whitelist.split("[\\s,]+"))); + List<String> addresses = new ArrayList<>(Arrays.asList(whitelist.split("[\\s,]+"))); for (String localhost : XDAT.getLocalhostIPs()) { if (!addresses.contains(localhost)) { addresses.add(localhost); } } - XDAT.getConfigService().replaceConfig(user.getLogin(), "", XDAT.IP_WHITELIST_TOOL, XDAT.IP_WHITELIST_PATH, Joiner.on("\n").join(addresses)); + XDAT.getConfigService().replaceConfig(getUser().getLogin(), "", XDAT.IP_WHITELIST_TOOL, XDAT.IP_WHITELIST_PATH, Joiner.on("\n").join(addresses)); } catch (IOException e) { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, e, "Error occurred trying to handle the incoming data"); _log.error("Error occurred trying to handle the incoming data", e); diff --git a/src/main/java/org/nrg/xnat/restlet/extensions/ScanQualityLabelRestlet.java b/src/main/java/org/nrg/xnat/restlet/extensions/ScanQualityLabelRestlet.java index a0f6977fba1c62393a0e23c341878a5e165c473f..f61a3cc74040d5e8c703884c760a87556fd5c061 100644 --- a/src/main/java/org/nrg/xnat/restlet/extensions/ScanQualityLabelRestlet.java +++ b/src/main/java/org/nrg/xnat/restlet/extensions/ScanQualityLabelRestlet.java @@ -49,7 +49,7 @@ public class ScanQualityLabelRestlet extends SecureResource { } try { - List<String> labels = ScanQualityUtils.getQualityLabels(_projectId, user); + List<String> labels = ScanQualityUtils.getQualityLabels(_projectId, getUser()); JSONObject json = new JSONObject(); json.put(StringUtils.isBlank(_projectId) ? "site" : _projectId, labels); return new JSONObjectRepresentation(MediaType.APPLICATION_JSON, json); diff --git a/src/main/java/org/nrg/xnat/restlet/extensions/SessionCountRestlet.java b/src/main/java/org/nrg/xnat/restlet/extensions/SessionCountRestlet.java index dadb93ed63ebf8ff62dc07a5ae50e686ec964779..318cfaa8fa0db199d4d5fe2f53d84f506752b8c3 100644 --- a/src/main/java/org/nrg/xnat/restlet/extensions/SessionCountRestlet.java +++ b/src/main/java/org/nrg/xnat/restlet/extensions/SessionCountRestlet.java @@ -10,8 +10,6 @@ */ package org.nrg.xnat.restlet.extensions; -import java.util.List; - import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -20,9 +18,6 @@ import org.nrg.xdat.security.helpers.Roles; import org.nrg.xdat.security.helpers.Users; import org.nrg.xdat.security.user.exceptions.UserInitException; import org.nrg.xdat.security.user.exceptions.UserNotFoundException; -import org.nrg.xdat.security.helpers.Users; -import org.nrg.xdat.security.user.exceptions.UserInitException; -import org.nrg.xdat.security.user.exceptions.UserNotFoundException; import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.XnatRestlet; import org.nrg.xnat.restlet.resources.SecureResource; @@ -39,6 +34,8 @@ import org.springframework.security.core.session.SessionInformation; import org.springframework.security.core.session.SessionRegistry; import org.springframework.security.core.session.SessionRegistryImpl; +import java.util.List; + @XnatRestlet({"/services/sessions", "/services/sessions/{USERNAME}"}) public class SessionCountRestlet extends SecureResource { public static final String PARAM_USERNAME = "USERNAME"; @@ -53,6 +50,8 @@ public class SessionCountRestlet extends SecureResource { final String username = (String) getRequest().getAttributes().get(PARAM_USERNAME); + final UserI user = getUser(); + // You can't request another user's session count unless you're a site admin. if (!StringUtils.isBlank(username)) { // But if it's just you, no harm no foul. @@ -67,9 +66,7 @@ public class SessionCountRestlet extends SecureResource { UserI xdatUser=null; try { xdatUser = Users.getUser(username); - } catch (UserNotFoundException e) { - - } catch (UserInitException e) { + } catch (UserNotFoundException | UserInitException e) { logger.error("",e); } diff --git a/src/main/java/org/nrg/xnat/restlet/extensions/StudyRoutingRestlet.java b/src/main/java/org/nrg/xnat/restlet/extensions/StudyRoutingRestlet.java index fbbb4e6736b453086b77309d0e58f8c82e9c4aa3..33dafd3552d86c6156f009078c0b0ddcb6b02dfb 100644 --- a/src/main/java/org/nrg/xnat/restlet/extensions/StudyRoutingRestlet.java +++ b/src/main/java/org/nrg/xnat/restlet/extensions/StudyRoutingRestlet.java @@ -20,6 +20,7 @@ import org.nrg.xdat.security.helpers.Roles; import org.nrg.xdat.security.helpers.UserHelper; import org.nrg.xdat.services.StudyRoutingService; import org.nrg.xft.XFTTable; +import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.XnatRestlet; import org.nrg.xnat.restlet.resources.SecureResource; import org.restlet.Context; @@ -98,6 +99,7 @@ public class StudyRoutingRestlet extends SecureResource { @Override public Representation represent(final Variant variant) { final MediaType mediaType = overrideVariant(variant); + final UserI user = getUser(); if (StringUtils.isNotBlank(_studyInstanceUid)) { final Map<String, String> routing = _routingService.findStudyRouting(_studyInstanceUid); if (routing == null || routing.size() == 0) { @@ -155,6 +157,7 @@ public class StudyRoutingRestlet extends SecureResource { @Override public void handlePut() { try { + final UserI user = getUser(); if (!Permissions.can(user,"xnat:mrSessionData/project", _projectId, SecurityManager.EDIT)) { getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, "You do not have sufficient privileges to modify study routings for this project."); return; @@ -185,6 +188,7 @@ public class StudyRoutingRestlet extends SecureResource { @Override public void handleDelete() { + final UserI user = getUser(); if (StringUtils.isBlank(_studyInstanceUid)) { if (!Roles.isSiteAdmin(user)) { getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, "You must be a site administrator to delete all study routings for this site."); diff --git a/src/main/java/org/nrg/xnat/restlet/extensions/UserRolesRestlet.java b/src/main/java/org/nrg/xnat/restlet/extensions/UserRolesRestlet.java index ebc9829bbb6d5ae336d5b3a9a950bf19de6b5066..64e310234f4a039bcbcf983f02214ba7b8b998dd 100644 --- a/src/main/java/org/nrg/xnat/restlet/extensions/UserRolesRestlet.java +++ b/src/main/java/org/nrg/xnat/restlet/extensions/UserRolesRestlet.java @@ -1,12 +1,7 @@ package org.nrg.xnat.restlet.extensions; -import java.util.Collection; -import java.util.Hashtable; -import java.util.List; - +import com.google.common.collect.Lists; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; -import org.nrg.xdat.om.XdatRoleType; import org.nrg.xdat.security.helpers.Roles; import org.nrg.xdat.security.helpers.Users; import org.nrg.xdat.security.services.RoleRepositoryServiceI.RoleDefinitionI; @@ -23,8 +18,13 @@ 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 com.google.common.collect.Lists; +import java.util.Collection; +import java.util.Collections; +import java.util.Hashtable; +import java.util.List; /** * @author tim@deck5consulting.com @@ -33,7 +33,7 @@ import com.google.common.collect.Lists; */ @XnatRestlet("/user/{USER_ID}/roles") public class UserRolesRestlet extends SecureResource { - static Logger logger = Logger.getLogger(UserRolesRestlet.class); + private static final Logger logger = LoggerFactory.getLogger(UserRolesRestlet.class); UserI other=null; String userId=null; /** @@ -44,7 +44,7 @@ public class UserRolesRestlet extends SecureResource { public UserRolesRestlet(Context context, Request request, Response response) { super(context, request, response); - if (!Roles.isSiteAdmin(user)) { + if (!Roles.isSiteAdmin(getUser())) { getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, "User does not have privileges to access this project."); } else { userId = (String) getRequest().getAttributes().get("USER_ID"); @@ -72,11 +72,7 @@ public class UserRolesRestlet extends SecureResource { final List<String> roles=Lists.newArrayList(); if(hasQueryVariable("roles")){ - final String roleS=getQueryVariable("roles"); - - for(String role: roleS.split(",")){ - roles.add(role); - } + Collections.addAll(roles, getQueryVariable("roles").split(",")); } try { @@ -87,7 +83,8 @@ public class UserRolesRestlet extends SecureResource { for(RoleDefinitionI def:defined){ allDefinedRoles.add(def.getKey()); } - + + final UserI user = getUser(); //remove roles and save one at a time so that there is a separate workflow entry for each one for(String dRole:allDefinedRoles){ if(!roles.contains(dRole)){ @@ -117,7 +114,6 @@ public class UserRolesRestlet extends SecureResource { } catch (Throwable e) { logger.error("",e); this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,e.getMessage()); - return; } } @@ -126,15 +122,15 @@ public class UserRolesRestlet extends SecureResource { @Override public Representation represent(Variant variant) throws ResourceException { MediaType mt = overrideVariant(variant); - Hashtable<String,Object> params=new Hashtable<String,Object>(); + Hashtable<String,Object> params= new Hashtable<>(); XFTTable table=new XFTTable(); table.initTable(new String[]{"role"}); - for(String role: Roles.getRoles(user)){ + for(String role: Roles.getRoles(getUser())){ table.rows().add(new Object[]{role}); } - - if(table!=null)params.put("totalRecords", table.size()); + + params.put("totalRecords", table.size()); return this.representTable(table, mt, params); } } diff --git a/src/main/java/org/nrg/xnat/restlet/extensions/UserSettingsRestlet.java b/src/main/java/org/nrg/xnat/restlet/extensions/UserSettingsRestlet.java index ff5da74b9b8534f8a9174cf0aac365711dc5d344..f4c828e3ffd3716efae102416ea4280a1efeb8a2 100644 --- a/src/main/java/org/nrg/xnat/restlet/extensions/UserSettingsRestlet.java +++ b/src/main/java/org/nrg/xnat/restlet/extensions/UserSettingsRestlet.java @@ -69,7 +69,7 @@ public class UserSettingsRestlet extends SecureResource { } } - if (!Roles.isSiteAdmin(user)) { + if (!Roles.isSiteAdmin(getUser())) { getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, "User does not have privileges to access this project."); _action = null; _auths = null; @@ -175,7 +175,7 @@ public class UserSettingsRestlet extends SecureResource { // Find all auths before saving primary record. This way, if there are any format errors, we'll error out before committing the new user record. List<Map<UserProperty, String>> auths = translateAuths(); - Users.save(xdatUser, user, false, EventUtils.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN, EventUtils.TYPE.WEB_SERVICE, "Registered User")); + Users.save(xdatUser, getUser(), false, EventUtils.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN, EventUtils.TYPE.WEB_SERVICE, "Registered User")); // If there are no auths specified... if (auths == null || auths.size() == 0) { diff --git a/src/main/java/org/nrg/xnat/restlet/extensions/WorkflowsRestlet.java b/src/main/java/org/nrg/xnat/restlet/extensions/WorkflowsRestlet.java index 7e48694ec8e4abc26e66761b30bd507ef873260d..e5369f2c3d05386d11f3aa005ae18dc531898a4c 100644 --- a/src/main/java/org/nrg/xnat/restlet/extensions/WorkflowsRestlet.java +++ b/src/main/java/org/nrg/xnat/restlet/extensions/WorkflowsRestlet.java @@ -19,6 +19,7 @@ import org.nrg.xft.XFTTable; import org.nrg.xft.event.persist.PersistentWorkflowI; import org.nrg.xft.event.persist.PersistentWorkflowUtils; import org.nrg.xft.search.CriteriaCollection; +import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.XnatRestlet; import org.nrg.xnat.restlet.resources.SecureResource; import org.restlet.Context; @@ -78,8 +79,9 @@ public class WorkflowsRestlet extends SecureResource { @Override public Representation represent(Variant variant) { MediaType mt = overrideVariant(variant); - if (workflow_primary_key !=null) { - PersistentWorkflowI wrkFlow = PersistentWorkflowUtils.getWorkflowByEventId(user,Integer.parseInt(workflow_primary_key)); + final UserI user = getUser(); + if (workflow_primary_key != null) { + PersistentWorkflowI wrkFlow = PersistentWorkflowUtils.getWorkflowByEventId(user, Integer.parseInt(workflow_primary_key)); return representItem(((WrkWorkflowdata)wrkFlow).getItem(),mt); }else { XnatExperimentdata expt = null; @@ -87,7 +89,7 @@ public class WorkflowsRestlet extends SecureResource { expt=XnatExperimentdata.getXnatExperimentdatasById(xnat_id, user, false); if(project_id!=null){ if(expt==null){ - expt = XnatExperimentdata.GetExptByProjectIdentifier(project_id, xnat_id,user, false); + expt = XnatExperimentdata.GetExptByProjectIdentifier(project_id, xnat_id, user, false); } } } @@ -125,7 +127,7 @@ public class WorkflowsRestlet extends SecureResource { PopulateItem populator = PopulateItem.Populate(rowHash, user, "wrk:workflowdata", true); return representItem(populator.getItem(), mt); }else { - Hashtable<String, Object> params = new Hashtable<String, Object>(); + Hashtable<String, Object> params = new Hashtable<>(); return representTable(table, mt, params); } }else { @@ -143,7 +145,7 @@ public class WorkflowsRestlet extends SecureResource { }else { org.nrg.xft.search.ItemSearch itemSearch = new org.nrg.xft.search.ItemSearch(user, "wrk:workflowdata", cc); XFTTable table = itemSearch.executeToTable(false); - Hashtable<String,Object> params=new Hashtable<String,Object>(); + Hashtable<String,Object> params= new Hashtable<>(); params.put("title", "All workflows"); return representTable(table, mt, params); } @@ -242,7 +244,7 @@ public class WorkflowsRestlet extends SecureResource { mt = overrideVariant(variant); try { XFTTable table=XFTTable.Execute(query, user.getDBName(), userName); - Hashtable<String,Object> params=new Hashtable<String,Object>(); + Hashtable<String,Object> params= new Hashtable<>(); params.put("title", "All " + status + " workflows"); return representTable(table, mt, params); }catch(Exception e) { 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 ebbcdb058197cf1b11397530c8c5d4b86d1a0ec8..189541b3760b8ff21e25645575fc6f6dbb3bdf52 100644 --- a/src/main/java/org/nrg/xnat/restlet/guard/XnatSecureGuard.java +++ b/src/main/java/org/nrg/xnat/restlet/guard/XnatSecureGuard.java @@ -102,23 +102,14 @@ public class XnatSecureGuard extends Filter { } return true; } else { - UserI user; final ChallengeResponse challengeResponse = request.getChallengeResponse(); if (challengeResponse != null) { - user = authenticateBasic(challengeResponse); + UserI user = authenticateBasic(challengeResponse); if (user != null) { return true; } - } - else if (!XDAT.getSiteConfigPreferences().getRequireLogin()) { - try { - user=Users.getGuest(); - if (user!=null) { - return true; - } - } catch (Exception e) { - logger.error("",e); - } + } else { + return !XDAT.getSiteConfigPreferences().getRequireLogin(); } } return false; diff --git a/src/main/java/org/nrg/xnat/restlet/projectResource/extensions/ProjectPermissionsFilter.java b/src/main/java/org/nrg/xnat/restlet/projectResource/extensions/ProjectPermissionsFilter.java index 65e1d84886ed0cffe5b890971d39c914cb7f3476..97cbb0819ad888afce12a7d7a6b12ebbcb7f97a8 100644 --- a/src/main/java/org/nrg/xnat/restlet/projectResource/extensions/ProjectPermissionsFilter.java +++ b/src/main/java/org/nrg/xnat/restlet/projectResource/extensions/ProjectPermissionsFilter.java @@ -2,6 +2,7 @@ package org.nrg.xnat.restlet.projectResource.extensions; import org.nrg.xdat.security.helpers.Groups; import org.nrg.xft.XFTTable; +import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.resources.ProjectResource; import org.nrg.xnat.restlet.resources.SecureResource; import org.nrg.xnat.restlet.resources.SecureResource.FilteredResourceHandlerI; @@ -11,24 +12,24 @@ import org.restlet.resource.Variant; import java.util.Hashtable; @SuppressWarnings("unused") -public class ProjectPermissionsFilter implements FilteredResourceHandlerI{ +public class ProjectPermissionsFilter implements FilteredResourceHandlerI { + @Override + public boolean canHandle(SecureResource resource) { + return resource.isQueryVariableTrue("creatableTypes"); + } - @Override - public boolean canHandle(SecureResource resource) { - return resource.isQueryVariableTrue("creatableTypes"); - } + @Override + public Representation handle(SecureResource resource, Variant variant) throws Exception { + final ProjectResource projResource = (ProjectResource) resource; + final StringBuilder builder = new StringBuilder(); + final UserI user = resource.getUser(); - @Override - public Representation handle(SecureResource resource, Variant variant) throws Exception { - ProjectResource projResource=(ProjectResource)resource; - StringBuilder builder=new StringBuilder(); - if(Groups.isMember(resource.user,"ALL_DATA_ADMIN")){ - builder.append(String.format("SELECT DISTINCT element_name FROM xdat_element_access xea JOIN xdat_field_mapping_set xfms ON xea.xdat_element_access_id=xfms.permissions_allow_set_xdat_elem_xdat_element_access_id JOIN xdat_field_mapping xfm ON xfms.xdat_field_mapping_set_id=xfm.xdat_field_mapping_set_xdat_field_mapping_set_id WHERE create_element=1 AND field_value='%1$s' and field !=''", projResource.getProjectId())); - }else{ - builder.append(String.format("SELECT DISTINCT element_name FROM xdat_user_groupID map JOIN xdat_userGroup gp ON map.groupid=gp.id JOIN xdat_element_access xea ON gp.xdat_usergroup_id=xea.xdat_usergroup_xdat_usergroup_id JOIN xdat_field_mapping_set xfms ON xea.xdat_element_access_id=xfms.permissions_allow_set_xdat_elem_xdat_element_access_id JOIN xdat_field_mapping xfm ON xfms.xdat_field_mapping_set_id=xfm.xdat_field_mapping_set_xdat_field_mapping_set_id WHERE map.groups_groupid_xdat_user_xdat_user_id=%1$s AND create_element=1 AND field_value='%2$s' and field !=''",resource.user.getID(),projResource.getProjectId())); + if (Groups.isMember(user, "ALL_DATA_ADMIN")) { + builder.append(String.format("SELECT DISTINCT element_name FROM xdat_element_access xea JOIN xdat_field_mapping_set xfms ON xea.xdat_element_access_id=xfms.permissions_allow_set_xdat_elem_xdat_element_access_id JOIN xdat_field_mapping xfm ON xfms.xdat_field_mapping_set_id=xfm.xdat_field_mapping_set_xdat_field_mapping_set_id WHERE create_element=1 AND field_value='%1$s' and field !=''", projResource.getProjectId())); + } else { + builder.append(String.format("SELECT DISTINCT element_name FROM xdat_user_groupID map JOIN xdat_userGroup gp ON map.groupid=gp.id JOIN xdat_element_access xea ON gp.xdat_usergroup_id=xea.xdat_usergroup_xdat_usergroup_id JOIN xdat_field_mapping_set xfms ON xea.xdat_element_access_id=xfms.permissions_allow_set_xdat_elem_xdat_element_access_id JOIN xdat_field_mapping xfm ON xfms.xdat_field_mapping_set_id=xfm.xdat_field_mapping_set_xdat_field_mapping_set_id WHERE map.groups_groupid_xdat_user_xdat_user_id=%1$s AND create_element=1 AND field_value='%2$s' and field !=''", user.getID(), projResource.getProjectId())); } - - return resource.representTable(XFTTable.Execute(builder.toString(), resource.user.getDBName(), resource.userName), resource.overrideVariant(variant), new Hashtable<String,Object>()) ; - } + return resource.representTable(XFTTable.Execute(builder.toString(), user.getDBName(), resource.userName), resource.overrideVariant(variant), new Hashtable<String, Object>()); + } } diff --git a/src/main/java/org/nrg/xnat/restlet/projectsList/extensions/EditableProjects.java b/src/main/java/org/nrg/xnat/restlet/projectsList/extensions/EditableProjects.java index 64787d5d8ba73e2cffa354d48aa65f6a5a23c8ab..2603d390e7504a04d9e1bf926b6bd19afa7802ac 100644 --- a/src/main/java/org/nrg/xnat/restlet/projectsList/extensions/EditableProjects.java +++ b/src/main/java/org/nrg/xnat/restlet/projectsList/extensions/EditableProjects.java @@ -1,38 +1,41 @@ package org.nrg.xnat.restlet.projectsList.extensions; -import java.util.Hashtable; - import org.nrg.xdat.security.helpers.Groups; import org.nrg.xft.XFTTable; import org.nrg.xft.schema.Wrappers.GenericWrapper.GenericWrapperElement; +import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.resources.SecureResource; import org.nrg.xnat.restlet.resources.SecureResource.FilteredResourceHandlerI; import org.restlet.resource.Representation; import org.restlet.resource.Variant; -public class EditableProjects implements FilteredResourceHandlerI{ +import java.util.Hashtable; - @Override - public boolean canHandle(SecureResource resource) { - return resource.isQueryVariableTrue("creatableTypes"); - } +@SuppressWarnings("unused") +public class EditableProjects implements FilteredResourceHandlerI { - @Override - public Representation handle(SecureResource resource, Variant variant) throws Exception { - StringBuilder builder=new StringBuilder(); - if(Groups.isMember(resource.user,"ALL_DATA_ADMIN")){ - builder.append("SELECT proj.ID, proj.name, proj.description,proj.secondary_id FROM xnat_projectData proj;"); - }else{ - builder.append(String.format("SELECT DISTINCT proj.ID, proj.name, proj.description,proj.secondary_id FROM xdat_user_groupID map JOIN xdat_userGroup gp ON map.groupid=gp.id JOIN xdat_element_access xea ON gp.xdat_usergroup_id=xea.xdat_usergroup_xdat_usergroup_id JOIN xdat_field_mapping_set xfms ON xea.xdat_element_access_id=xfms.permissions_allow_set_xdat_elem_xdat_element_access_id JOIN xdat_field_mapping xfm ON xfms.xdat_field_mapping_set_id=xfm.xdat_field_mapping_set_xdat_field_mapping_set_id AND create_element=1 AND field_value!='*' AND field_value!='' and field !='' JOIN xnat_projectData proj ON field_value=proj.ID WHERE map.groups_groupid_xdat_user_xdat_user_id=%s",resource.user.getID())); - if(resource.hasQueryVariable("data-type")){ - GenericWrapperElement gwe = GenericWrapperElement.GetElement(resource.getQueryVariable("data-type")); - if(gwe!=null){ - builder.append(" AND xea.element_name='" + gwe.getXSIType() + "' "); - } - } + @Override + public boolean canHandle(SecureResource resource) { + return resource.isQueryVariableTrue("creatableTypes"); + } + + @Override + public Representation handle(SecureResource resource, Variant variant) throws Exception { + final StringBuilder builder = new StringBuilder(); + final UserI user = resource.getUser(); + if (Groups.isMember(user, "ALL_DATA_ADMIN")) { + builder.append("SELECT proj.ID, proj.name, proj.description,proj.secondary_id FROM xnat_projectData proj;"); + } else { + builder.append(String.format("SELECT DISTINCT proj.ID, proj.name, proj.description,proj.secondary_id FROM xdat_user_groupID map JOIN xdat_userGroup gp ON map.groupid=gp.id JOIN xdat_element_access xea ON gp.xdat_usergroup_id=xea.xdat_usergroup_xdat_usergroup_id JOIN xdat_field_mapping_set xfms ON xea.xdat_element_access_id=xfms.permissions_allow_set_xdat_elem_xdat_element_access_id JOIN xdat_field_mapping xfm ON xfms.xdat_field_mapping_set_id=xfm.xdat_field_mapping_set_xdat_field_mapping_set_id AND create_element=1 AND field_value!='*' AND field_value!='' and field !='' JOIN xnat_projectData proj ON field_value=proj.ID WHERE map.groups_groupid_xdat_user_xdat_user_id=%s", user.getID())); + if (resource.hasQueryVariable("data-type")) { + GenericWrapperElement gwe = GenericWrapperElement.GetElement(resource.getQueryVariable("data-type")); + if (gwe != null) { + builder.append(" AND xea.element_name='").append(gwe.getXSIType()).append("' "); + } + } } - - return resource.representTable(XFTTable.Execute(builder.toString(), resource.user.getDBName(), resource.userName), resource.overrideVariant(variant), new Hashtable<String,Object>()) ; - } + + return resource.representTable(XFTTable.Execute(builder.toString(), user.getDBName(), resource.userName), resource.overrideVariant(variant), new Hashtable<String, Object>()); + } } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/AutomationResource.java b/src/main/java/org/nrg/xnat/restlet/resources/AutomationResource.java index 125a6171355ec5b466bd11520cb43041553bd80e..9295092cf445b827a343281c3917697f4a977c74 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/AutomationResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/AutomationResource.java @@ -11,6 +11,7 @@ import org.nrg.xft.event.EventDetails; import org.nrg.xft.event.EventUtils; import org.nrg.xft.event.persist.PersistentWorkflowI; import org.nrg.xft.event.persist.PersistentWorkflowUtils; +import org.nrg.xft.security.UserI; import org.nrg.xnat.utils.WorkflowUtils; import org.restlet.Context; import org.restlet.data.MediaType; @@ -80,6 +81,7 @@ public abstract class AutomationResource extends SecureResource { } protected void validateProjectAccess(final String projectId) throws ResourceException { + final UserI user = getUser(); final XnatProjectdata project = XnatProjectdata.getXnatProjectdatasById(projectId, user, false); if (project == null) { throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "Can't find project with ID: " + getProjectId()); @@ -129,7 +131,7 @@ public abstract class AutomationResource extends SecureResource { protected void recordAutomationEvent(final String automationId, final String containerId, final String operation, final Class<?> type) { try { final EventDetails instance = EventUtils.newEventInstance(EventUtils.CATEGORY.DATA, EventUtils.TYPE.WEB_SERVICE, operation, "", operation + " " + type + " with ID " + automationId); - PersistentWorkflowI workflow = PersistentWorkflowUtils.buildOpenWorkflow(user, type.getName(), automationId, containerId, instance); + PersistentWorkflowI workflow = PersistentWorkflowUtils.buildOpenWorkflow(getUser(), type.getName(), automationId, containerId, instance); assert workflow != null; workflow.setStatus(PersistentWorkflowUtils.COMPLETE); WorkflowUtils.save(workflow, workflow.buildEvent()); @@ -207,7 +209,7 @@ public abstract class AutomationResource extends SecureResource { } else { try { - XFTTable table = XFTTable.Execute("SELECT id FROM xnat_projectdata WHERE projectdata_info = " + entityId, user.getDBName(), userName); + XFTTable table = XFTTable.Execute("SELECT id FROM xnat_projectdata WHERE projectdata_info = " + entityId, getUser().getDBName(), userName); if (table.size() != 1) { throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "Couldn't find a project with the ID or alias of " + entityId); } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ConfigResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ConfigResource.java index 385f97f399e4fe5141794cf386315501ba2f131a..f10c72735c446417da06643a45ed4df7253db123 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ConfigResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ConfigResource.java @@ -23,6 +23,7 @@ import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.security.helpers.Permissions; import org.nrg.xdat.security.helpers.Roles; import org.nrg.xft.XFTTable; +import org.nrg.xft.security.UserI; import org.nrg.xnat.helpers.merge.AnonUtils; import org.nrg.xnat.restlet.util.FileWriterWrapperI; import org.restlet.Context; @@ -85,6 +86,7 @@ public class ConfigResource extends SecureResource { @Override public Representation represent(Variant variant) throws ResourceException { + final UserI user = getUser(); try { final MediaType mt = overrideVariant(variant); @@ -290,6 +292,7 @@ public class ConfigResource extends SecureResource { * it can just send it a second (or 100th) time, and it is guaranteed by the HTTP spec that this has exactly the * same effect as sending once. */ + final UserI user = getUser(); try { //check access, almost copy-paste code in the GET method. if (!((StringUtils.isNotBlank(projectId) && Permissions.canEdit(user, "xnat:subjectData/project", projectId)) || Roles.isSiteAdmin(user))) { @@ -382,6 +385,7 @@ public class ConfigResource extends SecureResource { @Override public void handleDelete() { //check access, almost copy-paste code in the GET method. + final UserI user = getUser(); try { if (StringUtils.isBlank(projectId)) { if (!Roles.isSiteAdmin(user)) { @@ -410,13 +414,13 @@ public class ConfigResource extends SecureResource { private String getBodyContents() throws FileUploadException, ClientException, IOException { List<FileWriterWrapperI> fws = getFileWriters(); if (fws.size() == 0) { - _log.warn("Unknown upload format", user.getUsername(), projectId); + _log.warn("Unknown upload format", getUser().getUsername(), projectId); getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Unable to identify upload format."); return null; } if (fws.size() > 1) { - _log.info("Importer is limited to one uploaded resource at a time.", user.getUsername(), projectId); + _log.info("Importer is limited to one uploaded resource at a time.", getUser().getUsername(), projectId); getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Importer is limited to one uploaded resource at a time."); return null; } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ExperimentListResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ExperimentListResource.java index a4580eb325c74971352e6b39aa94f189270a189c..7fe707a9068fc505766c8e6f41e6d6972f1f403d 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ExperimentListResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ExperimentListResource.java @@ -29,6 +29,7 @@ import org.nrg.xft.exception.DBPoolException; import org.nrg.xft.schema.Wrappers.GenericWrapper.GenericWrapperElement; import org.nrg.xft.schema.design.SchemaElementI; import org.nrg.xft.search.QueryOrganizer; +import org.nrg.xft.security.UserI; import org.nrg.xnat.helpers.xmlpath.XMLPathShortcuts; import org.restlet.data.MediaType; import org.restlet.data.Request; @@ -55,7 +56,7 @@ public class ExperimentListResource extends QueryOrganizerResource { @Override public ArrayList<String> getDefaultFields(GenericWrapperElement e) { - ArrayList<String> al=new ArrayList<String>(); + ArrayList<String> al= new ArrayList<>(); al.add("ID"); al.add("project"); @@ -82,8 +83,8 @@ public class ExperimentListResource extends QueryOrganizerResource { @SuppressWarnings("ConstantConditions") @Override - public Representation getRepresentation(Variant variant) { - Representation rep=super.getRepresentation(variant); + public Representation represent(Variant variant) { + Representation rep=super.represent(variant); if(rep!=null) { return rep; } @@ -97,13 +98,11 @@ public class ExperimentListResource extends QueryOrganizerResource { handler=filter; } } - } catch (InstantiationException e1) { - logger.error("",e1); - } catch (IllegalAccessException e1) { + } catch (InstantiationException | IllegalAccessException e1) { logger.error("",e1); } - Hashtable<String,Object> params=new Hashtable<String,Object>(); + Hashtable<String,Object> params= new Hashtable<>(); try { if(handler!=null){ @@ -142,9 +141,9 @@ public class ExperimentListResource extends QueryOrganizerResource { /** * Get a list of the possible experiment handlers. This allows additional handlers to be injected at a later date or via a module. - * @return - * @throws InstantiationException - * @throws IllegalAccessException + * @return The list of handlers. + * @throws InstantiationException When an error occurs creating an object. + * @throws IllegalAccessException When an error occurs accessing an object. */ public static List<FilteredExptListHandlerI> getHandlers() throws InstantiationException, IllegalAccessException{ if(handlers==null){ @@ -171,13 +170,13 @@ public class ExperimentListResource extends QueryOrganizerResource { } //FilteredExptListHandlerI allows additional experiment list handlers to be added via modules - public static interface FilteredExptListHandlerI{ - public boolean canHandle(SecureResource resource); - public XFTTable build(ExperimentListResource resource,Hashtable<String,Object> params) throws Exception; + interface FilteredExptListHandlerI { + boolean canHandle(SecureResource resource); + XFTTable build(ExperimentListResource resource,Hashtable<String,Object> params) throws Exception; } //handles requests where ?recent=something - public static class RecentExperiments implements FilteredExptListHandlerI{ + private static class RecentExperiments implements FilteredExptListHandlerI { @Override public boolean canHandle(SecureResource resource) { @@ -205,31 +204,33 @@ public class ExperimentListResource extends QueryOrganizerResource { //experiments VelocityContext context= new VelocityContext(); context.put("time", Calendar.getInstance().getTime()); - + + final UserI user = resource.getUser(); + StringBuilder builder=new StringBuilder(); - builder.append("SELECT * FROM (SELECT DISTINCT ON (expt.id) expt.id,perm.label,perm.project,date,status, workflow_status, xme.element_name, COALESCE(es.code,es.singular,es.element_name) AS TYPE_DESC,insert_date,activation_date,last_modified,workflow_date,pipeline_name, COALESCE(workflow_date,last_modified,insert_date) AS action_date FROM xnat_experimentData expt LEFT JOIN xdat_meta_element xme ON expt.extension=xme.xdat_meta_element_id LEFT JOIN xnat_experimentData_meta_data emd ON expt.experimentData_info=emd.meta_data_id LEFT JOIN xdat_element_security es ON xme.element_name=es.element_name LEFT JOIN ( SELECT DISTINCT ON (id) id,launch_time AS workflow_date,CASE pipeline_name WHEN 'Transferred'::text THEN 'Archived'::text ELSE CASE xs_lastposition('/'::text, pipeline_name::text) WHEN 0 THEN pipeline_name ELSE substring(substring(pipeline_name::text, xs_lastposition('/'::text, pipeline_name::text) + 1), 1, xs_lastposition('.'::text, substring(pipeline_name::text, xs_lastposition('/'::text, pipeline_name::text) + 1)) - 1) END END AS pipeline_name,status AS workflow_status FROM wrk_workflowdata WHERE category!='SIDE_ADMIN' AND launch_time > (NOW() - interval '" + days +" day') AND status!='Failed (Dismissed)' AND pipeline_name NOT LIKE 'xnat_tools%AutoRun.xml' ORDER BY id,launch_time DESC ) wrkflw ON expt.id=wrkflw.id RIGHT JOIN ("); - if(Groups.isMember(resource.user, "ALL_DATA_ACCESS") || Groups.isMember(resource.user, "ALL_DATA_ADMIN")){ + builder.append("SELECT * FROM (SELECT DISTINCT ON (expt.id) expt.id,perm.label,perm.project,date,status, workflow_status, xme.element_name, COALESCE(es.code,es.singular,es.element_name) AS TYPE_DESC,insert_date,activation_date,last_modified,workflow_date,pipeline_name, COALESCE(workflow_date,last_modified,insert_date) AS action_date FROM xnat_experimentData expt LEFT JOIN xdat_meta_element xme ON expt.extension=xme.xdat_meta_element_id LEFT JOIN xnat_experimentData_meta_data emd ON expt.experimentData_info=emd.meta_data_id LEFT JOIN xdat_element_security es ON xme.element_name=es.element_name LEFT JOIN ( SELECT DISTINCT ON (id) id,launch_time AS workflow_date,CASE pipeline_name WHEN 'Transferred'::text THEN 'Archived'::text ELSE CASE xs_lastposition('/'::text, pipeline_name::text) WHEN 0 THEN pipeline_name ELSE substring(substring(pipeline_name::text, xs_lastposition('/'::text, pipeline_name::text) + 1), 1, xs_lastposition('.'::text, substring(pipeline_name::text, xs_lastposition('/'::text, pipeline_name::text) + 1)) - 1) END END AS pipeline_name,status AS workflow_status FROM wrk_workflowdata WHERE category!='SIDE_ADMIN' AND launch_time > (NOW() - interval '").append(days).append(" day') AND status!='Failed (Dismissed)' AND pipeline_name NOT LIKE 'xnat_tools%AutoRun.xml' ORDER BY id,launch_time DESC ) wrkflw ON expt.id=wrkflw.id RIGHT JOIN ("); + if(Groups.isMember(user, "ALL_DATA_ACCESS") || Groups.isMember(user, "ALL_DATA_ADMIN")){ builder.append("SELECT DISTINCT ON (isd.ID) isd.ID, label, project FROM xnat_imageSessionData isd LEFT JOIN xnat_experimentData expt ON isd.ID=expt.ID"); }else{ - builder.append("SELECT DISTINCT ON (ID) ID, label, project FROM (" + Permissions.getUserPermissionsSQL(resource.user) + ") perms INNER JOIN (SELECT isd.id, element_name || '/project' as field, expt.project, expt.label FROM xnat_imageSessionData isd LEFT JOIN xnat_experimentData expt ON isd.id=expt.id LEFT JOIN xdat_meta_element xme ON expt.extension=xme.xdat_meta_element_id UNION SELECT expt.id,xme.element_name || '/sharing/share/project', shr.project, shr.label FROM xnat_experimentData_share shr LEFT JOIN xnat_experimentData expt ON expt.id=shr.sharing_share_xnat_experimentda_id LEFT JOIN xdat_meta_element xme ON expt.extension=xme.xdat_meta_element_id) expts ON perms.field=expts.field AND perms.field_value=expts.project"); + builder.append("SELECT DISTINCT ON (ID) ID, label, project FROM (").append(Permissions.getUserPermissionsSQL(user)).append(") perms INNER JOIN (SELECT isd.id, element_name || '/project' as field, expt.project, expt.label FROM xnat_imageSessionData isd LEFT JOIN xnat_experimentData expt ON isd.id=expt.id LEFT JOIN xdat_meta_element xme ON expt.extension=xme.xdat_meta_element_id UNION SELECT expt.id,xme.element_name || '/sharing/share/project', shr.project, shr.label FROM xnat_experimentData_share shr LEFT JOIN xnat_experimentData expt ON expt.id=shr.sharing_share_xnat_experimentda_id LEFT JOIN xdat_meta_element xme ON expt.extension=xme.xdat_meta_element_id) expts ON perms.field=expts.field AND perms.field_value=expts.project"); } builder.append(") perm ON expt.id=perm.id "); builder.append(" RIGHT JOIN xnat_imageSessionData isd ON perm.id=isd.id "); - builder.append(" WHERE (insert_date > (NOW() - interval '" + days +" day') OR activation_date > (NOW() - interval '" + days +" day') OR last_modified > (NOW() - interval '" + days +" day') OR workflow_date > (NOW() - interval '" + days +" day')) "); + builder.append(" WHERE (insert_date > (NOW() - interval '").append(days).append(" day') OR activation_date > (NOW() - interval '").append(days).append(" day') OR last_modified > (NOW() - interval '").append(days).append(" day') OR workflow_date > (NOW() - interval '").append(days).append(" day')) "); builder.append(" )SEARCH ORDER BY action_date DESC"); if(limit) { builder.append(" LIMIT 60"); } - table=XFTTable.Execute(builder.toString(), resource.user.getDBName(), resource.userName); + table=XFTTable.Execute(builder.toString(), user.getDBName(), resource.userName); return table; } } //handles everything else - public static class DefaultExperimentHandler implements FilteredExptListHandlerI{ + private static class DefaultExperimentHandler implements FilteredExptListHandlerI { @Override public boolean canHandle(SecureResource resource) { @@ -238,10 +239,11 @@ public class ExperimentListResource extends QueryOrganizerResource { @Override public XFTTable build(ExperimentListResource resource,Hashtable<String, Object> params) throws Exception { - XFTTable table=null; + final UserI user = resource.getUser(); + XFTTable table; params.put("title", "Matching experiments"); String rootElementName=resource.getRootElementName(); - QueryOrganizer qo = new QueryOrganizer(rootElementName,resource.user,ViewManager.ALL); + QueryOrganizer qo = new QueryOrganizer(rootElementName,user,ViewManager.ALL); resource.populateQuery(qo); @@ -252,11 +254,11 @@ public class ExperimentListResource extends QueryOrganizerResource { String query=qo.buildQuery(); - table=XFTTable.Execute(query, resource.user.getDBName(), resource.userName); + table=XFTTable.Execute(query, user.getDBName(), resource.userName); if(!ElementSecurity.IsSecureElement(rootElementName)){ - List<Object[]> remove=new ArrayList<Object[]>(); - Hashtable<String, Boolean> checked = new Hashtable<String,Boolean>(); + List<Object[]> remove= new ArrayList<>(); + Hashtable<String, Boolean> checked = new Hashtable<>(); String enS=qo.getFieldAlias("xnat:experimentData/extension_item/element_name"); if(enS==null) { @@ -282,7 +284,7 @@ public class ExperimentListResource extends QueryOrganizerResource { SecurityValues values = new SecurityValues(); values.put(element_name + "/project",project); - if (Permissions.canRead(resource.user,secureElement,values)) { + if (Permissions.canRead(user,secureElement,values)) { checked.put(element_name+project, Boolean.TRUE); }else{ checked.put(element_name+project, Boolean.FALSE); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ExperimentResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ExperimentResource.java index 6145475b3fa88ab65491308e3fafa3285e9f661f..9c11769e407f4ce4ab82be2c76b86e91ec67ccab 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ExperimentResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ExperimentResource.java @@ -29,6 +29,7 @@ import org.nrg.xft.event.EventUtils; import org.nrg.xft.event.persist.PersistentWorkflowI; import org.nrg.xft.event.persist.PersistentWorkflowUtils; import org.nrg.xft.exception.InvalidValueException; +import org.nrg.xft.security.UserI; import org.nrg.xft.utils.SaveItemHelper; import org.nrg.xft.utils.ValidationUtils.ValidationResults; import org.nrg.xft.utils.XftStringUtils; @@ -73,6 +74,7 @@ public class ExperimentResource extends ItemResource { final String projectId = (String) getParameter(request, "PROJECT_ID"); if (StringUtils.isNotBlank(projectId)) { + final UserI user = getUser(); _project = XnatProjectdata.getProjectByIDorAlias(projectId, user, false); _existing = XnatExperimentdata.GetExptByProjectIdentifier(projectId, _experimentId, user, false); } else { @@ -90,6 +92,7 @@ public class ExperimentResource extends ItemResource { final MediaType mt = overrideVariant(variant); if (_experiment == null && _experimentId != null) { + final UserI user = getUser(); _experiment = XnatExperimentdata.getXnatExperimentdatasById(_experimentId, user, false); if (_project != null) { @@ -159,6 +162,7 @@ public class ExperimentResource extends ItemResource { XFTItem item = loadItem(null, true, template); + final UserI user = getUser(); if (item == null) { String xsiType = getQueryVariable("xsiType"); if (xsiType != null) { @@ -516,6 +520,7 @@ public class ExperimentResource extends ItemResource { @Override public void handleDelete() { + final UserI user = getUser(); if (_experiment == null && _experimentId != null) { _experiment = XnatExperimentdata.getXnatExperimentdatasById(_experimentId, user, false); @@ -596,6 +601,7 @@ public class ExperimentResource extends ItemResource { } if (subject == null) { + final UserI user = getUser(); subject = new XnatSubjectdata(user); subject.setProject(_project.getId()); subject.setLabel(assessor.getSubjectId()); @@ -612,6 +618,7 @@ public class ExperimentResource extends ItemResource { } private XnatSubjectdata getSubject(XnatSubjectassessordata assessor) { + final UserI user = getUser(); XnatSubjectdata subject = XnatSubjectdata.getXnatSubjectdatasById(assessor.getSubjectId(), user, false); if (subject != null) { return subject; @@ -650,6 +657,7 @@ public class ExperimentResource extends ItemResource { retExp = XnatExperimentdata.getXnatExperimentdatasById(currExp.getId(), null, completeDocument); } + final UserI user = getUser(); if (retExp == null && currExp.getProject() != null && currExp.getLabel() != null) { retExp = XnatExperimentdata.GetExptByProjectIdentifier(currExp.getProject(), currExp.getLabel(), user, completeDocument); } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ExptAssessmentResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ExptAssessmentResource.java index 3bfda2bfc9398a8f472ed374e2a3945d94f696d6..6e52d0af54961e70d4625598ef77320104f26909 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ExptAssessmentResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ExptAssessmentResource.java @@ -21,7 +21,6 @@ import org.nrg.xdat.om.XnatImageassessordata; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.om.base.BaseXnatExperimentdata; import org.nrg.xdat.security.helpers.Permissions; -import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.XFTItem; import org.nrg.xft.XFTTable; import org.nrg.xft.event.EventMetaI; @@ -31,8 +30,8 @@ import org.nrg.xft.event.persist.PersistentWorkflowUtils.EventRequirementAbsent; import org.nrg.xft.exception.InvalidValueException; import org.nrg.xft.security.UserI; import org.nrg.xft.utils.SaveItemHelper; -import org.nrg.xft.utils.XftStringUtils; import org.nrg.xft.utils.ValidationUtils.ValidationResults; +import org.nrg.xft.utils.XftStringUtils; import org.nrg.xnat.helpers.xmlpath.XMLPathShortcuts; import org.nrg.xnat.utils.WorkflowUtils; import org.restlet.Context; @@ -56,6 +55,8 @@ public class ExptAssessmentResource extends ItemResource { public ExptAssessmentResource(Context context, Request request, Response response) { super(context, request, response); + final UserI user = getUser(); + String pID= (String)getParameter(request,"PROJECT_ID"); if(pID!=null){ proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); @@ -108,6 +109,7 @@ public class ExptAssessmentResource extends ItemResource { @Override public void handlePut() { + final UserI user = getUser(); try { XFTItem template=null; if (existing!=null && !this.isQueryVariableTrue("allowDataDeletion")){ @@ -233,7 +235,7 @@ public class ExptAssessmentResource extends ItemResource { } if(!matched){ - XnatExperimentdataShare pp= new XnatExperimentdataShare((UserI)user); + XnatExperimentdataShare pp= new XnatExperimentdataShare(user); pp.setProject(this.proj.getId()); assessor.setSharing_share(pp); } @@ -371,6 +373,7 @@ public class ExptAssessmentResource extends ItemResource { @Override public void handleDelete(){ + final UserI user = getUser(); if(assessor==null&& exptID!=null){ assessor=(XnatImageassessordata)XnatExperimentdata.getXnatExperimentdatasById(exptID, user, false); @@ -441,8 +444,9 @@ public class ExptAssessmentResource extends ItemResource { } @Override - public Representation getRepresentation(Variant variant) { + public Representation represent(Variant variant) { MediaType mt = overrideVariant(variant); + final UserI user = getUser(); if(assessor==null&& exptID!=null){ assessor=(XnatImageassessordata)XnatExperimentdata.getXnatExperimentdatasById(exptID, user, false); @@ -489,7 +493,7 @@ public class ExptAssessmentResource extends ItemResource { t.rows().add(row); } - Hashtable<String, Object> params = new Hashtable<String, Object>(); + Hashtable<String, Object> params = new Hashtable<>(); params.put("totalRecords", t.size()); return representTable(t, mt, params); } else { diff --git a/src/main/java/org/nrg/xnat/restlet/resources/InvestigatorListResource.java b/src/main/java/org/nrg/xnat/restlet/resources/InvestigatorListResource.java index 0ed8e7a938eb3e77c8193c9262eeb0423d558d9b..f420d3a26115a14e6b4840ff84474c93e63bffca 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/InvestigatorListResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/InvestigatorListResource.java @@ -12,6 +12,7 @@ package org.nrg.xnat.restlet.resources; import org.nrg.xft.XFTTable; import org.nrg.xft.exception.DBPoolException; +import org.nrg.xft.security.UserI; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Request; @@ -39,22 +40,23 @@ public class InvestigatorListResource extends SecureResource { } @Override - public Representation getRepresentation(Variant variant) { - Hashtable<String,Object> params=new Hashtable<String,Object>(); + public Representation represent(Variant variant) { + Hashtable<String,Object> params= new Hashtable<>(); params.put("title", "Investigators"); MediaType mt = overrideVariant(variant); try { - String query = "SELECT DISTINCT ON ( inv.lastname,inv.firstname) inv.firstname,inv.lastname,inv.institution,inv.department,inv.email,inv.xnat_investigatorData_id,login FROM xnat_investigatorData inv LEFT JOIN xdat_user u ON ((lower(inv.firstname)=lower(u.firstname) AND lower(inv.lastname)=lower(u.lastname)) OR inv.email=u.email) ORDER BY inv.lastname,inv.firstname"; + final UserI user = getUser(); + String query = "SELECT DISTINCT ON ( inv.lastname,inv.firstname) inv.firstname,inv.lastname,inv.institution,inv.department,inv.email,inv.xnat_investigatorData_id,login FROM xnat_investigatorData inv LEFT JOIN xdat_user u ON ((lower(inv.firstname)=lower(u.firstname) AND lower(inv.lastname)=lower(u.lastname)) OR inv.email=u.email) ORDER BY inv.lastname,inv.firstname"; table = XFTTable.Execute(query, user.getDBName(), user.getLogin()); - } catch (SQLException e) { - e.printStackTrace(); - } catch (DBPoolException e) { - e.printStackTrace(); + } catch (SQLException | DBPoolException e) { + logger.error("An error occurred retrieving investigators", e); } - if(table!=null)params.put("totalRecords", table.size()); - return this.representTable(table, mt, params); + if(table!=null) { + params.put("totalRecords", table.size()); + } + return representTable(table, mt, params); } } \ No newline at end of file diff --git a/src/main/java/org/nrg/xnat/restlet/resources/PARList.java b/src/main/java/org/nrg/xnat/restlet/resources/PARList.java index 75c27470940d3e10a86c953be5117486a66eeeff..5d41523852ca34a52a431286608351c9d27fa3d4 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/PARList.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/PARList.java @@ -11,6 +11,7 @@ package org.nrg.xnat.restlet.resources; import org.nrg.xft.XFTTable; +import org.nrg.xft.security.UserI; import org.restlet.Context; import org.restlet.data.Request; import org.restlet.data.Response; @@ -34,7 +35,8 @@ public class PARList extends SecureResource { @Override public Representation represent(Variant variant) { - Hashtable<String, Object> params = new Hashtable<>(); + final UserI user = getUser(); + final Hashtable<String, Object> params = new Hashtable<>(); try { final XFTTable table = XFTTable.Execute(String.format(PAR_QUERY, user.getEmail().toLowerCase()), user.getDBName(), user.getLogin()); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/PARResource.java b/src/main/java/org/nrg/xnat/restlet/resources/PARResource.java index e90dede4a5bdcd374b33b31fd7afb00958eb125c..2f0db407a93140d958e53d304396930196970414 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/PARResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/PARResource.java @@ -14,6 +14,7 @@ import org.apache.commons.lang3.StringUtils; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.security.helpers.Roles; import org.nrg.xft.XFTTable; +import org.nrg.xft.security.UserI; import org.nrg.xnat.turbine.utils.ProjectAccessRequest; import org.restlet.Context; import org.restlet.data.Request; @@ -32,12 +33,13 @@ import java.util.Objects; * @author timo */ public class PARResource extends SecureResource { - private static final Logger _log = LoggerFactory.getLogger(PARResource.class); - ProjectAccessRequest par = null; + private static final Logger _log = LoggerFactory.getLogger(PARResource.class); + private ProjectAccessRequest par = null; public PARResource(Context context, Request request, Response response) throws Exception { super(context, request, response); - String par_id = (String) getParameter(request, "PAR_ID"); + final UserI user = getUser(); + String par_id = (String) getParameter(request, "PAR_ID"); par = ProjectAccessRequest.RequestPARByGUID(par_id, user); if (par == null) { par = ProjectAccessRequest.RequestPARById(Integer.parseInt(par_id), user); @@ -83,6 +85,7 @@ public class PARResource extends SecureResource { return; } else { try { + final UserI user = getUser(); if (getQueryVariable("accept") != null) { par.process(user, true, getEventType(), getReason(), getComment()); } else if (getQueryVariable("decline") != null) { @@ -105,6 +108,7 @@ public class PARResource extends SecureResource { table.initTable(new String[]{"id", "proj_id", "create_date", "level"}); Hashtable<String, Object> params = new Hashtable<>(); try { + final UserI user = getUser(); ArrayList<ProjectAccessRequest> pars = ProjectAccessRequest.RequestPARsByUserEmail(user.getEmail(), user); for (ProjectAccessRequest par : pars) { Object[] row = new Object[4]; @@ -123,6 +127,7 @@ public class PARResource extends SecureResource { } private boolean isParUser() { + final UserI user = getUser(); return Objects.equals(par.getUserId(), user.getID()) || (par.getUserId() == null && StringUtils.equalsIgnoreCase(par.getEmail(), user.getEmail())); } } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProjSubExptAsstList.java b/src/main/java/org/nrg/xnat/restlet/resources/ProjSubExptAsstList.java index d0aca15768cb5ed845fdf56a2b79232a658abe3b..a8dc35cbf24ba74e4f8a0c2265aa3e155de82573 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjSubExptAsstList.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjSubExptAsstList.java @@ -21,14 +21,13 @@ import org.nrg.xft.XFTItem; import org.nrg.xft.XFTTable; import org.nrg.xft.db.ViewManager; import org.nrg.xft.event.EventUtils; -import org.nrg.xft.exception.DBPoolException; import org.nrg.xft.exception.InvalidValueException; import org.nrg.xft.schema.Wrappers.GenericWrapper.GenericWrapperElement; import org.nrg.xft.search.CriteriaCollection; import org.nrg.xft.search.QueryOrganizer; import org.nrg.xft.security.UserI; -import org.nrg.xft.utils.XftStringUtils; import org.nrg.xft.utils.ValidationUtils.ValidationResults; +import org.nrg.xft.utils.XftStringUtils; import org.nrg.xnat.helpers.xmlpath.XMLPathShortcuts; import org.restlet.Context; import org.restlet.data.MediaType; @@ -38,7 +37,6 @@ import org.restlet.data.Status; import org.restlet.resource.Representation; import org.restlet.resource.Variant; -import java.sql.SQLException; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; @@ -51,7 +49,9 @@ public class ProjSubExptAsstList extends QueryOrganizerResource { public ProjSubExptAsstList(Context context, Request request, Response response) { super(context, request, response); - String pID= (String)getParameter(request,"PROJECT_ID"); + final UserI user = getUser(); + + final String pID= (String)getParameter(request,"PROJECT_ID"); if(pID!=null){ proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); @@ -126,10 +126,9 @@ public class ProjSubExptAsstList extends QueryOrganizerResource { @Override public void handlePost() { - XFTItem item = null; - - try { - item=this.loadItem(null,true); + final UserI user = getUser(); + try { + XFTItem item = loadItem(null,true); if(item==null){ String xsiType=this.getQueryVariable("xsiType"); @@ -296,10 +295,11 @@ public class ProjSubExptAsstList extends QueryOrganizerResource { } @Override - public Representation getRepresentation(Variant variant) { + public Representation represent(Variant variant) { + final UserI user = getUser(); XFTTable table = null; if(assessed!=null){ - Representation rep=super.getRepresentation(variant); + Representation rep=super.represent(variant); if(rep!=null)return rep; try { @@ -351,25 +351,20 @@ public class ProjSubExptAsstList extends QueryOrganizerResource { } } } - } catch (SQLException e) { - logger.error("", e); - } catch (DBPoolException e) { - logger.error("", e); } catch (Exception e) { logger.error("", e); } - Hashtable<String, Object> params = new Hashtable<String, Object>(); - if (table != null) + Hashtable<String, Object> params = new Hashtable<>(); + if (table != null) { params.put("totalRecords", table.size()); + } return this.representTable(table, overrideVariant(variant), params); - } - Hashtable<String,Object> params=new Hashtable<String,Object>(); + Hashtable<String,Object> params= new Hashtable<>(); params.put("title", "Project Subject Experiment Assessors"); - if(table!=null)params.put("totalRecords", table.size()); - return this.representTable(table, overrideVariant(variant), params); + return representTable(null, overrideVariant(variant), params); } } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProjSubExptList.java b/src/main/java/org/nrg/xnat/restlet/resources/ProjSubExptList.java index aef98bc2de988ec6196fdf30b47511faf055e386..c700033fd88159f78c7bb77f026b2153c949f09e 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjSubExptList.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjSubExptList.java @@ -23,14 +23,12 @@ import org.nrg.xft.XFTItem; import org.nrg.xft.XFTTable; import org.nrg.xft.db.ViewManager; import org.nrg.xft.event.EventUtils; -import org.nrg.xft.exception.DBPoolException; import org.nrg.xft.exception.InvalidValueException; -import org.nrg.xft.schema.design.SchemaElementI; import org.nrg.xft.search.CriteriaCollection; import org.nrg.xft.search.QueryOrganizer; import org.nrg.xft.security.UserI; -import org.nrg.xft.utils.XftStringUtils; import org.nrg.xft.utils.ValidationUtils.ValidationResults; +import org.nrg.xft.utils.XftStringUtils; import org.nrg.xnat.helpers.xmlpath.XMLPathShortcuts; import org.nrg.xnat.restlet.actions.TriggerPipelines; import org.nrg.xnat.restlet.util.XNATRestConstants; @@ -42,7 +40,6 @@ import org.restlet.data.Status; import org.restlet.resource.Representation; import org.restlet.resource.Variant; -import java.sql.SQLException; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; @@ -53,53 +50,54 @@ public class ProjSubExptList extends SubjAssessmentAbst { String pID=null; String subID=null; + public ProjSubExptList(Context context, Request request, Response response) { super(context, request, response); - pID = (String) getParameter(request,"PROJECT_ID"); - if(pID!=null){ - proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); + pID = (String) getParameter(request, "PROJECT_ID"); + if (pID != null) { + final UserI user = getUser(); + + proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); if (proj == null) { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND, - "Unable to identify project " + pID); + "Unable to identify project " + pID); return; } - subID = (String) getParameter(request,"SUBJECT_ID"); - if(subID!=null){ - subject = XnatSubjectdata.GetSubjectByProjectIdentifier(proj - .getId(), subID, user, false); + subID = (String) getParameter(request, "SUBJECT_ID"); + if (subID != null) { + subject = XnatSubjectdata.GetSubjectByProjectIdentifier(proj.getId(), subID, user, false); - if(subject==null){ - subject = XnatSubjectdata.getXnatSubjectdatasById(subID, - user, false); + if (subject == null) { + subject = XnatSubjectdata.getXnatSubjectdatasById(subID, user, false); if (subject != null - && (proj != null && !subject.hasProject(proj - .getId()))) { + && (proj != null && !subject.hasProject(proj + .getId()))) { subject = null; } - } + } - if(subject!=null){ + if (subject != null) { this.getVariants().add( new Variant(MediaType.APPLICATION_JSON)); - this.getVariants().add(new Variant(MediaType.TEXT_HTML)); - this.getVariants().add(new Variant(MediaType.TEXT_XML)); - }else{ + this.getVariants().add(new Variant(MediaType.TEXT_HTML)); + this.getVariants().add(new Variant(MediaType.TEXT_XML)); + } else { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND, - "Unable to identify subject " + subID); - } - }else{ + "Unable to identify subject " + subID); + } + } else { this.getVariants().add(new Variant(MediaType.APPLICATION_JSON)); this.getVariants().add(new Variant(MediaType.TEXT_HTML)); this.getVariants().add(new Variant(MediaType.TEXT_XML)); } - }else{ + } else { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } - this.fieldMapping.putAll(XMLPathShortcuts.getInstance().getShortcuts(XMLPathShortcuts.EXPERIMENT_DATA,true)); + this.fieldMapping.putAll(XMLPathShortcuts.getInstance().getShortcuts(XMLPathShortcuts.EXPERIMENT_DATA, true)); } @Override @@ -109,178 +107,176 @@ public class ProjSubExptList extends SubjAssessmentAbst { @Override public void handlePost() { - XFTItem item = null; + try { + final UserI user = getUser(); - try { - item=this.loadItem(null,true); + XFTItem item = loadItem(null, true); - if(item==null){ - String xsiType=this.getQueryVariable("xsiType"); - if(xsiType!=null){ - item=XFTItem.NewItem(xsiType, user); - } + if (item == null) { + String xsiType = this.getQueryVariable("xsiType"); + if (xsiType != null) { + item = XFTItem.NewItem(xsiType, user); } + } - if(item==null){ - this.getResponse().setStatus(Status.CLIENT_ERROR_EXPECTATION_FAILED, "Need POST Contents"); - return; - } + if (item == null) { + this.getResponse().setStatus(Status.CLIENT_ERROR_EXPECTATION_FAILED, "Need POST Contents"); + return; + } - if(item.instanceOf("xnat:subjectAssessorData")){ - XnatSubjectassessordata expt = (XnatSubjectassessordata)BaseElement.GetGeneratedItem(item); + if (item.instanceOf("xnat:subjectAssessorData")) { + XnatSubjectassessordata expt = (XnatSubjectassessordata) BaseElement.GetGeneratedItem(item); - //MATCH PROJECT - if(this.proj==null && expt.getProject()!=null){ - proj = XnatProjectdata.getXnatProjectdatasById(expt.getProject(), user, false); - } + //MATCH PROJECT + if (this.proj == null && expt.getProject() != null) { + proj = XnatProjectdata.getXnatProjectdatasById(expt.getProject(), user, false); + } - if(this.proj!=null){ - if(expt.getProject()==null || expt.getProject().equals("")){ - expt.setProject(this.proj.getId()); - }else if(expt.getProject().equals(this.proj.getId())){ - }else{ - boolean matched=false; - for(XnatExperimentdataShareI pp : expt.getSharing_share()){ - if(pp.getProject().equals(this.proj.getId())){ - matched=true; - break; - } + if (this.proj != null) { + if (expt.getProject() == null || expt.getProject().equals("")) { + expt.setProject(this.proj.getId()); + } else if (expt.getProject().equals(this.proj.getId())) { + } else { + boolean matched = false; + for (XnatExperimentdataShareI pp : expt.getSharing_share()) { + if (pp.getProject().equals(this.proj.getId())) { + matched = true; + break; } + } - if(!matched){ - XnatExperimentdataShare pp= new XnatExperimentdataShare((UserI)user); - pp.setProject(this.proj.getId()); - expt.setSharing_share(pp); - } + if (!matched) { + XnatExperimentdataShare pp = new XnatExperimentdataShare((UserI) user); + pp.setProject(this.proj.getId()); + expt.setSharing_share(pp); } - }else{ - this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY,"Submitted experiment record must include the project attribute."); - return; } + } else { + this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY, "Submitted experiment record must include the project attribute."); + return; + } - //MATCH SUBJECT - if(this.subject!=null){ - expt.setSubjectId(this.subject.getId()); - }else{ - if(expt.getSubjectId()!=null && !expt.getSubjectId().equals("")){ - this.subject=XnatSubjectdata.getXnatSubjectdatasById(expt.getSubjectId(), user, false); + //MATCH SUBJECT + if (this.subject != null) { + expt.setSubjectId(this.subject.getId()); + } else { + if (expt.getSubjectId() != null && !expt.getSubjectId().equals("")) { + this.subject = XnatSubjectdata.getXnatSubjectdatasById(expt.getSubjectId(), user, false); - if(this.subject==null && expt.getProject()!=null && expt.getLabel()!=null){ - this.subject=XnatSubjectdata.GetSubjectByProjectIdentifier(expt.getProject(), expt.getSubjectId(),user, false); - } + if (this.subject == null && expt.getProject() != null && expt.getLabel() != null) { + this.subject = XnatSubjectdata.GetSubjectByProjectIdentifier(expt.getProject(), expt.getSubjectId(), user, false); + } - if(this.subject==null){ - for(XnatExperimentdataShareI pp : expt.getSharing_share()){ - this.subject=XnatSubjectdata.GetSubjectByProjectIdentifier(pp.getProject(), expt.getSubjectId(),user, false); - if(this.subject!=null){ - break; - } + if (this.subject == null) { + for (XnatExperimentdataShareI pp : expt.getSharing_share()) { + this.subject = XnatSubjectdata.GetSubjectByProjectIdentifier(pp.getProject(), expt.getSubjectId(), user, false); + if (this.subject != null) { + break; } } + } - if(this.subject==null){ - this.subject = new XnatSubjectdata((UserI)user); + if (this.subject == null) { + this.subject = new XnatSubjectdata((UserI) user); this.subject.setProject(this.proj.getId()); this.subject.setLabel(expt.getSubjectId()); this.subject.setId(XnatSubjectdata.CreateNewID()); - create(this.subject,false,true,newEventInstance(EventUtils.CATEGORY.DATA,EventUtils.AUTO_CREATE_SUBJECT)); + create(this.subject, false, true, newEventInstance(EventUtils.CATEGORY.DATA, EventUtils.AUTO_CREATE_SUBJECT)); expt.setSubjectId(this.subject.getId()); } } } - if(this.subject==null){ - this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY,"Submitted experiment record must include the subject."); + if (this.subject == null) { + this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY, "Submitted experiment record must include the subject."); return; } - //FIND PRE-EXISTING - XnatSubjectassessordata existing=null; - if(expt.getId()!=null){ - existing=(XnatSubjectassessordata)XnatExperimentdata.getXnatExperimentdatasById(expt.getId(), user, completeDocument); - } + //FIND PRE-EXISTING + XnatSubjectassessordata existing = null; + if (expt.getId() != null) { + existing = (XnatSubjectassessordata) XnatExperimentdata.getXnatExperimentdatasById(expt.getId(), user, completeDocument); + } - if(existing==null && expt.getProject()!=null && expt.getLabel()!=null){ - existing=(XnatSubjectassessordata)XnatExperimentdata.GetExptByProjectIdentifier(expt.getProject(), expt.getLabel(),user, completeDocument); - } + if (existing == null && expt.getProject() != null && expt.getLabel() != null) { + existing = (XnatSubjectassessordata) XnatExperimentdata.GetExptByProjectIdentifier(expt.getProject(), expt.getLabel(), user, completeDocument); + } - if(existing==null){ - for(XnatExperimentdataShareI pp : expt.getSharing_share()){ - existing=(XnatSubjectassessordata)XnatExperimentdata.GetExptByProjectIdentifier(pp.getProject(), pp.getLabel(),user, completeDocument); - if(existing!=null){ - break; - } + if (existing == null) { + for (XnatExperimentdataShareI pp : expt.getSharing_share()) { + existing = (XnatSubjectassessordata) XnatExperimentdata.GetExptByProjectIdentifier(pp.getProject(), pp.getLabel(), user, completeDocument); + if (existing != null) { + break; } } + } - if(existing==null){ - if(!Permissions.canCreate(user,expt)){ - this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN,"Specified user account has insufficient create privileges for experiments in this project."); + if (existing == null) { + if (!Permissions.canCreate(user, expt)) { + this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, "Specified user account has insufficient create privileges for experiments in this project."); return; - } - //IS NEW - if(expt.getId()==null || expt.getId().equals("")){ + } + //IS NEW + if (expt.getId() == null || expt.getId().equals("")) { expt.setId(XnatExperimentdata.CreateNewID()); - } - }else{ - this.getResponse().setStatus(Status.CLIENT_ERROR_CONFLICT,"Specified experiment already exists."); - return; - //MATCHED } + } else { + this.getResponse().setStatus(Status.CLIENT_ERROR_CONFLICT, "Specified experiment already exists."); + return; + //MATCHED + } - boolean allowDataDeletion=false; - if(this.getQueryVariable("allowDataDeletion")!=null && this.getQueryVariable("allowDataDeletion").equals("true")){ - allowDataDeletion=true; - } + boolean allowDataDeletion = false; + if (this.getQueryVariable("allowDataDeletion") != null && this.getQueryVariable("allowDataDeletion").equals("true")) { + allowDataDeletion = true; + } - if(StringUtils.isNotBlank(expt.getLabel()) && !XftStringUtils.isValidId(expt.getId())){ - this.getResponse().setStatus(Status.CLIENT_ERROR_EXPECTATION_FAILED,"Invalid character in experiment label."); + if (StringUtils.isNotBlank(expt.getLabel()) && !XftStringUtils.isValidId(expt.getId())) { + this.getResponse().setStatus(Status.CLIENT_ERROR_EXPECTATION_FAILED, "Invalid character in experiment label."); return; } - final ValidationResults vr = expt.validate(); - if (vr != null && !vr.isValid()) - { - this.getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST,vr.toFullString()); + if (vr != null && !vr.isValid()) { + this.getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, vr.toFullString()); return; - } + } - create(expt,false,allowDataDeletion,newEventInstance(EventUtils.CATEGORY.DATA, EventUtils.getAddModifyAction(expt.getXSIType(), (existing==null)))); + create(expt, false, allowDataDeletion, newEventInstance(EventUtils.CATEGORY.DATA, EventUtils.getAddModifyAction(expt.getXSIType(), (existing == null)))); - postSaveManageStatus(expt); + postSaveManageStatus(expt); - if(Permissions.canEdit(user,expt.getItem())){ - if(this.isQueryVariableTrue(XNATRestConstants.TRIGGER_PIPELINES) || this.containsAction(XNATRestConstants.TRIGGER_PIPELINES)){ - TriggerPipelines tp = new TriggerPipelines(expt,this.isQueryVariableTrue(XNATRestConstants.SUPRESS_EMAIL),user); + if (Permissions.canEdit(user, expt.getItem())) { + if (this.isQueryVariableTrue(XNATRestConstants.TRIGGER_PIPELINES) || this.containsAction(XNATRestConstants.TRIGGER_PIPELINES)) { + TriggerPipelines tp = new TriggerPipelines(expt, this.isQueryVariableTrue(XNATRestConstants.SUPRESS_EMAIL), user); tp.call(); } } this.returnSuccessfulCreateFromList(expt.getId()); - }else{ - this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY,"Only xnat:Subject documents can be PUT to this address."); - } + } else { + this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY, "Only xnat:Subject documents can be PUT to this address."); + } } catch (ActionException e) { - this.getResponse().setStatus(e.getStatus(),e.getMessage()); + this.getResponse().setStatus(e.getStatus(), e.getMessage()); return; } catch (InvalidValueException e) { this.getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); - logger.error("",e); - } catch (Exception e) { - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - logger.error("",e); + logger.error("", e); + } catch (Exception e) { + this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); + logger.error("", e); } } - - @Override - public Representation getRepresentation(Variant variant) { - Representation rep=super.getRepresentation(variant); - if(rep!=null)return rep; + public Representation represent(Variant variant) { + Representation rep=super.represent(variant); + if(rep!=null) { + return rep; + } XFTTable table = null; @@ -289,6 +285,8 @@ public class ProjSubExptList extends SubjAssessmentAbst { return null; } + final UserI user = getUser(); + try { final SecurityValues values = new SecurityValues(); values.put("xnat:subjectData/project", proj.getId()); @@ -343,8 +341,8 @@ public class ProjSubExptList extends SubjAssessmentAbst { if(table.size()>0){ if(!ElementSecurity.IsSecureElement(rootElementName)){ - List<Object[]> remove=new ArrayList<Object[]>(); - Hashtable<String, Boolean> checked = new Hashtable<String,Boolean>(); + List<Object[]> remove= new ArrayList<>(); + Hashtable<String, Boolean> checked = new Hashtable<>(); String enS=qo.getFieldAlias("xnat:experimentData/extension_item/element_name"); if(enS==null) { @@ -401,15 +399,11 @@ public class ProjSubExptList extends SubjAssessmentAbst { } } } - } catch (SQLException e) { - logger.error("",e); - } catch (DBPoolException e) { - logger.error("",e); } catch (Exception e) { logger.error("",e); } - Hashtable<String,Object> params=new Hashtable<String,Object>(); + Hashtable<String,Object> params= new Hashtable<>(); if (table != null) params.put("totalRecords", table.size()); return this.representTable(table, overrideVariant(variant), params); 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 723063c17d47d0aa80ac47341eeddbd68856ded0..f882797e1d79cd64caa13ae41d43eff7778c7a57 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectAccessibilityResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectAccessibilityResource.java @@ -15,6 +15,7 @@ import org.nrg.xdat.security.helpers.Permissions; import org.nrg.xft.event.EventMetaI; import org.nrg.xft.event.EventUtils; import org.nrg.xft.event.persist.PersistentWorkflowI; +import org.nrg.xft.security.UserI; import org.nrg.xnat.utils.WorkflowUtils; import org.restlet.Context; import org.restlet.data.MediaType; @@ -34,7 +35,7 @@ public class ProjectAccessibilityResource extends SecureResource { String pID= (String)getParameter(request,"PROJECT_ID"); if(pID!=null){ - proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); + proj = XnatProjectdata.getProjectByIDorAlias(pID, getUser(), false); } access=(String)getParameter(request,"ACCESS_LEVEL"); @@ -61,16 +62,17 @@ public class ProjectAccessibilityResource extends SecureResource { public void handlePut() { if(proj!=null && access!=null){ try { - if (!Permissions.canDelete(user,proj)){ + final UserI user = getUser(); + if (!Permissions.canDelete(user, proj)){ getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); return; } String currentAccess = proj.getPublicAccessibility(); if (!currentAccess.equals(access)){ - PersistentWorkflowI wrk=WorkflowUtils.buildProjectWorkflow(user, proj,newEventInstance(EventUtils.CATEGORY.PROJECT_ACCESS,EventUtils.MODIFY_PROJECT_ACCESS)); + PersistentWorkflowI wrk=WorkflowUtils.buildProjectWorkflow(user, proj, newEventInstance(EventUtils.CATEGORY.PROJECT_ACCESS, EventUtils.MODIFY_PROJECT_ACCESS)); EventMetaI c=wrk.buildEvent(); - if(Permissions.setDefaultAccessibility(proj.getId(),access, true,user,c)){ + if(Permissions.setDefaultAccessibility(proj.getId(), access, true, user, c)){ WorkflowUtils.complete(wrk, c); } } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProjectArchive.java b/src/main/java/org/nrg/xnat/restlet/resources/ProjectArchive.java index 1c6cd584c65d3fc78c6d23ba4439fb0176576d1a..31127d58aeccd1017ab3c7f0a8095450bc31c4f5 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectArchive.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectArchive.java @@ -30,20 +30,19 @@ public class ProjectArchive extends ItemResource { String pID= (String)getParameter(request,"PROJECT_ID"); if(pID!=null){ - proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); + proj = XnatProjectdata.getProjectByIDorAlias(pID, getUser(), false); } if(proj!=null){ this.getVariants().add(new Variant(MediaType.TEXT_XML)); }else{ response.setStatus(Status.CLIENT_ERROR_NOT_FOUND,"Unable to find project '"+ pID + "'"); - return; } } @Override - public Representation getRepresentation(Variant variant) { + public Representation represent(Variant variant) { MediaType mt = overrideVariant(variant); if(proj!=null){ 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 ac0b747a2cfb22ff704a3a3f621bff01595ab2e4..8ae1d8f9dc0db7d4b6c1fbd85fdd689e8381c86d 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectGroupResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectGroupResource.java @@ -1,24 +1,16 @@ package org.nrg.xnat.restlet.resources; -import java.sql.SQLException; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.math.NumberUtils; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.math.NumberUtils; 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; -import org.nrg.xdat.security.PermissionCriteriaI; -import org.nrg.xdat.security.UserGroup; -import org.nrg.xdat.security.UserGroupI; +import org.nrg.xdat.security.*; import org.nrg.xdat.security.helpers.Groups; import org.nrg.xdat.security.helpers.Permissions; import org.nrg.xdat.security.helpers.UserHelper; -import org.nrg.xft.XFT; import org.nrg.xft.XFTTable; import org.nrg.xft.event.EventMetaI; import org.nrg.xft.event.EventUtils; @@ -36,8 +28,10 @@ import org.restlet.data.Status; import org.restlet.resource.Representation; import org.restlet.resource.Variant; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; +import java.sql.SQLException; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; public class ProjectGroupResource extends SecureResource { public static Logger logger = Logger.getLogger(ProjectGroupResource.class); @@ -61,7 +55,7 @@ public class ProjectGroupResource extends SecureResource { String pID= (String)getParameter(request,"PROJECT_ID"); if(pID!=null){ - proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); + proj = XnatProjectdata.getProjectByIDorAlias(pID, getUser(), false); } gID =(String)getParameter(request,"GROUP_ID"); @@ -119,6 +113,7 @@ public class ProjectGroupResource extends SecureResource { getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); return; }else{ + final UserI user = getUser(); try { if(UserHelper.getUserHelperService(user).canDelete(proj)){ final PersistentWorkflowI workflow=WorkflowUtils.getOrCreateWorkflowData(null, user, XnatProjectdata.SCHEMA_ELEMENT_NAME, proj.getId(),proj.getId(),EventUtils.newEventInstance(EventUtils.CATEGORY.PROJECT_ADMIN,EventUtils.TYPE.WEB_SERVICE,"Remove Group")); @@ -152,6 +147,7 @@ public class ProjectGroupResource extends SecureResource { getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); }else{ try { + final UserI user = getUser(); if(Permissions.canDelete(user,proj)){ boolean isNew = false; Map<String,Object> props = Maps.newHashMap(); @@ -281,19 +277,21 @@ public class ProjectGroupResource extends SecureResource { @Override public Representation represent(Variant variant) { - XFTTable table=null; if(proj!=null){ if(group==null){ //return a list of groups try { StringBuffer query = new StringBuffer("SELECT ug.id, ug.displayname,ug.tag,ug.xdat_usergroup_id, COUNT(map.groups_groupid_xdat_user_xdat_user_id) AS users FROM xdat_userGroup ug LEFT JOIN xdat_user_groupid map ON ug.id=map.groupid WHERE tag='").append(proj.getId()).append("' "); query.append(" GROUP BY ug.id, ug.displayname,ug.tag,ug.xdat_usergroup_id ORDER BY ug.displayname DESC;"); - table = XFTTable.Execute(query.toString(), user.getDBName(), user.getLogin()); + final UserI user = getUser(); + final XFTTable table = XFTTable.Execute(query.toString(), user.getDBName(), user.getLogin()); - Hashtable<String,Object> params=new Hashtable<String,Object>(); + Hashtable<String,Object> params= new Hashtable<>(); params.put("title", "Projects"); - if(table!=null)params.put("totalRecords", table.size()); + if(table!=null) { + params.put("totalRecords", table.size()); + } return this.representTable(table, overrideVariant(variant), params); } catch (SQLException e) { logger.error("",e); 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 0c6a1fc5de2ac18f98a715112675801cc62b8cb1..86d01b8842595221a1c0602107d889f3fafd6600 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectListResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectListResource.java @@ -79,6 +79,7 @@ public class ProjectListResource extends QueryOrganizerResource { try { item = this.loadItem("xnat:projectData", true); + final UserI user = getUser(); if (item == null) { String xsiType = this.getQueryVariable("xsiType"); if (xsiType != null) { @@ -208,7 +209,7 @@ public class ProjectListResource extends QueryOrganizerResource { public Representation handle(SecureResource resource, Variant variant) throws Exception { DisplaySearch ds = new DisplaySearch(); - UserI user = resource.user; + UserI user = resource.getUser(); XFTTable table = null; try { ds.setUser(user); @@ -511,15 +512,16 @@ public class ProjectListResource extends QueryOrganizerResource { throw new Exception("You must specify one of the following values for the permissions parameter: " + Joiner.on(", ").join(PERMISSIONS)); } - final String dataType = resource.getQueryVariable("dataType"); - final UserHelperServiceI userHelperService = UserHelper.getUserHelperService(resource.user); + final String dataType = resource.getQueryVariable("dataType"); + final UserI user = resource.getUser(); + final UserHelperServiceI userHelperService = UserHelper.getUserHelperService(user); if (userHelperService != null) { final Map<Object, Object> projects = userHelperService.getCachedItemValuesHash("xnat:projectData", null, false, "xnat:projectData/ID", "xnat:projectData/secondary_ID"); for (final Object key : projects.keySet()) { final String projectId = (String) key; // If no data type is specified, we check both MR and PET session data permissions. This is basically // tailored for checking for projects to which the user can upload imaging data. - final boolean canEdit = StringUtils.isBlank(dataType) ? userHelperService.hasEditAccessToSessionDataByTag(projectId) : Permissions.can(resource.user, dataType + "/project", projectId, permissions); + final boolean canEdit = StringUtils.isBlank(dataType) ? userHelperService.hasEditAccessToSessionDataByTag(projectId) : Permissions.can(user, dataType + "/project", projectId, permissions); if (canEdit) { table.insertRowItems(projectId, projects.get(projectId)); } @@ -541,7 +543,7 @@ public class ProjectListResource extends QueryOrganizerResource { public Representation handle(SecureResource resource, Variant variant) throws Exception { ProjectListResource projResource = (ProjectListResource) resource; XFTTable table; - UserI user = resource.user; + UserI user = resource.getUser(); try { final String re = projResource.getRootElementName(); 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 3292ce80832b1ec697418a8d851a2067503f282c..c9c0a1149d3c8d906dd5672348821d0b639ba890 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectMemberResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectMemberResource.java @@ -54,92 +54,94 @@ public class ProjectMemberResource extends SecureResource { ArrayList<String> unknown= new ArrayList<>(); String gID=null; boolean displayHiddenUsers = false; - + public ProjectMemberResource(Context context, Request request, Response response) { super(context, request, response); - - this.getVariants().add(new Variant(MediaType.APPLICATION_JSON)); - this.getVariants().add(new Variant(MediaType.TEXT_HTML)); - this.getVariants().add(new Variant(MediaType.TEXT_XML)); - - String pID= getUrlEncodedParameter(request, "PROJECT_ID"); - if(pID!=null){ - proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); - } - - gID = getUrlEncodedParameter(request, "GROUP_ID"); - - group=Groups.getGroup(gID); - - if(group==null){ - group=Groups.getGroup(pID + "_" +gID); - } - - if(group==null){ - try { - for(UserGroupI gp: Groups.getGroupsByTag(pID)){ - if(StringUtils.equals(gID, gp.getDisplayname())){ - group=gp; - break; - } + + this.getVariants().add(new Variant(MediaType.APPLICATION_JSON)); + this.getVariants().add(new Variant(MediaType.TEXT_HTML)); + this.getVariants().add(new Variant(MediaType.TEXT_XML)); + + final UserI user = getUser(); + + String pID = getUrlEncodedParameter(request, "PROJECT_ID"); + if (pID != null) { + proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); + } + + gID = getUrlEncodedParameter(request, "GROUP_ID"); + + group = Groups.getGroup(gID); + + if (group == null) { + group = Groups.getGroup(pID + "_" + gID); + } + + if (group == null) { + try { + for (UserGroupI gp : Groups.getGroupsByTag(pID)) { + if (StringUtils.equals(gID, gp.getDisplayname())) { + group = gp; + break; } - } catch (Exception e) { - logger.error("",e); } + } catch (Exception e) { + logger.error("", e); } - + } - String tempValue =(String)getParameter(request,"USER_ID"); - try { - String[] ids; - if(tempValue.contains(",")){ - ids=tempValue.split(","); - }else{ - ids=new String[]{tempValue}; - } - for (final String id : ids) { - String uID = id.trim(); - Integer xdat_user_id = null; - try { - xdat_user_id = Integer.parseInt(uID); - } catch (NumberFormatException ignored) { + String tempValue = (String) getParameter(request, "USER_ID"); + try { + String[] ids; + if (tempValue.contains(",")) { + ids = tempValue.split(","); + } else { + ids = new String[] {tempValue}; + } - } + for (final String id : ids) { + String uID = id.trim(); + Integer xdat_user_id = null; + try { + xdat_user_id = Integer.parseInt(uID); + } catch (NumberFormatException ignored) { + } - if (xdat_user_id == null) { - //login or email - UserI newUser = null; - try { - newUser = Users.getUser(uID); - } catch (UserNotFoundException ignored) { - } - if (newUser == null) { - //by email - List<UserI> items = Users.getUsersByEmail(uID); - if (items.size() > 0) { - newUsers.addAll(items); - } else { - unknown.add(uID); - } + + if (xdat_user_id == null) { + //login or email + UserI newUser = null; + try { + newUser = Users.getUser(uID); + } catch (UserNotFoundException ignored) { + } + if (newUser == null) { + //by email + List<UserI> items = Users.getUsersByEmail(uID); + if (items.size() > 0) { + newUsers.addAll(items); } else { - newUsers.add(newUser); + unknown.add(uID); } } else { - UserI tempUser = Users.getUser(xdat_user_id); - if (tempUser != null) { - newUsers.add(tempUser); - } + newUsers.add(newUser); + } + } else { + UserI tempUser = Users.getUser(xdat_user_id); + if (tempUser != null) { + newUsers.add(tempUser); } } - } catch (Exception e) { - logger.error("",e); - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } - displayHiddenUsers = Boolean.parseBoolean((String)getParameter(request, "DISPLAY_HIDDEN_USERS")); - + } catch (Exception e) { + logger.error("", e); + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } + displayHiddenUsers = Boolean.parseBoolean((String) getParameter(request, "DISPLAY_HIDDEN_USERS")); + + } @Override public boolean allowPut() { @@ -156,6 +158,7 @@ public class ProjectMemberResource extends SecureResource { if(proj==null || group==null || newUsers.size()==0){ getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); }else{ + final UserI user = getUser(); try { if(Permissions.canDelete(user,proj)){ try { @@ -183,6 +186,7 @@ public class ProjectMemberResource extends SecureResource { getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); }else{ try { + final UserI user = getUser(); if(Permissions.canDelete(user,proj)){ if (unknown.size()>0){ //NEW USER @@ -271,6 +275,7 @@ public class ProjectMemberResource extends SecureResource { query.append(" and enabled = 1 "); } query.append(" ORDER BY g.id DESC;"); + final UserI user = getUser(); table = XFTTable.Execute(query.toString(), user.getDBName(), user.getLogin()); } catch (SQLException | DBPoolException e) { logger.error("",e); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProjectPARListResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ProjectPARListResource.java index f228a616c57c1e408c595083430f1cefb82d779a..21a9809f413bf419df3ca6cccdea40607592c003 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectPARListResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectPARListResource.java @@ -12,6 +12,7 @@ package org.nrg.xnat.restlet.resources; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xft.XFTTable; +import org.nrg.xft.security.UserI; import org.nrg.xnat.turbine.utils.ProjectAccessRequest; import org.restlet.Context; import org.restlet.data.MediaType; @@ -31,9 +32,11 @@ public class ProjectPARListResource extends SecureResource { XnatProjectdata proj=null; public ProjectPARListResource(Context context, Request request, Response response) throws Exception { - super(context, request, response); - String pID = (String) getParameter(request,"PROJECT_ID"); + + final UserI user = getUser(); + final String pID = (String) getParameter(request, "PROJECT_ID"); + if (pID != null) { proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); } @@ -53,9 +56,10 @@ public class ProjectPARListResource extends SecureResource { @Override public Representation represent(Variant variant) { XFTTable table = new XFTTable(); - Hashtable<String,Object> params=new Hashtable<String,Object>(); + Hashtable<String,Object> params= new Hashtable<>(); if (ProjectAccessRequest.CREATED_PAR_TABLE) { try { + final UserI user = getUser(); table = XFTTable .Execute( "SELECT par.par_id,par.proj_id,par.level,par.create_date,par.email,u.login,p.secondary_id,par.approved, par.approval_date FROM xs_par_table par LEFT JOIN xnat_projectData p ON par.proj_id=p.id LEFT JOIN xdat_user u ON par.approver_id=u.xdat_user_id WHERE par.proj_id='" 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 08dc5bac5b8c74853ae082909f887789440db166..4a657327bdfa386b02dc3122237f229dfb11e8de 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectPipelineListResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectPipelineListResource.java @@ -38,7 +38,7 @@ public class ProjectPipelineListResource extends SecureResource { pID= (String)getParameter(request,"PROJECT_ID"); if(pID!=null){ - proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); + proj = XnatProjectdata.getProjectByIDorAlias(pID, getUser(), false); } } @@ -67,7 +67,7 @@ public class ProjectPipelineListResource extends SecureResource { if (isUserAuthorized) { try { ArcProject arcProject = ArcSpecManager.GetFreshInstance().getProjectArc(proj.getId()); - boolean success = PipelineRepositoryManager.GetInstance().delete(arcProject, pathToPipeline, datatype, user); + boolean success = PipelineRepositoryManager.GetInstance().delete(arcProject, pathToPipeline, datatype, getUser()); 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" ); @@ -108,7 +108,7 @@ public class ProjectPipelineListResource extends SecureResource { private boolean isUserAuthorized() { boolean isUserAuthorized = false; try { - isUserAuthorized = Permissions.canDelete(user,proj); + isUserAuthorized = Permissions.canDelete(getUser(),proj); }catch(Exception e) { e.printStackTrace(); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); 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 bbbd370c4f5f30d9cbe6da090c3cc2bd7cccdcc2..3f2a771cf43303da08423144c6cc67dcbd5eb10e 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectResource.java @@ -26,6 +26,7 @@ import org.nrg.xft.event.EventUtils; import org.nrg.xft.event.persist.PersistentWorkflowI; import org.nrg.xft.event.persist.PersistentWorkflowUtils; import org.nrg.xft.exception.InvalidPermissionException; +import org.nrg.xft.security.UserI; import org.nrg.xft.utils.XftStringUtils; import org.nrg.xnat.helpers.xmlpath.XMLPathShortcuts; import org.nrg.xnat.turbine.utils.ArcSpecManager; @@ -61,7 +62,7 @@ public class ProjectResource extends ItemResource { projectId = (String) getParameter(request, "PROJECT_ID"); if (projectId != null) { - project = XnatProjectdata.getProjectByIDorAlias(projectId, user, false); + project = XnatProjectdata.getProjectByIDorAlias(projectId, getUser(), false); } if (project != null) { @@ -84,6 +85,8 @@ public class ProjectResource extends ItemResource { @Override public void handleDelete() { + final UserI user = getUser(); + if (user == null || user.isGuest()) { getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); } else { @@ -125,6 +128,7 @@ public class ProjectResource extends ItemResource { @Override public void handlePut() { + final UserI user = getUser(); if (user == null || user.isGuest()) { getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); } else { diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProjectSearchResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ProjectSearchResource.java index 5737ab14719f8d38e4a10b2925092cc82d6c3bf7..44760f254f17cfd77f9c30a18b4aab117fc12455 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectSearchResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectSearchResource.java @@ -33,8 +33,8 @@ import org.xml.sax.SAXException; import java.io.Reader; public class ProjectSearchResource extends ItemResource { - XdatStoredSearch xss = null; - String sID=null; + private XdatStoredSearch xss = null; + private String sID =null; XnatProjectdata proj=null; public ProjectSearchResource(Context context, Request request, Response response) { @@ -45,7 +45,7 @@ public class ProjectSearchResource extends ItemResource { String pID= (String)getParameter(request,"PROJECT_ID"); if(pID!=null){ - proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); + proj = XnatProjectdata.getProjectByIDorAlias(pID, getUser(), false); if(proj!=null){ this.getVariants().add(new Variant(MediaType.TEXT_XML)); @@ -64,14 +64,14 @@ public class ProjectSearchResource extends ItemResource { } @Override - public Representation getRepresentation(Variant variant) { + public Representation represent(Variant variant) { MediaType mt = overrideVariant(variant); if(xss==null && sID!=null){ if(sID.startsWith("@")){ xss=proj.getDefaultSearch(sID.substring(1)); }else{ - xss= XdatStoredSearch.getXdatStoredSearchsById(sID, user, true); + xss= XdatStoredSearch.getXdatStoredSearchsById(sID, getUser(), true); } } @@ -107,59 +107,59 @@ public class ProjectSearchResource extends ItemResource { @Override public void handlePut() { - try { - Reader sax=this.getRequest().getEntity().getReader(); - - SAXReader reader = new SAXReader(user); - XFTItem item = reader.parse(sax); - - if(!item.instanceOf("xdat:stored_search")){ - this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); - return; - } - XdatStoredSearch search = new XdatStoredSearch(item); - - if(search.getId()==null || !search.getId().equals(sID)){ - search.setId(sID); - } - - boolean found=false; - for(XdatStoredSearchAllowedUser au : search.getAllowedUser()){ - if(au.getLogin().equals(user.getLogin())){ - found=true; - } - } - if(!found){ - XdatStoredSearchAllowedUser au = new XdatStoredSearchAllowedUser((UserI)user); - au.setLogin(user.getLogin()); - search.setAllowedUser(au); - } - - PersistentWorkflowI wrk= PersistentWorkflowUtils.getOrCreateWorkflowData(null, user, search.getItem(), EventUtils.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN, EventUtils.TYPE.WEB_SERVICE, "Modified Project stored search")); - try { - SaveItemHelper.authorizedSave(search,user, false, true,wrk.buildEvent()); - PersistentWorkflowUtils.complete(wrk, wrk.buildEvent()); - } catch (Exception e) { - PersistentWorkflowUtils.fail(wrk, wrk.buildEvent()); - throw e; - } - } catch (SAXException e) { - logger.error("",e); + try { + final UserI user = getUser(); + Reader sax=this.getRequest().getEntity().getReader(); + + SAXReader reader = new SAXReader(user); + XFTItem item = reader.parse(sax); + + if(!item.instanceOf("xdat:stored_search")){ this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); + return; + } + XdatStoredSearch search = new XdatStoredSearch(item); + + if(search.getId()==null || !search.getId().equals(sID)){ + search.setId(sID); + } + + boolean found=false; + for(XdatStoredSearchAllowedUser au : search.getAllowedUser()){ + if(au.getLogin().equals(user.getLogin())){ + found=true; + } + } + if(!found){ + XdatStoredSearchAllowedUser au = new XdatStoredSearchAllowedUser(user); + au.setLogin(user.getLogin()); + search.setAllowedUser(au); + } + + PersistentWorkflowI wrk= PersistentWorkflowUtils.getOrCreateWorkflowData(null, user, search.getItem(), EventUtils.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN, EventUtils.TYPE.WEB_SERVICE, "Modified Project stored search")); + try { + SaveItemHelper.authorizedSave(search,user, false, true,wrk.buildEvent()); + PersistentWorkflowUtils.complete(wrk, wrk.buildEvent()); } catch (Exception e) { - logger.error("",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } + PersistentWorkflowUtils.fail(wrk, wrk.buildEvent()); + throw e; + } + } catch (SAXException e) { + logger.error("",e); + this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); + } catch (Exception e) { + logger.error("",e); + this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } + } - - @Override public void handleDelete() { if(sID!=null){ try { + final UserI user = getUser(); XdatStoredSearch search = XdatStoredSearch.getXdatStoredSearchsById(sID, user, false); - + if(search!=null){ XdatStoredSearchAllowedUser mine=null; for(XdatStoredSearchAllowedUser au : search.getAllowedUser()){ diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProjectSubjectList.java b/src/main/java/org/nrg/xnat/restlet/resources/ProjectSubjectList.java index 65f1c96cf13d6d383788c02800af100f4418f4fb..4cc92e0cc65bcd063c9f073a30565a47966661ca 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectSubjectList.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectSubjectList.java @@ -49,7 +49,7 @@ public class ProjectSubjectList extends QueryOrganizerResource { String pID= (String)getParameter(request,"PROJECT_ID"); if(pID!=null){ - proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); + proj = XnatProjectdata.getProjectByIDorAlias(pID, getUser(), false); if(proj!=null){ @@ -77,8 +77,9 @@ public class ProjectSubjectList extends QueryOrganizerResource { try { item=this.loadItem("xnat:subjectData",true); - - if(item==null){ + + final UserI user = getUser(); + if(item == null){ item=XFTItem.NewItem("xnat:subjectData", user); } @@ -108,7 +109,7 @@ public class ProjectSubjectList extends QueryOrganizerResource { } if(!matched){ - XnatProjectparticipantI pp= new XnatProjectparticipant((UserI)user); + XnatProjectparticipantI pp= new XnatProjectparticipant(user); ((XnatProjectparticipant)pp).setProject(this.proj.getId()); sub.setSharing_share((XnatProjectparticipant)pp); } @@ -124,12 +125,12 @@ public class ProjectSubjectList extends QueryOrganizerResource { } if(existing==null && sub.getProject()!=null && sub.getLabel()!=null){ - existing=XnatSubjectdata.GetSubjectByProjectIdentifier(sub.getProject(), sub.getLabel(),user, completeDocument); + existing=XnatSubjectdata.GetSubjectByProjectIdentifier(sub.getProject(), sub.getLabel(), user, completeDocument); } if(existing==null){ for(XnatProjectparticipantI pp : sub.getSharing_share()){ - existing=XnatSubjectdata.GetSubjectByProjectIdentifier(pp.getProject(), pp.getLabel(),user, completeDocument); + existing=XnatSubjectdata.GetSubjectByProjectIdentifier(pp.getProject(), pp.getLabel(), user, completeDocument); if(existing!=null){ break; } @@ -137,7 +138,7 @@ public class ProjectSubjectList extends QueryOrganizerResource { } if(existing==null){ - if(!Permissions.canCreate(user,sub)){ + if(!Permissions.canCreate(user, sub)){ this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN,"Specified user account has insufficient create privileges for subjects in this project."); return; } @@ -207,15 +208,16 @@ public class ProjectSubjectList extends QueryOrganizerResource { } @Override - public Representation getRepresentation(Variant variant) { + public Representation represent(Variant variant) { XFTTable table = null; if(proj!=null){ - final Representation rep=super.getRepresentation(variant); + final Representation rep=super.represent(variant); if(rep!=null)return rep; try { + final UserI user = getUser(); final QueryOrganizer qo = new QueryOrganizer(this.getRootElementName(), user, - ViewManager.ALL); + ViewManager.ALL); this.populateQuery(qo); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProjectUserListResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ProjectUserListResource.java index 9acf245cb52daca54bc32a064de693a2908ff4fd..fd02b112a73b2de0176972d5c336bdbfab20deda 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjectUserListResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjectUserListResource.java @@ -19,6 +19,7 @@ import org.nrg.xdat.security.helpers.Permissions; import org.nrg.xdat.security.helpers.Roles; import org.nrg.xft.XFTTable; import org.nrg.xft.exception.DBPoolException; +import org.nrg.xft.security.UserI; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Request; @@ -48,6 +49,7 @@ public class ProjectUserListResource extends SecureResource { getVariants().add(new Variant(MediaType.TEXT_XML)); final String projectId = (String) getParameter(request, "PROJECT_ID"); + final UserI user = getUser(); _project = org.apache.commons.lang3.StringUtils.isNotBlank(projectId) ? XnatProjectdata.getProjectByIDorAlias(projectId, user, false) : null; if (_project == null) { _displayHiddenUsers = false; @@ -67,11 +69,15 @@ public class ProjectUserListResource extends SecureResource { final XFTTable table; if (_project != null) { final 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(_project.getId()).append("' "); + if(this.getQueryVariable("includeAllDataAccess")!=null && this.getQueryVariable("includeAllDataAccess").equalsIgnoreCase("true")){ + query.append(" OR g.id ='ALL_DATA_ADMIN' "); + } try { if(!_displayHiddenUsers){ query.append(" and enabled = 1 "); } query.append(" ORDER BY g.id DESC;"); + final UserI user = getUser(); table = XFTTable.Execute(query.toString(), user.getDBName(), user.getLogin()); } catch (SQLException | DBPoolException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "An error occurred trying to run the following query: " + query.toString(), e); @@ -97,7 +103,7 @@ public class ProjectUserListResource extends SecureResource { try { List<String> projectUserResourceWhitelist = getSerializer().deserializeJson(config, TYPE_REFERENCE_LIST_STRING); if (projectUserResourceWhitelist != null) { - return projectUserResourceWhitelist.contains(user.getUsername()); + return projectUserResourceWhitelist.contains(getUser().getUsername()); } } catch (IOException e) { logger.error("", e); 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 6f6a2e2aae23f058d7641082817a0ee55dbf3ba5..3582fe1997232cb65436b52399c5f12b6bed00c6 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProjtExptPipelineResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProjtExptPipelineResource.java @@ -30,6 +30,7 @@ import org.nrg.xft.event.EventMetaI; import org.nrg.xft.event.EventUtils; import org.nrg.xft.event.persist.PersistentWorkflowI; import org.nrg.xft.event.persist.PersistentWorkflowUtils; +import org.nrg.xft.security.UserI; import org.nrg.xnat.exceptions.ValidationException; import org.nrg.xnat.restlet.actions.FixScanTypes; import org.nrg.xnat.restlet.actions.PullSessionDataFromHeaders; @@ -60,8 +61,9 @@ public class ProjtExptPipelineResource extends SecureResource { String pID = (String) getParameter(request,"PROJECT_ID"); if (pID != null) { - proj = XnatProjectdata.getXnatProjectdatasById(pID, user, false); + final UserI user = getUser(); + proj = XnatProjectdata.getXnatProjectdatasById(pID, user, false); step = (String) getParameter(request,"STEP_ID"); if (step != null) { String exptID = (String) getParameter(request,"EXPT_ID"); @@ -122,17 +124,18 @@ public class ProjtExptPipelineResource extends SecureResource { public void handlePost() { if(proj!=null && step!=null && expt != null){ try { + final UserI user = getUser(); if(step.equals(XNATRestConstants.TRIGGER_PIPELINES)){ - if(Permissions.canEdit(user,expt)){ + if(Permissions.canEdit(user, expt)){ - PersistentWorkflowI wrk = PersistentWorkflowUtils.buildOpenWorkflow(user, expt.getItem(),newEventInstance(EventUtils.CATEGORY.DATA,EventUtils.TRIGGER_PIPELINES)); + PersistentWorkflowI wrk = PersistentWorkflowUtils.buildOpenWorkflow(user, expt.getItem(), newEventInstance(EventUtils.CATEGORY.DATA, EventUtils.TRIGGER_PIPELINES)); EventMetaI c=wrk.buildEvent(); try { - FixScanTypes fst=new FixScanTypes(expt,user,proj,true,c); + FixScanTypes fst=new FixScanTypes(expt, user, proj, true, c); fst.call(); - TriggerPipelines tp = new TriggerPipelines(expt,this.isQueryVariableTrue(XNATRestConstants.SUPRESS_EMAIL),user); + TriggerPipelines tp = new TriggerPipelines(expt, this.isQueryVariableTrue(XNATRestConstants.SUPRESS_EMAIL), user); tp.call(); PersistentWorkflowUtils.complete(wrk,c); } catch (Exception e) { @@ -141,12 +144,12 @@ public class ProjtExptPipelineResource extends SecureResource { } } }else if(step.equals(XNATRestConstants.PULL_DATA_FROM_HEADERS) && expt instanceof XnatImagesessiondata){ - if(Permissions.canEdit(user,expt)){ + if(Permissions.canEdit(user, expt)){ try { - PersistentWorkflowI wrk=PersistentWorkflowUtils.buildOpenWorkflow(user, expt.getItem(),newEventInstance(EventUtils.CATEGORY.DATA, EventUtils.DICOM_PULL)); + PersistentWorkflowI wrk=PersistentWorkflowUtils.buildOpenWorkflow(user, expt.getItem(), newEventInstance(EventUtils.CATEGORY.DATA, EventUtils.DICOM_PULL)); EventMetaI c=wrk.buildEvent(); try { - PullSessionDataFromHeaders pull=new PullSessionDataFromHeaders((XnatImagesessiondata)expt, user, this.isQueryVariableTrue("allowDataDeletion"), this.isQueryVariableTrue("overwrite"),false,c); + PullSessionDataFromHeaders pull=new PullSessionDataFromHeaders((XnatImagesessiondata)expt, user, this.isQueryVariableTrue("allowDataDeletion"), this.isQueryVariableTrue("overwrite"), false, c); pull.call(); WorkflowUtils.complete(wrk, c); } catch (Exception e) { @@ -168,14 +171,14 @@ public class ProjtExptPipelineResource extends SecureResource { getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); } }else if(step.equals(XNATRestConstants.FIX_SCAN_TYPES) && expt instanceof XnatImagesessiondata){ - if(Permissions.canEdit(user,expt)){ + if(Permissions.canEdit(user, expt)){ - PersistentWorkflowI wrk = PersistentWorkflowUtils.buildOpenWorkflow(user, expt.getItem(),newEventInstance(EventUtils.CATEGORY.DATA,EventUtils.TRIGGER_PIPELINES)); + PersistentWorkflowI wrk = PersistentWorkflowUtils.buildOpenWorkflow(user, expt.getItem(), newEventInstance(EventUtils.CATEGORY.DATA, EventUtils.TRIGGER_PIPELINES)); EventMetaI c=wrk.buildEvent(); PersistentWorkflowUtils.save(wrk,c); try { - FixScanTypes fst=new FixScanTypes(expt,user,proj,true,c); + FixScanTypes fst=new FixScanTypes(expt, user, proj, true, c); fst.call(); WorkflowUtils.complete(wrk, c); } catch (Exception e) { @@ -266,7 +269,9 @@ public class ProjtExptPipelineResource extends SecureResource { } private void launch(ArcPipelinedataI arcPipeline, Map<String,String> paramsMap) throws Exception { - XnatPipelineLauncher xnatPipelineLauncher = new XnatPipelineLauncher(user); + final UserI user = getUser(); + + XnatPipelineLauncher xnatPipelineLauncher = new XnatPipelineLauncher(user); xnatPipelineLauncher.setSupressNotification(true); List<String> hasParams = new ArrayList<String>(); @@ -384,6 +389,8 @@ public class ProjtExptPipelineResource extends SecureResource { } private boolean launch(ArcPipelinedataI arcPipeline) throws Exception { + final UserI user = getUser(); + XnatPipelineLauncher xnatPipelineLauncher = new XnatPipelineLauncher(user); xnatPipelineLauncher.setSupressNotification(true); xnatPipelineLauncher.setParameter("useremail", user.getEmail()); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ProtocolResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ProtocolResource.java index b3c8d5ca0eb31c9e8aba9132caa3e90fc069e0bf..9590057b148b52ac7be67e7b971ef33b6c81804f 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ProtocolResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ProtocolResource.java @@ -44,8 +44,10 @@ public class ProtocolResource extends ItemResource { public ProtocolResource(Context context, Request request, Response response) { super(context, request, response); - - String pID = (String) getParameter(request,"PROJECT_ID"); + + final UserI user = getUser(); + + final String pID = (String) getParameter(request,"PROJECT_ID"); if (pID != null) { proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); } @@ -67,6 +69,7 @@ public class ProtocolResource extends ItemResource { @Override public void handlePut() { try { + final UserI user = getUser(); XFTItem template=null; if (existing!=null){ template=existing.getItem().getCurrentDBVersion(); @@ -148,7 +151,9 @@ public class ProtocolResource extends ItemResource { if(existing!=null){ protocol=existing; } - + + final UserI user = getUser(); + try { if(!Permissions.canEdit(user,proj)){ @@ -177,9 +182,10 @@ public class ProtocolResource extends ItemResource { } @Override - public Representation getRepresentation(Variant variant) { + public Representation represent(Variant variant) { MediaType mt = overrideVariant(variant); - + final UserI user = getUser(); + if(protocol!=null){ return this.representItem(protocol.getItem(),mt); }else{ @@ -192,7 +198,7 @@ public class ProtocolResource extends ItemResource { if(temp==null && ess!=null){ GenericWrapperElement e=GenericWrapperElement.GetElement(dataType); - temp=new XnatDatatypeprotocol((UserI)user); + temp=new XnatDatatypeprotocol(user); temp.setProperty("xnat_projectdata_id", proj.getId()); temp.setDataType(e.getXSIType()); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ReconList.java b/src/main/java/org/nrg/xnat/restlet/resources/ReconList.java index 43c3328f5b4bc24b546f4dd283d0f2e1d1695876..e9158decccc4639d8d299f165975ac2ae0b4236b 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ReconList.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ReconList.java @@ -23,6 +23,7 @@ import org.nrg.xft.exception.InvalidValueException; import org.nrg.xft.schema.Wrappers.GenericWrapper.GenericWrapperElement; import org.nrg.xft.search.CriteriaCollection; import org.nrg.xft.search.QueryOrganizer; +import org.nrg.xft.security.UserI; import org.nrg.xft.utils.ValidationUtils.ValidationResults; import org.nrg.xnat.helpers.xmlpath.XMLPathShortcuts; import org.nrg.xnat.restlet.representations.ItemXMLRepresentation; @@ -44,84 +45,84 @@ public class ReconList extends QueryOrganizerResource { XnatSubjectdata sub=null; XnatImagesessiondata session=null; XnatReconstructedimagedata recon=null; - + public ReconList(Context context, Request request, Response response) { super(context, request, response); - - String pID= (String)getParameter(request,"PROJECT_ID"); - if(pID!=null){ - proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); + final UserI user = getUser(); - String subID= (String)getParameter(request,"SUBJECT_ID"); - if(subID!=null){ + String pID = (String) getParameter(request, "PROJECT_ID"); + if (pID != null) { + proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); + + String subID = (String) getParameter(request, "SUBJECT_ID"); + if (subID != null) { sub = XnatSubjectdata.GetSubjectByProjectIdentifier(proj - .getId(), subID, user, false); - - if(sub==null){ + .getId(), subID, user, false); + + if (sub == null) { sub = XnatSubjectdata.getXnatSubjectdatasById(subID, user, - false); + false); if (sub != null - && (proj != null && !sub.hasProject(proj.getId()))) { + && (proj != null && !sub.hasProject(proj.getId()))) { sub = null; } - } - - if(sub!=null){ + } + + if (sub != null) { String exptID = (String) getParameter(request, - "ASSESSED_ID"); + "ASSESSED_ID"); session = XnatImagesessiondata .getXnatImagesessiondatasById(exptID, user, false); if (session != null - && (proj != null && !session.hasProject(proj - .getId()))) { + && (proj != null && !session.hasProject(proj + .getId()))) { session = null; } - - if(session==null){ + + if (session == null) { session = (XnatImagesessiondata) XnatImagesessiondata .GetExptByProjectIdentifier(proj.getId(), - exptID, user, false); - } - - if(session!=null){ + exptID, user, false); + } + + if (session != null) { this.getVariants().add( new Variant(MediaType.APPLICATION_JSON)); this.getVariants() - .add(new Variant(MediaType.TEXT_HTML)); - this.getVariants().add(new Variant(MediaType.TEXT_XML)); - }else{ + .add(new Variant(MediaType.TEXT_HTML)); + this.getVariants().add(new Variant(MediaType.TEXT_XML)); + } else { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); - } - }else{ - response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } - }else{ - response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); + } else { + response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } - }else{ - String exptID= (String)getParameter(request,"ASSESSED_ID"); + } else { + response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); + } + } else { + String exptID = (String) getParameter(request, "ASSESSED_ID"); session = XnatImagesessiondata.getXnatImagesessiondatasById(exptID, - user, false); - - if(session==null){ + user, false); + + if (session == null) { session = (XnatImagesessiondata) XnatImagesessiondata .GetExptByProjectIdentifier(proj.getId(), exptID, user, - false); - } - - if(session!=null){ - this.getVariants().add(new Variant(MediaType.APPLICATION_JSON)); - this.getVariants().add(new Variant(MediaType.TEXT_HTML)); - this.getVariants().add(new Variant(MediaType.TEXT_XML)); - }else{ + false); + } + + if (session != null) { + this.getVariants().add(new Variant(MediaType.APPLICATION_JSON)); + this.getVariants().add(new Variant(MediaType.TEXT_HTML)); + this.getVariants().add(new Variant(MediaType.TEXT_XML)); + } else { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); - } } + } - this.fieldMapping.putAll(XMLPathShortcuts.getInstance().getShortcuts(XMLPathShortcuts.RECON_DATA,true)); - - } + this.fieldMapping.putAll(XMLPathShortcuts.getInstance().getShortcuts(XMLPathShortcuts.RECON_DATA, true)); + } @Override public boolean allowPost() { @@ -130,10 +131,11 @@ public class ReconList extends QueryOrganizerResource { @Override public void handlePost() { - XFTItem item = null; + final UserI user = getUser(); try { - item=this.loadItem("xnat:reconstructedImageData",true); + XFTItem item = null; + item=this.loadItem("xnat:reconstructedImageData",true); if(item==null){ String xsiType=this.getQueryVariable("xsiType"); @@ -281,7 +283,8 @@ public class ReconList extends QueryOrganizerResource { if(rep!=null)return rep; XFTTable table; - try { + try { + final UserI user = getUser(); final String re=this.getRootElementName(); final QueryOrganizer qo = new QueryOrganizer(re, user, @@ -300,13 +303,13 @@ public class ReconList extends QueryOrganizerResource { table = formatHeaders(table, qo, "xnat:reconstructedImageData/ID", String.format("/data/experiments/%s/reconstructions/",session.getId())); } catch (Exception e) { - e.printStackTrace(); + logger.error("", e); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return null; } MediaType mt = overrideVariant(variant); - Hashtable<String, Object> params = new Hashtable<String, Object>(); + Hashtable<String, Object> params = new Hashtable<>(); if (table != null) params.put("totalRecords", table.size()); return this.representTable(table, mt, params); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ReconResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ReconResource.java index 5a756ed85d9489aa73b73b89fa890af7577687ff..127758f8ecd9f8ffc9d78bcf2678d25a67cd8e36 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ReconResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ReconResource.java @@ -25,6 +25,7 @@ import org.nrg.xft.event.EventUtils; import org.nrg.xft.event.persist.PersistentWorkflowI; import org.nrg.xft.event.persist.PersistentWorkflowUtils; import org.nrg.xft.exception.InvalidValueException; +import org.nrg.xft.security.UserI; import org.nrg.xft.utils.SaveItemHelper; import org.nrg.xft.utils.ValidationUtils.ValidationResults; import org.nrg.xnat.helpers.xmlpath.XMLPathShortcuts; @@ -46,46 +47,46 @@ public class ReconResource extends ItemResource { XnatReconstructedimagedata recon=null; String exptID=null; - + public ReconResource(Context context, Request request, Response response) { super(context, request, response); - - String pID= (String)getParameter(request,"PROJECT_ID"); - if(pID!=null){ - proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); - } - - String assessedID= (String)getParameter(request,"ASSESSED_ID"); - if(assessedID!=null){ - if(session==null&& assessedID!=null){ + + String pID = (String) getParameter(request, "PROJECT_ID"); + final UserI user = getUser(); + if (pID != null) { + proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); + } + + String assessedID = (String) getParameter(request, "ASSESSED_ID"); + if (assessedID != null) { + if (session == null && assessedID != null) { session = (XnatImagesessiondata) XnatExperimentdata .getXnatExperimentdatasById(assessedID, user, false); if (session != null - && (proj != null && !session.hasProject(proj.getId()))) { + && (proj != null && !session.hasProject(proj.getId()))) { session = null; } - - if(session==null && this.proj!=null){ + + if (session == null && this.proj != null) { session = (XnatImagesessiondata) XnatExperimentdata .GetExptByProjectIdentifier(this.proj.getId(), - assessedID, user, false); - } + assessedID, user, false); } + } - exptID= (String)getParameter(request,"RECON_ID"); - if(exptID!=null){ + exptID = (String) getParameter(request, "RECON_ID"); + if (exptID != null) { this.getVariants().add(new Variant(MediaType.TEXT_HTML)); - this.getVariants().add(new Variant(MediaType.TEXT_XML)); - } - - }else{ + this.getVariants().add(new Variant(MediaType.TEXT_XML)); + } + + } else { response.setStatus(Status.CLIENT_ERROR_GONE, - "Unable to find session '" + assessedID + "'"); + "Unable to find session '" + assessedID + "'"); } - - this.fieldMapping.putAll(XMLPathShortcuts.getInstance().getShortcuts(XMLPathShortcuts.RECON_DATA,false)); - } + this.fieldMapping.putAll(XMLPathShortcuts.getInstance().getShortcuts(XMLPathShortcuts.RECON_DATA, false)); + } @Override public boolean allowPut() { @@ -99,7 +100,8 @@ public class ReconResource extends ItemResource { try { item=this.loadItem("xnat:reconstructedImageData",true); - if(item==null){ + final UserI user = getUser(); + if(item == null){ String xsiType=this.getQueryVariable("xsiType"); if(xsiType!=null){ item=XFTItem.NewItem(xsiType, user); @@ -126,7 +128,7 @@ public class ReconResource extends ItemResource { this.session=(XnatImagesessiondata)XnatExperimentdata.getXnatExperimentdatasById(recon.getImageSessionId(), user, false); if(this.session==null && this.proj!=null){ - this.session=(XnatImagesessiondata)XnatExperimentdata.GetExptByProjectIdentifier(this.proj.getId(), recon.getImageSessionId(),user, false); + this.session=(XnatImagesessiondata)XnatExperimentdata.GetExptByProjectIdentifier(this.proj.getId(), recon.getImageSessionId(), user, false); } if(this.session!=null){ recon.setImageSessionId(this.session.getId()); @@ -164,7 +166,7 @@ public class ReconResource extends ItemResource { } if(existing==null){ - if(!Permissions.canEdit(user,this.session)){ + if(!Permissions.canEdit(user, this.session)){ this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN,"Specified user account has insufficient create privileges for sessions in this project."); return; } @@ -173,8 +175,8 @@ public class ReconResource extends ItemResource { String query = "SELECT count(id) AS id_count FROM xnat_reconstructedimagedata WHERE id='"; String login = null; - if (user!=null){ - login=user.getUsername(); + if (user != null){ + login= user.getUsername(); } try { int i=1; @@ -190,7 +192,7 @@ public class ReconResource extends ItemResource { } } }else{ - if(!Permissions.canEdit(user,session)){ + if(!Permissions.canEdit(user, session)){ this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN,"Specified user account has insufficient edit privileges for sessions in this project."); return; } @@ -234,63 +236,63 @@ public class ReconResource extends ItemResource { } @Override - public void handleDelete(){ - if(recon==null&& exptID!=null){ - recon=(XnatReconstructedimagedata)XnatReconstructedimagedata.getXnatReconstructedimagedatasById(exptID, user, completeDocument); - } - - if(recon==null){ - this.getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND,"Unable to find the specified reconstruction."); - return; - } - - if(filepath!=null && !filepath.equals("")){ - this.getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); - return; - } - try { - - if(!Permissions.canDelete(user,session) || XDAT.getBoolSiteConfigurationProperty("security.prevent-data-deletion", false)){ - this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN,"User account doesn't have permission to modify this session."); + public void handleDelete() { + final UserI user = getUser(); + if (recon == null && exptID != null) { + recon = XnatReconstructedimagedata.getXnatReconstructedimagedatasById(exptID, user, completeDocument); + } + + if (recon == null) { + this.getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND, "Unable to find the specified reconstruction."); + return; + } + + if (filepath != null && !filepath.equals("")) { + this.getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); + return; + } + try { + + if (!Permissions.canDelete(user, session) || XDAT.getBoolSiteConfigurationProperty("security.prevent-data-deletion", false)) { + this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, "User account doesn't have permission to modify this session."); return; } - final PersistentWorkflowI workflow=WorkflowUtils.getOrCreateWorkflowData(getEventId(), user, session.getXSIType(), session.getId(), (proj==null)?session.getProject():proj.getId(),newEventInstance(EventUtils.CATEGORY.DATA, EventUtils.getDeleteAction(recon.getXSIType()))); - final EventMetaI ci=workflow.buildEvent(); - PersistentWorkflowUtils.save(workflow,ci); - - try { - String removeFiles=this.getQueryVariable("removeFiles"); - if (removeFiles!=null){ - for (XnatAbstractresourceI om : recon.getOut_file()){ - XnatAbstractresource resourceA = (XnatAbstractresource)om; - resourceA.deleteWithBackup(session.getArchiveRootPath(),user,ci); - } - } - SaveItemHelper.authorizedDelete(recon.getItem().getCurrentDBVersion(), user,ci); - - WorkflowUtils.complete(workflow, ci); - - Users.clearCache(user); - MaterializedView.deleteByUser(user); - } catch (Exception e) { - WorkflowUtils.fail(workflow, ci); - throw e; + final PersistentWorkflowI workflow = WorkflowUtils.getOrCreateWorkflowData(getEventId(), user, session.getXSIType(), session.getId(), (proj == null) ? session.getProject() : proj.getId(), newEventInstance(EventUtils.CATEGORY.DATA, EventUtils.getDeleteAction(recon.getXSIType()))); + final EventMetaI ci = workflow.buildEvent(); + PersistentWorkflowUtils.save(workflow, ci); + + try { + String removeFiles = this.getQueryVariable("removeFiles"); + if (removeFiles != null) { + for (XnatAbstractresourceI om : recon.getOut_file()) { + XnatAbstractresource resourceA = (XnatAbstractresource) om; + resourceA.deleteWithBackup(session.getArchiveRootPath(), user, ci); + } } + SaveItemHelper.authorizedDelete(recon.getItem().getCurrentDBVersion(), user, ci); + + WorkflowUtils.complete(workflow, ci); + + Users.clearCache(user); + MaterializedView.deleteByUser(user); + } catch (Exception e) { + WorkflowUtils.fail(workflow, ci); + throw e; + } } catch (SQLException e) { e.printStackTrace(); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,e); + this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, e); } catch (Exception e) { e.printStackTrace(); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,e); + this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, e); } } - @Override - public Representation getRepresentation(Variant variant) { + public Representation represent(Variant variant) { if(recon==null&& exptID!=null){ - recon=(XnatReconstructedimagedata)XnatReconstructedimagedata.getXnatReconstructedimagedatasById(exptID, user, completeDocument); + recon= XnatReconstructedimagedata.getXnatReconstructedimagedatasById(exptID, getUser(), completeDocument); } if(recon!=null){ diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ScanDIRResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ScanDIRResource.java index a42d10b459157a333e49f0759fe659185a371c0c..56bc95f7d3985a9f1c925fd3eca80f19ae49e01f 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ScanDIRResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ScanDIRResource.java @@ -31,6 +31,7 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.net.URLDecoder; +import java.nio.charset.Charset; import java.util.*; public class ScanDIRResource extends ScanResource { @@ -49,38 +50,40 @@ public class ScanDIRResource extends ScanResource { } @Override - public Representation getRepresentation(Variant variant) { + public Representation represent(Variant variant) { final List<XnatImagescandata> scans; - if (null != scan) { - scans = Collections.singletonList(scan); - } else if (null == this.session) { - this.getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND, "Unable to find the specified session."); - return null; - } else if (!Strings.isNullOrEmpty(scanID)) { - scanID = URLDecoder.decode(scanID); - scans = XnatImagescandata.getScansByIdORType(scanID, session, user, completeDocument); - if (scans.isEmpty()){ - this.getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND, "Unable to find the specified scan(s)."); + try { + if (null != scan) { + scans = Collections.singletonList(scan); + } else if (null == this.session) { + this.getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND, "Unable to find the specified session."); + return null; + } else if (!Strings.isNullOrEmpty(scanID)) { + scanID = URLDecoder.decode(scanID, Charset.defaultCharset().name()); + scans = XnatImagescandata.getScansByIdORType(scanID, session, getUser(), completeDocument); + if (scans.isEmpty()){ + this.getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND, "Unable to find the specified scan(s)."); + return null; + } + } else { + // TODO: use all scans for the given session? + this.getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "No scan specified"); return null; } - } else { - // TODO: use all scans for the given session? - this.getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "No scan specified"); - return null; - } - assert !scans.isEmpty(); - ZipRepresentation rep; - try { + assert !scans.isEmpty(); + //prepare Maps for use in cleaning file paths and relativing them. - final Map<String,String> session_mapping=new Hashtable<String,String>(); + final Map<String,String> session_mapping= new Hashtable<>(); session_mapping.put(session.getId(),session.getArchiveDirectoryName()); session_mapping.put(session.getArchiveDirectoryName(),session.getArchiveDirectoryName()); - final ArrayList<String> session_ids=new ArrayList<String>(); + final ArrayList<String> session_ids= new ArrayList<>(); session_ids.add(session.getArchiveDirectoryName()); Map<String,String> valuesToReplace=RestFileUtils.getReMaps(scans,null); + + final ZipRepresentation rep; try{ rep = new ZipRepresentation(MediaType.APPLICATION_ZIP,session_ids,identifyCompression(null)); } catch (ActionException e) { @@ -92,7 +95,6 @@ public class ScanDIRResource extends ScanResource { //this is the expected path to the SESSION_DIR final String rootPath=session.getArchivePath(); - // create a directory in the temporary directory to hold our files File _tmp_working_dir = File.createTempFile("dicom_","",new File(System.getProperty("java.io.tmpdir"))); String name = _tmp_working_dir.getAbsolutePath(); @@ -121,7 +123,7 @@ public class ScanDIRResource extends ScanResource { if (tmp_dicom_dir != null) { tmp_dicom_dir.mkdirs(); } - if(f!=null && f.exists()){ + if(f.exists()){ rep.addEntry(relative, f); // copy file to the directory structure in the working temp directory. FileUtils.copyFileToDirectory(f,tmp_dicom_dir); @@ -139,8 +141,7 @@ public class ScanDIRResource extends ScanResource { rep.deleteDirectoryAfterWrite(tmp_working_dir); this.setContentDisposition(rep.getDownloadName()); return rep; - } - finally { + } finally { dicomdir.close(); } } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ScanList.java b/src/main/java/org/nrg/xnat/restlet/resources/ScanList.java index 61d4d3fb2db0de090da66aa5753fcf69dcfa2690..99063453203124d62bfae544b7e6a59934a72b21 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ScanList.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ScanList.java @@ -24,6 +24,7 @@ import org.nrg.xft.exception.InvalidValueException; import org.nrg.xft.schema.Wrappers.GenericWrapper.GenericWrapperElement; import org.nrg.xft.search.CriteriaCollection; import org.nrg.xft.search.QueryOrganizer; +import org.nrg.xft.security.UserI; import org.nrg.xft.utils.ValidationUtils.ValidationResults; import org.nrg.xnat.helpers.xmlpath.XMLPathShortcuts; import org.nrg.xnat.restlet.representations.ItemXMLRepresentation; @@ -49,8 +50,9 @@ public class ScanList extends QueryOrganizerResource { public ScanList(Context context, Request request, Response response) { super(context, request, response); - String pID= (String)getParameter(request,"PROJECT_ID"); - if(pID!=null){ + String pID= (String)getParameter(request,"PROJECT_ID"); + final UserI user = getUser(); + if(pID != null){ proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); String subID= (String)getParameter(request,"SUBJECT_ID"); @@ -60,7 +62,7 @@ public class ScanList extends QueryOrganizerResource { if(sub==null){ sub = XnatSubjectdata.getXnatSubjectdatasById(subID, user, - false); + false); if (sub != null && (proj != null && !sub.hasProject(proj.getId()))) { sub = null; @@ -81,7 +83,7 @@ public class ScanList extends QueryOrganizerResource { if(session==null){ session = (XnatImagesessiondata) XnatImagesessiondata .GetExptByProjectIdentifier(proj.getId(), - exptID, user, false); + exptID, user, false); } if(session!=null){ @@ -102,12 +104,12 @@ public class ScanList extends QueryOrganizerResource { }else{ String exptID= (String)getParameter(request,"ASSESSED_ID"); session = XnatImagesessiondata.getXnatImagesessiondatasById(exptID, - user, false); + user, false); if(session==null){ session = (XnatImagesessiondata) XnatImagesessiondata .GetExptByProjectIdentifier(proj.getId(), exptID, user, - false); + false); } if(session!=null){ @@ -144,7 +146,8 @@ public class ScanList extends QueryOrganizerResource { } item=this.loadItem(dataType,true); - if(item==null){ + final UserI user = getUser(); + if(item == null){ String xsiType=this.getQueryVariable("xsiType"); if(xsiType!=null){ item=XFTItem.NewItem(xsiType, user); @@ -167,7 +170,7 @@ public class ScanList extends QueryOrganizerResource { this.session=(XnatImagesessiondata)XnatExperimentdata.getXnatExperimentdatasById(scan.getImageSessionId(), user, false); if(this.session==null && this.proj!=null){ - this.session=(XnatImagesessiondata)XnatExperimentdata.GetExptByProjectIdentifier(this.proj.getId(), scan.getImageSessionId(),user, false); + this.session=(XnatImagesessiondata)XnatExperimentdata.GetExptByProjectIdentifier(this.proj.getId(), scan.getImageSessionId(), user, false); } if(this.session!=null){ scan.setImageSessionId(this.session.getId()); @@ -207,7 +210,7 @@ public class ScanList extends QueryOrganizerResource { } if(existing==null){ - if(!Permissions.canEdit(user,this.session)){ + if(!Permissions.canEdit(user, this.session)){ this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN,"Specified user account has insufficient create privileges for sessions in this project."); return; } @@ -216,8 +219,8 @@ public class ScanList extends QueryOrganizerResource { String query = "SELECT count(id) AS id_count FROM xnat_imageScanData WHERE image_session_id='" + this.session.getId() + "' AND id='"; String login = null; - if (user!=null){ - login=user.getUsername(); + if (user != null){ + login= user.getUsername(); } try { int i=1; @@ -304,8 +307,8 @@ public class ScanList extends QueryOrganizerResource { try { final String re=this.getRootElementName(); - final QueryOrganizer qo = new QueryOrganizer(re, user, - ViewManager.ALL); + final UserI user = getUser(); + final QueryOrganizer qo = new QueryOrganizer(re, user, ViewManager.ALL); this.populateQuery(qo); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ScanResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ScanResource.java index 6d6e70d0b179c143826c00930f027602bf3ad541..d889b46c93ea9cb496f8606fa963d00917ae56ac 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ScanResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ScanResource.java @@ -27,6 +27,7 @@ import org.nrg.xft.event.persist.PersistentWorkflowI; import org.nrg.xft.event.persist.PersistentWorkflowUtils; import org.nrg.xft.exception.InvalidValueException; import org.nrg.xft.search.CriteriaCollection; +import org.nrg.xft.security.UserI; import org.nrg.xft.utils.ValidationUtils.ValidationResults; import org.nrg.xnat.helpers.xmlpath.XMLPathShortcuts; import org.nrg.xnat.restlet.actions.PullScanDataFromHeaders; @@ -56,7 +57,9 @@ public class ScanResource extends ItemResource { public ScanResource(Context context, Request request, Response response) { super(context, request, response); - String pID = (String) getParameter(request, "PROJECT_ID"); + final UserI user = getUser(); + + final String pID = (String) getParameter(request, "PROJECT_ID"); if (pID != null) { proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); } @@ -92,7 +95,8 @@ public class ScanResource extends ItemResource { @Override public void handlePut() { - if (user == null) { + final UserI user = getUser(); + if (user.isGuest()) { getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, "No authenticated user found."); } @@ -270,7 +274,7 @@ public class ScanResource extends ItemResource { } try { - if (!Permissions.canDelete(user,session) || XDAT.getBoolSiteConfigurationProperty("security.prevent-data-deletion", false)) { + if (!Permissions.canDelete(getUser(), session) || XDAT.getBoolSiteConfigurationProperty("security.prevent-data-deletion", false)) { getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, "User account doesn't have permission to modify this session."); return; } @@ -305,7 +309,7 @@ public class ScanResource extends ItemResource { CriteriaCollection cc = new CriteriaCollection("AND"); cc.addClause("xnat:imageScanData/ID", scanID); cc.addClause("xnat:imageScanData/image_session_ID", session.getId()); - ArrayList<XnatImagescandata> scans = XnatImagescandata.getXnatImagescandatasByField(cc, user, completeDocument); + ArrayList<XnatImagescandata> scans = XnatImagescandata.getXnatImagescandatasByField(cc, getUser(), completeDocument); if (scans.size() > 0) { scan = scans.get(0); } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ScanTypeListing.java b/src/main/java/org/nrg/xnat/restlet/resources/ScanTypeListing.java index 275e22ddd1900e913bfaf4d06ca613c3c783f246..e6ef0669c083c74f50cd87920ba2a3e7ab1ebd88 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ScanTypeListing.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ScanTypeListing.java @@ -13,6 +13,7 @@ package org.nrg.xnat.restlet.resources; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xft.XFTTable; +import org.nrg.xft.security.UserI; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Request; @@ -31,7 +32,7 @@ public class ScanTypeListing extends SecureResource { String pID = (String) getParameter(request,"PROJECT_ID"); if (pID != null) { - proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); + proj = XnatProjectdata.getProjectByIDorAlias(pID, getUser(), false); if (proj == null) { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); @@ -44,8 +45,9 @@ public class ScanTypeListing extends SecureResource { } @Override - public Representation getRepresentation(Variant variant) { - XFTTable table = null; + public Representation represent(Variant variant) { + final UserI user = getUser(); + XFTTable table = null; String scan_table = this.getQueryVariable("table"); if (scan_table == null) { @@ -68,13 +70,13 @@ public class ScanTypeListing extends SecureResource { query += " GROUP BY scan.type ORDER BY scan.type"; - table = (XFTTable) XFTTable.Execute(query, user.getDBName(), user + table = XFTTable.Execute(query, user.getDBName(), user .getLogin()); } catch (Exception e) { logger.error("",e); } - Hashtable<String,Object> params=new Hashtable<String,Object>(); + Hashtable<String,Object> params= new Hashtable<>(); params.put("title", "Scan Types"); MediaType mt = overrideVariant(variant); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ScannerListing.java b/src/main/java/org/nrg/xnat/restlet/resources/ScannerListing.java index f71cc20702571e12988294be4740f77bc218542e..20caa02c03bd22791d1ecb1d2b9359b6655f8b94 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ScannerListing.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ScannerListing.java @@ -13,7 +13,7 @@ package org.nrg.xnat.restlet.resources; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xft.XFTTable; -import org.nrg.xft.exception.DBPoolException; +import org.nrg.xft.security.UserI; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Request; @@ -22,7 +22,6 @@ import org.restlet.data.Status; import org.restlet.resource.Representation; import org.restlet.resource.Variant; -import java.sql.SQLException; import java.util.Hashtable; public class ScannerListing extends SecureResource { @@ -33,7 +32,7 @@ public class ScannerListing extends SecureResource { String pID = (String) getParameter(request,"PROJECT_ID"); if (pID != null) { - proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); + proj = XnatProjectdata.getProjectByIDorAlias(pID, getUser(), false); if (proj == null) { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); @@ -46,9 +45,9 @@ public class ScannerListing extends SecureResource { } @Override - public Representation getRepresentation(Variant variant) { - XFTTable table = null; - + public Representation represent(Variant variant) { + final UserI user = getUser(); + String scan_table=this.getQueryVariable("table"); if(scan_table==null){ scan_table="xnat_mrSessionData"; @@ -59,22 +58,19 @@ public class ScannerListing extends SecureResource { return null; } } - + + XFTTable table = null; try { String query="SELECT DISTINCT isd.scanner FROM " + scan_table + " mod LEFT JOIN xnat_imageSessionData isd ON mod.id=isd.id LEFT JOIN xnat_experimentData expt ON isd.id=expt.id WHERE isd.scanner IS NOT NULL"; if(proj!=null)query+=" WHERE expt.project='" + proj.getId() + "'"; - - table=(XFTTable)XFTTable.Execute(query,user.getDBName(),user.getLogin()); - } catch (SQLException e) { - e.printStackTrace(); - } catch (DBPoolException e) { - e.printStackTrace(); + + table=XFTTable.Execute(query,user.getDBName(),user.getLogin()); } catch (Exception e) { - e.printStackTrace(); + logger.error("", e); } - - Hashtable<String,Object> params=new Hashtable<String,Object>(); + + Hashtable<String,Object> params= new Hashtable<>(); params.put("title", "Scanners"); MediaType mt = overrideVariant(variant); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ScriptResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ScriptResource.java index e433a37e8e480949cc34564b11d967d5125fbeb4..e75c21993ff5967eb693ac54c4777be6bb326273 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ScriptResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ScriptResource.java @@ -10,6 +10,7 @@ import org.nrg.framework.exceptions.NrgServiceException; import org.nrg.xdat.XDAT; import org.nrg.xdat.security.helpers.Roles; import org.nrg.xft.XFTTable; +import org.nrg.xft.security.UserI; import org.nrg.xnat.helpers.prearchive.PrearcDatabase; import org.restlet.Context; import org.restlet.data.*; @@ -44,6 +45,7 @@ public class ScriptResource extends AutomationResource { _version = (String) getRequest().getAttributes().get(VERSION); // If the user isn't a site admin, there's a limited set of operations they are permitted to perform. + final UserI user = getUser(); if (!Roles.isSiteAdmin(user)) { // You can't put or post or delete a script and you can't retrieve a specific script OTHER THAN the split // PET/MR script, which is used by the upload applet. diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ScriptRunnerResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ScriptRunnerResource.java index 17c26725c7f27ee004488390968035cad5eb2099..1b9455f87a6af92423e915a13e18d2065df0528e 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ScriptRunnerResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ScriptRunnerResource.java @@ -33,7 +33,7 @@ public class ScriptRunnerResource extends AutomationResource { // Technically this shouldn't happen because the URL has language first then version, but why not? if (_log.isDebugEnabled()) { - _log.debug(getRequestContext("Servicing script runner request for user " + user.getLogin()) + (StringUtils.isBlank(_language) ? " to get a list of available script runners" : " to get information about " + _language)); + _log.debug(getRequestContext("Servicing script runner request for user " + getUser().getLogin()) + (StringUtils.isBlank(_language) ? " to get a list of available script runners" : " to get information about " + _language)); } } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ScriptTriggerResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ScriptTriggerResource.java index 7a511d8d394d5a3514d72f0d2d1442a58658ca78..93456ca78a68f4d34f24317c485d79173237b4db 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ScriptTriggerResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ScriptTriggerResource.java @@ -1,5 +1,7 @@ package org.nrg.xnat.restlet.resources; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.apache.commons.lang3.StringUtils; import org.nrg.action.ClientException; import org.nrg.action.ServerException; @@ -10,6 +12,7 @@ import org.nrg.framework.constants.Scope; import org.nrg.xdat.XDAT; import org.nrg.xdat.security.helpers.Roles; import org.nrg.xft.XFTTable; +import org.nrg.xft.security.UserI; import org.python.google.common.collect.Sets; import org.restlet.Context; import org.restlet.data.*; @@ -20,9 +23,6 @@ import org.restlet.resource.Variant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - import java.io.IOException; import java.util.*; @@ -87,6 +87,7 @@ public class ScriptTriggerResource extends AutomationResource { } final Method method = request.getMethod(); + final UserI user = getUser(); if (StringUtils.isNotBlank(projectId)) { validateProjectAccess(projectId); @@ -307,8 +308,7 @@ public class ScriptTriggerResource extends AutomationResource { //final Properties properties; JsonResults jsonResults; try { - final String text = entity.getText(); - final String jsonString = text; + final String jsonString = entity.getText(); final GsonBuilder builder = new GsonBuilder(); final Gson gson = builder.create(); jsonResults = gson.fromJson(jsonString,JsonResults.class); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ScriptTriggerTemplateResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ScriptTriggerTemplateResource.java index 23100cdf0a6c52931b2816620924f262849903c6..878c706690d1642caf466e233ee84ccdef75e968 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ScriptTriggerTemplateResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ScriptTriggerTemplateResource.java @@ -14,6 +14,7 @@ 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.XFTTable; +import org.nrg.xft.security.UserI; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Request; @@ -49,6 +50,8 @@ public class ScriptTriggerTemplateResource extends AutomationResource { _templateId = (String) getRequest().getAttributes().get(TEMPLATE_ID); + final UserI user = getUser(); + if (getScope() == Scope.Site) { if (!Roles.isSiteAdmin(user)) { _log.warn(getRequestContext("User " + user.getLogin() + " attempted to access forbidden script trigger template resources")); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/ScriptVersionsResource.java b/src/main/java/org/nrg/xnat/restlet/resources/ScriptVersionsResource.java index 6e4d199b6db4f531c4579eeb785620a06989a8cc..81b92dd498feb5cd14ec6fd8c1530dea6fd6fffe 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/ScriptVersionsResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/ScriptVersionsResource.java @@ -7,6 +7,7 @@ import org.nrg.automation.services.ScriptService; import org.nrg.xdat.XDAT; import org.nrg.xdat.security.helpers.Roles; import org.nrg.xft.XFTTable; +import org.nrg.xft.security.UserI; import org.nrg.xnat.helpers.prearchive.PrearcDatabase; import org.restlet.Context; import org.restlet.data.MediaType; @@ -40,6 +41,8 @@ public class ScriptVersionsResource extends AutomationResource { _scriptId = (String) getRequest().getAttributes().get(SCRIPT_ID); + final UserI user = getUser(); + // If the user isn't a site admin, there's a limited set of operations they are permitted to perform. if (!Roles.isSiteAdmin(user)) { // You can't put or post or delete a script and you can't retrieve a specific script OTHER THAN the split 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 49409e2b6c9bd502e79481dec9ed93de1723ae4e..ab66f40b14bd3c90299eb2d8c2444b57f2b41f8e 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/SecureResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/SecureResource.java @@ -27,6 +27,7 @@ import org.nrg.action.ClientException; import org.nrg.action.ServerException; import org.nrg.config.services.ConfigService; import org.nrg.framework.constants.Scope; +import org.nrg.framework.exceptions.NrgServiceError; import org.nrg.framework.exceptions.NrgServiceRuntimeException; import org.nrg.framework.services.SerializerService; import org.nrg.framework.utilities.Reflection; @@ -35,6 +36,8 @@ import org.nrg.xdat.base.BaseElement; import org.nrg.xdat.om.XnatAbstractresource; import org.nrg.xdat.security.helpers.Permissions; import org.nrg.xdat.security.helpers.Users; +import org.nrg.xdat.security.user.exceptions.UserInitException; +import org.nrg.xdat.security.user.exceptions.UserNotFoundException; import org.nrg.xdat.turbine.utils.AccessLogger; import org.nrg.xdat.turbine.utils.PopulateItem; import org.nrg.xdat.turbine.utils.TurbineUtils; @@ -76,6 +79,7 @@ import org.restlet.util.Series; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; +import javax.annotation.Nonnull; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @@ -129,7 +133,7 @@ public abstract class SecureResource extends Resource { protected List<String> actions = null; public String userName = null; - public UserI user = null; + private UserI user = null; public String requested_format = null; public String filepath = null; @@ -149,14 +153,6 @@ 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 && !XDAT.getSiteConfigPreferences().getRequireLogin()){ - try { - user = Users.getGuest(); - XDAT.setUserDetails(user); - } catch (Exception e) { - logger.error("",e); - } - } filepath = getRequest().getResourceRef().getRemainingPart(); if (filepath != null) { if (filepath.contains("?")) { @@ -963,6 +959,15 @@ public abstract class SecureResource extends Resource { return value != null && Boolean.parseBoolean((String) value); } + @Nonnull + public UserI getUser() { + try { + return user == null ? Users.getGuest() : user; + } catch (UserNotFoundException | UserInitException e) { + throw new NrgServiceRuntimeException(NrgServiceError.UserServiceError, "An error occurred retrieving the guest user.", e); + } + } + public String getLabelForFieldMapping(String xPath) { for (Map.Entry<String, String> entry : fieldMapping.entrySet()) { if (entry.getValue().equalsIgnoreCase(xPath)) { @@ -1048,7 +1053,6 @@ public abstract class SecureResource extends Resource { return getFileWritersAndLoadParams(getRequest().getEntity(), false); } - public void handleParam(final String key, final Object value) throws ClientException { } @@ -1096,8 +1100,8 @@ public abstract class SecureResource extends Resource { * @param entity The request entity. * @param useFileFieldName Indicates whether the form field name should be used to identify the extracted files. * @return A list of any {@link FileWriterWrapperI} objects found in the request. - * @throws FileUploadException - * @throws ClientException + * @throws FileUploadException When an error occurs uploading the file. + * @throws ClientException When an invalid request or data are submitted. */ public List<FileWriterWrapperI> getFileWritersAndLoadParams(final Representation entity, boolean useFileFieldName) throws FileUploadException, ClientException { final List<FileWriterWrapperI> wrappers = new ArrayList<>(); @@ -1546,8 +1550,8 @@ public abstract class SecureResource extends Resource { * Get a list of the possible handlers. This allows additional handlers to be injected at a later date or via a module. * * @return A list of possible handlers for the indicated package. - * @throws InstantiationException - * @throws IllegalAccessException + * @throws InstantiationException When an error occurs creating one of the handler objects. + * @throws IllegalAccessException When access levels are incorrect during access or creation. */ public static List<FilteredResourceHandlerI> getHandlers(String _package, List<FilteredResourceHandlerI> _defaultHandlers) throws InstantiationException, IllegalAccessException { if (handlers.get(_package) == null) { diff --git a/src/main/java/org/nrg/xnat/restlet/resources/SubjAssessmentResource.java b/src/main/java/org/nrg/xnat/restlet/resources/SubjAssessmentResource.java index 6d2bf20513bd428f47cd8b24695ad5800b7cf47d..6d692ce0459e66dd8f9827581b513cdc5f671eee 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/SubjAssessmentResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/SubjAssessmentResource.java @@ -32,8 +32,8 @@ import org.nrg.xft.event.persist.PersistentWorkflowUtils.EventRequirementAbsent; import org.nrg.xft.exception.InvalidValueException; import org.nrg.xft.security.UserI; import org.nrg.xft.utils.SaveItemHelper; -import org.nrg.xft.utils.XftStringUtils; import org.nrg.xft.utils.ValidationUtils.ValidationResults; +import org.nrg.xft.utils.XftStringUtils; import org.nrg.xnat.archive.Rename; import org.nrg.xnat.archive.Rename.DuplicateLabelException; import org.nrg.xnat.archive.Rename.FolderConflictException; @@ -57,6 +57,7 @@ import org.restlet.resource.Representation; import org.restlet.resource.ResourceException; import org.restlet.resource.Variant; import org.xml.sax.SAXException; + import java.net.URISyntaxException; import java.util.*; @@ -70,16 +71,17 @@ public class SubjAssessmentResource extends SubjAssessmentAbst { public SubjAssessmentResource(Context context, Request request, Response response) { super(context, request, response); - - String pID= (String)getParameter(request,"PROJECT_ID"); - if(pID!=null){ - proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); + + final UserI user = getUser(); + final String pID = (String) getParameter(request, "PROJECT_ID"); + if (pID != null) { + proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); } if(proj==null){ response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); return; - } + } subID= (String)getParameter(request,"SUBJECT_ID"); if(subID!=null){ @@ -129,6 +131,7 @@ public class SubjAssessmentResource extends SubjAssessmentAbst { } private XnatSubjectdata getExistingSubject(XnatProjectdata proj, String subjectId){ + final UserI user = getUser(); // First check if the subject is associated with the project, // if that fails check the global pool. XnatSubjectdata s = XnatSubjectdata.GetSubjectByProjectIdentifier(proj.getId(), subjectId, user, false); @@ -139,6 +142,7 @@ public class SubjAssessmentResource extends SubjAssessmentAbst { } private XnatSubjectassessordata getExistingExperiment(XnatSubjectassessordata currExp){ + final UserI user = getUser(); XnatSubjectassessordata retExp = null; if(currExp.getId()!=null){ retExp = (XnatSubjectassessordata)XnatExperimentdata.getXnatExperimentdatasById(currExp.getId(), null, completeDocument); @@ -161,8 +165,9 @@ public class SubjAssessmentResource extends SubjAssessmentAbst { @Override public void handlePut() { - XFTItem item = null; + XFTItem item = null; + final UserI user = getUser(); try { XFTItem template=null; if (existing!=null){ @@ -630,6 +635,7 @@ public class SubjAssessmentResource extends SubjAssessmentAbst { @Override public void handleDelete(){ + final UserI user = getUser(); if(expt==null&& exptID!=null){ expt=(XnatSubjectassessordata)XnatExperimentdata.getXnatExperimentdatasById(exptID, user, false); @@ -694,9 +700,10 @@ public class SubjAssessmentResource extends SubjAssessmentAbst { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override - public Representation getRepresentation(Variant variant) { + public Representation represent(Variant variant) { MediaType mt = overrideVariant(variant); + final UserI user = getUser(); if(expt==null&& exptID!=null){ expt=(XnatSubjectassessordata)XnatExperimentdata.getXnatExperimentdatasById(exptID, user, false); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/SubjectListResource.java b/src/main/java/org/nrg/xnat/restlet/resources/SubjectListResource.java index ecf088c14e589803686034d1f7d5d7557c88690f..895bcd968e69d33da9e94a2ec7ad2b9246cc0ee0 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/SubjectListResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/SubjectListResource.java @@ -14,6 +14,7 @@ import org.nrg.xft.XFTTable; import org.nrg.xft.db.ViewManager; import org.nrg.xft.schema.Wrappers.GenericWrapper.GenericWrapperElement; import org.nrg.xft.search.QueryOrganizer; +import org.nrg.xft.security.UserI; import org.nrg.xnat.helpers.xmlpath.XMLPathShortcuts; import org.restlet.Context; import org.restlet.data.MediaType; @@ -40,7 +41,7 @@ public class SubjectListResource extends QueryOrganizerResource { @Override public ArrayList<String> getDefaultFields(GenericWrapperElement e) { - ArrayList<String> al=new ArrayList<String>(); + ArrayList<String> al= new ArrayList<>(); al.add("ID"); al.add("project"); @@ -56,14 +57,14 @@ public class SubjectListResource extends QueryOrganizerResource { } @Override - public Representation getRepresentation(Variant variant) { - Representation rep=super.getRepresentation(variant); + public Representation represent(Variant variant) { + Representation rep=super.represent(variant); if(rep!=null)return rep; XFTTable table; try { - QueryOrganizer qo = new QueryOrganizer(this.getRootElementName(), user, - ViewManager.ALL); + final UserI user = getUser(); + QueryOrganizer qo = new QueryOrganizer(this.getRootElementName(), user, ViewManager.ALL); this.populateQuery(qo); @@ -80,7 +81,7 @@ public class SubjectListResource extends QueryOrganizerResource { } MediaType mt = overrideVariant(variant); - Hashtable<String, Object> params = new Hashtable<String, Object>(); + Hashtable<String, Object> params = new Hashtable<>(); if (table != null) params.put("totalRecords", table.size()); return this.representTable(table, mt, params); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/SubjectResource.java b/src/main/java/org/nrg/xnat/restlet/resources/SubjectResource.java index b2ed5a9a79a7b0ddbb2d4fc1da0f287f6b81838d..bd64c8f96b8ddb9b27cbca0b4a5773f805826b5c 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/SubjectResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/SubjectResource.java @@ -67,7 +67,8 @@ public class SubjectResource extends ItemResource { public SubjectResource(Context context, Request request, Response response) { super(context, request, response); - String pID = (String) getParameter(request, "PROJECT_ID"); + final UserI user = getUser(); + final String pID = (String) getParameter(request, "PROJECT_ID"); if (pID != null) { proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); } @@ -99,6 +100,7 @@ public class SubjectResource extends ItemResource { @Override public void handlePut() { try { + final UserI user = getUser(); XFTItem template = null; if (existing != null) { template = existing.getItem().getCurrentDBVersion(); @@ -179,7 +181,7 @@ public class SubjectResource extends ItemResource { } } if (Permissions.canCreate(user,sub.getXSIType() + "/project", newProject.getId())) { - XnatProjectparticipant pp = new XnatProjectparticipant((UserI) user); + XnatProjectparticipant pp = new XnatProjectparticipant(user); pp.setProject(newProject.getId()); if (newLabel != null) pp.setLabel(newLabel); pp.setSubjectId(sub.getId()); @@ -211,30 +213,32 @@ public class SubjectResource extends ItemResource { if (sub.getProject() == null || sub.getProject().equals("")) { sub.setProject(this.proj.getId()); - if (sub.getLabel() == null || sub.getLabel().equals("")) { - sub.setLabel(this.subID); - } - } else if (sub.getProject().equals(this.proj.getId())) { if (sub.getLabel() == null || sub.getLabel().equals("")) { sub.setLabel(this.subID); } } else { - boolean matched = false; - for (XnatProjectparticipantI pp : sub.getSharing_share()) { - if (pp.getProject().equals(this.proj.getId())) { - matched = true; + if (sub.getProject().equals(this.proj.getId())) { + if (sub.getLabel() == null || sub.getLabel().equals("")) { + sub.setLabel(this.subID); + } + } else { + boolean matched = false; + for (XnatProjectparticipantI pp : sub.getSharing_share()) { + if (pp.getProject().equals(this.proj.getId())) { + matched = true; - if (pp.getLabel() == null || pp.getLabel().equals("")) { - pp.setLabel(this.subID); + if (pp.getLabel() == null || pp.getLabel().equals("")) { + pp.setLabel(this.subID); + } + break; } - break; } - } - if (!matched) { - XnatProjectparticipant pp = new XnatProjectparticipant((UserI) user); - pp.setProject(this.proj.getId()); - pp.setLabel(this.subID); + if (!matched) { + XnatProjectparticipant pp = new XnatProjectparticipant(user); + pp.setProject(this.proj.getId()); + pp.setLabel(this.subID); + } } } } else { @@ -413,7 +417,6 @@ public class SubjectResource extends ItemResource { logger.error("", e); } catch (ActionException e) { this.getResponse().setStatus(e.getStatus(),e.getMessage()); - return; } catch (Exception e) { this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); logger.error("", e); @@ -427,6 +430,7 @@ public class SubjectResource extends ItemResource { @Override public void handleDelete() { + final UserI user = getUser(); if (sub == null && subID != null) { sub = XnatSubjectdata.getXnatSubjectdatasById(subID, user, false); @@ -489,6 +493,8 @@ public class SubjectResource extends ItemResource { public Representation represent(Variant variant) { MediaType mt = overrideVariant(variant); + final UserI user = getUser(); + if (sub == null && subID != null) { sub = XnatSubjectdata.getXnatSubjectdatasById(subID, user, false); @@ -510,7 +516,7 @@ public class SubjectResource extends ItemResource { return returnStatus(sub, mt); } else if (filepath != null && filepath.startsWith("projects")) { XFTTable t = new XFTTable(); - ArrayList<String> al = new ArrayList<String>(); + ArrayList<String> al = new ArrayList<>(); al.add("label"); al.add("ID"); al.add("Secondary_ID"); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/UserCacheResource.java b/src/main/java/org/nrg/xnat/restlet/resources/UserCacheResource.java index 24a96582b428694fb6480963a4ee5c1d87e1693a..5e29de21fdbc6df437d4e1d4acce1c1c834543cf 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/UserCacheResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/UserCacheResource.java @@ -78,7 +78,7 @@ public class UserCacheResource extends SecureResource { try { - String userPath = org.nrg.xdat.security.helpers.Users.getUserCacheUploadsPath(user); + String userPath = org.nrg.xdat.security.helpers.Users.getUserCacheUploadsPath(getUser()); String pXNAME = (String)getParameter(getRequest(),"XNAME"); String pFILE = (String)getParameter(getRequest(),"FILE"); @@ -115,7 +115,7 @@ public class UserCacheResource extends SecureResource { try { - String userPath = org.nrg.xdat.security.helpers.Users.getUserCacheUploadsPath(user); + String userPath = org.nrg.xdat.security.helpers.Users.getUserCacheUploadsPath(getUser()); String pXNAME = (String)getParameter(getRequest(),"XNAME"); String pFILE = (String)getParameter(getRequest(),"FILE"); @@ -142,7 +142,7 @@ public class UserCacheResource extends SecureResource { @Override public void handlePost() { - String userPath = org.nrg.xdat.security.helpers.Users.getUserCacheUploadsPath(user); + String userPath = org.nrg.xdat.security.helpers.Users.getUserCacheUploadsPath(getUser()); String pXNAME = (String)getParameter(getRequest(),"XNAME"); String pFILE = (String)getParameter(getRequest(),"FILE"); @@ -198,7 +198,7 @@ public class UserCacheResource extends SecureResource { try { - String userPath = org.nrg.xdat.security.helpers.Users.getUserCacheUploadsPath(user); + String userPath = org.nrg.xdat.security.helpers.Users.getUserCacheUploadsPath(getUser()); String pXNAME = (String)getParameter(getRequest(),"XNAME"); String pFILE = (String)getParameter(getRequest(),"FILE"); @@ -210,7 +210,7 @@ public class UserCacheResource extends SecureResource { createUserResource(userPath,pXNAME); - } else if (pXNAME != null && pFILE != null) { + } else if (pXNAME != null) { // commenting this out because we currently need this feature. // if (this.isQueryVariableTrue("extract")) { // // PUT Specification wants to enable a GET request on the same URL. Wouldn't want to put extracted files without the @@ -232,7 +232,7 @@ public class UserCacheResource extends SecureResource { private void returnXnameList(String userPath) { File[] fileArray = new File(userPath).listFiles(); - ArrayList<String> columns=new ArrayList<String>(); + ArrayList<String> columns= new ArrayList<>(); columns.add("Resource"); columns.add("URI"); XFTTable table=new XFTTable(); @@ -257,22 +257,20 @@ public class UserCacheResource extends SecureResource { if (dir.exists() && dir.isDirectory()) { - ArrayList<File> fileList = new ArrayList<File>(); + ArrayList<File> fileList = new ArrayList<>(); fileList.addAll(FileUtils.listFiles(dir,null,true)); //Implement a sorting comparator on file list: Unnecessary, it is sorted by the representTable method. - ArrayList<String> columns=new ArrayList<String>(); + ArrayList<String> columns= new ArrayList<>(); columns.add("Name"); columns.add("Size"); columns.add("URI"); XFTTable table=new XFTTable(); table.initTable(columns); - - Iterator<File> i = fileList.iterator(); - while (i.hasNext()) { - File f = i.next(); - String path=constructPath(f); - Object[] oarray = new Object[] { path.substring(1), f.length(), constructURI(path) }; + + for (final File file : fileList) { + String path=constructPath(file); + Object[] oarray = new Object[] { path.substring(1), file.length(), constructURI(path) }; table.insertRow(oarray); } @@ -316,7 +314,7 @@ public class UserCacheResource extends SecureResource { } private void deleteUserFiles(String userPath, String pXNAME, String pFILE) { - ArrayList<File> fileList=new ArrayList<File>(); + ArrayList<File> fileList= new ArrayList<>(); String fileString = pFILE + getRequest().getResourceRef().getRemainingPart().replaceFirst("\\?.*$", ""); if (fileString.contains(",")) { @@ -387,7 +385,7 @@ public class UserCacheResource extends SecureResource { private boolean uploadUserFile(String userPath,String pXNAME,String pFILE) { // Create any subdirectories requested as well - String dirString=null; + String dirString; String fileName=null; String remainingPart = getRequest().getResourceRef().getRemainingPart().replaceFirst("\\?.*$", ""); if ((pFILE == null || pFILE.length()<1) && !remainingPart.equals("files")) { diff --git a/src/main/java/org/nrg/xnat/restlet/resources/UserFavoriteResource.java b/src/main/java/org/nrg/xnat/restlet/resources/UserFavoriteResource.java index 9d7ca057e0b83415c7836a3fcc0a6dba549b9780..2e15821cdc60e35e55ced3d1edf53aff2adcb914 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/UserFavoriteResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/UserFavoriteResource.java @@ -13,6 +13,7 @@ package org.nrg.xnat.restlet.resources; import org.nrg.xft.XFTTable; import org.nrg.xft.db.FavEntries; import org.nrg.xft.exception.DBPoolException; +import org.nrg.xft.security.UserI; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Request; @@ -72,7 +73,7 @@ public class UserFavoriteResource extends SecureResource { FavEntries favEntry=new FavEntries(); favEntry.setId(pID); favEntry.setDataType(dataType); - favEntry.setUser(user); + favEntry.setUser(getUser()); favEntry.save(); } catch (SQLException e) { e.printStackTrace(); @@ -86,7 +87,8 @@ public class UserFavoriteResource extends SecureResource { @Override public void handleDelete() { - if(pID==null || dataType==null || user==null){ + final UserI user = getUser(); + if(pID == null || dataType == null || user == null){ getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); }else{ try { @@ -106,7 +108,7 @@ public class UserFavoriteResource extends SecureResource { XFTTable table = null; if(dataType!=null){ try { - table=FavEntries.GetFavoriteEntries(dataType, user); + table=FavEntries.GetFavoriteEntries(dataType, getUser()); } catch (SQLException e) { e.printStackTrace(); } catch (DBPoolException e) { diff --git a/src/main/java/org/nrg/xnat/restlet/resources/UserFavoritesList.java b/src/main/java/org/nrg/xnat/restlet/resources/UserFavoritesList.java index 22af739f3c2aaf22fe84805d30eaa21aef9936bd..cb3ee0e3662038ca9929d543d3adf0af17d7a302 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/UserFavoritesList.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/UserFavoritesList.java @@ -37,11 +37,11 @@ public class UserFavoritesList extends SecureResource { } @Override - public Representation getRepresentation(Variant variant) { + public Representation represent(Variant variant) { XFTTable table = null; if(dataType!=null){ try { - table=FavEntries.GetFavoriteEntries(dataType, user); + table=FavEntries.GetFavoriteEntries(dataType, getUser()); } catch (SQLException e) { e.printStackTrace(); } catch (DBPoolException e) { diff --git a/src/main/java/org/nrg/xnat/restlet/resources/UserListResource.java b/src/main/java/org/nrg/xnat/restlet/resources/UserListResource.java index 97c99d4689b5e0768ce2dc308c2e4d0d51a0372b..2d47db5dad1bc6fa1efffcf614fd3431c8afc2bd 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/UserListResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/UserListResource.java @@ -14,6 +14,7 @@ import org.nrg.xdat.XDAT; import org.nrg.xdat.security.helpers.Roles; import org.nrg.xft.XFTTable; import org.nrg.xft.exception.DBPoolException; +import org.nrg.xft.security.UserI; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Request; @@ -30,9 +31,11 @@ public class UserListResource extends SecureResource { public UserListResource(Context context, Request request, Response response) { super(context, request, response); - + getVariants().addAll(STANDARD_VARIANTS); + final UserI user = getUser(); + if (user.isGuest() || restrictUserListAccessToAdmins() && !(Roles.isSiteAdmin(user) || isWhitelisted())) { logger.error("Unauthorized Access to site-level user resources. User: " + userName); this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN,"Access Denied: Only site managers can access site-level user resources."); @@ -54,19 +57,20 @@ public class UserListResource extends SecureResource { @Override public Representation represent(Variant variant) { - Hashtable<String,Object> params=new Hashtable<String,Object>(); + Hashtable<String,Object> params= new Hashtable<>(); params.put("title", "Projects"); MediaType mt = overrideVariant(variant); String query = "SELECT xdat_user_id,login,firstname,lastname,email FROM xdat_user WHERE enabled=1 ORDER BY lastname;"; - try { - table = XFTTable.Execute(query, user.getDBName(), user.getLogin()); - } catch (SQLException e) { + try { + final UserI user = getUser(); + table = XFTTable.Execute(query, user.getDBName(), user.getLogin()); + } catch (SQLException e) { logger.error("Error running SQL " + query, e); - } catch (DBPoolException e) { + } catch (DBPoolException e) { logger.error("Connection pooling error occurred", e); - } + } if(table!=null)params.put("totalRecords", table.size()); return this.representTable(table, mt, params); @@ -82,5 +86,5 @@ public class UserListResource extends SecureResource { */ private boolean restrictUserListAccessToAdmins() { return XDAT.getSiteConfigPreferences().getRestrictUserListAccessToAdmins(); - } - } + } +} diff --git a/src/main/java/org/nrg/xnat/restlet/resources/WorkflowEventResource.java b/src/main/java/org/nrg/xnat/restlet/resources/WorkflowEventResource.java index 34f582af225cd1b4184c4e784bdf45e4473f9c7c..29e3e57f3c36e73f92ce17f0c736433e3d29a1f4 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/WorkflowEventResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/WorkflowEventResource.java @@ -4,6 +4,7 @@ import org.apache.commons.lang3.StringUtils; import org.nrg.xdat.XDAT; import org.nrg.xft.XFTTable; import org.nrg.xft.exception.DBPoolException; +import org.nrg.xft.security.UserI; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Request; @@ -29,6 +30,7 @@ public class WorkflowEventResource extends AutomationResource { _spec = (String) getRequest().getAttributes().get(SPEC); if (_log.isDebugEnabled()) { + final UserI user = getUser(); if (StringUtils.isNotBlank(_spec)) { _log.debug("Servicing event request for workflow event " + _spec + " for user " + user.getLogin()); } else { @@ -62,7 +64,7 @@ public class WorkflowEventResource extends AutomationResource { final String workflowQuery = XDAT.getContextService().getBean("populateEventsQuery", String.class); final String eventSpecCriteria = XDAT.getContextService().getBean("eventSpecCriteria", String.class); final String query = workflowQuery + (StringUtils.isBlank(_spec) ? "" : String.format(eventSpecCriteria, _spec)); - final XFTTable table = XFTTable.Execute(query, user.getDBName(), userName); + final XFTTable table = XFTTable.Execute(query, getUser().getDBName(), userName); table.sort("event_label", "ASC"); return table; } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/WorkflowResource.java b/src/main/java/org/nrg/xnat/restlet/resources/WorkflowResource.java index 9c26bee970a7454ec98f2822498d8b890871802e..4d55941fd7003949dbcb27214538fd527f6bd3d9 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/WorkflowResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/WorkflowResource.java @@ -56,6 +56,8 @@ public class WorkflowResource extends ItemResource { WrkWorkflowdata workflow; try{ + final UserI user = getUser(); + // Create the new workflow item based on information from the user. item=loadItem("wrk:workflowData", true); String pipeline_name = item.getStringProperty("pipeline_name"); @@ -110,6 +112,7 @@ public class WorkflowResource extends ItemResource { @Override public Representation represent(Variant variant) { WrkWorkflowdata workflow = null; + final UserI user = getUser(); if(workflowId != null && !workflowId.isEmpty()){ // Lookup the workflow by the ID provided by the user. workflow = (WrkWorkflowdata)WorkflowUtils.getUniqueWorkflow(user, workflowId); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/files/CatalogResource.java b/src/main/java/org/nrg/xnat/restlet/resources/files/CatalogResource.java index 92215dadbcec79231109fc11e239404e5480a868..ddc51f7bf0807127e53b01d62cc17e0d961a23ef 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/files/CatalogResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/files/CatalogResource.java @@ -61,7 +61,7 @@ public class CatalogResource extends XNATCatalogTemplate { for(String resourceID:this.resource_ids){ if(id.toString().equals(resourceID) || (label!=null && label.equals(resourceID))){ - resources.add(XnatAbstractresource.getXnatAbstractresourcesByXnatAbstractresourceId(row[0], user, false)); + resources.add(XnatAbstractresource.getXnatAbstractresourcesByXnatAbstractresourceId(row[0], getUser(), false)); } } @@ -113,13 +113,14 @@ public class CatalogResource extends XNATCatalogTemplate { @Override public void handlePost() { - if(failFastDueToNonEmptyFilePath()) { - return; - } + if(failFastDueToNonEmptyFilePath()) { + return; + } - if(this.parent!=null && this.security!=null){ - XFTItem item = null; - try { + if(this.parent!=null && this.security!=null){ + XFTItem item; + final UserI user = getUser(); + try { if(Permissions.canEdit(user,this.security)){ if(this.resources.size()>0){ this.getResponse().setStatus(Status.CLIENT_ERROR_CONFLICT, "Specified resource already exists."); @@ -244,11 +245,12 @@ public class CatalogResource extends XNATCatalogTemplate { @Override public void handleDelete(){ - if(failFastDueToNonEmptyFilePath()) { - return; - } + if(failFastDueToNonEmptyFilePath()) { + return; + } - if(resources.size()>0 && this.parent!=null && this.security!=null){ + if(resources.size()>0 && this.parent!=null && this.security!=null){ + final UserI user = getUser(); for(XnatAbstractresource resource:resources){ try { if(Permissions.canDelete(user,this.security)){ @@ -328,7 +330,7 @@ public class CatalogResource extends XNATCatalogTemplate { for(String resourceID:this.resource_ids){ if(id.toString().equals(resourceID) || (label!=null && label.equals(resourceID))){ - resources.add(XnatAbstractresource.getXnatAbstractresourcesByXnatAbstractresourceId(row[0], user, false)); + resources.add(XnatAbstractresource.getXnatAbstractresourcesByXnatAbstractresourceId(row[0], getUser(), false)); } } @@ -338,7 +340,7 @@ public class CatalogResource extends XNATCatalogTemplate { @Override - public Representation getRepresentation(Variant variant) { + public Representation represent(Variant variant) { if(failFastDueToNonEmptyFilePath()) { return null; } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/files/CatalogResourceList.java b/src/main/java/org/nrg/xnat/restlet/resources/files/CatalogResourceList.java index 3ec4f8c9c9c987de96422df6112b3e2082c0b674..0b0c1af6c7a4b82fef056a1a084708dc59abda97 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/files/CatalogResourceList.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/files/CatalogResourceList.java @@ -21,6 +21,7 @@ import org.nrg.xft.event.EventUtils; import org.nrg.xft.event.persist.PersistentWorkflowI; import org.nrg.xft.event.persist.PersistentWorkflowUtils; import org.nrg.xft.exception.ElementNotFoundException; +import org.nrg.xft.security.UserI; import org.nrg.xft.utils.XftStringUtils; import org.nrg.xnat.restlet.resources.ScanList; import org.nrg.xnat.turbine.utils.ArchivableItem; @@ -75,6 +76,8 @@ public class CatalogResourceList extends XNATTemplate { XFTItem item; try { + final UserI user = getUser(); + item=loadItem("xnat:resourceCatalog", true); if(item==null){ @@ -182,6 +185,7 @@ public class CatalogResourceList extends XNATTemplate { @Override public Representation represent(Variant variant) { + final UserI user = getUser(); XFTTable table = null; if(recons.size()>0 || scans.size()>0 || expts.size()>0 || sub!=null || proj!=null){ diff --git a/src/main/java/org/nrg/xnat/restlet/resources/files/DIRResource.java b/src/main/java/org/nrg/xnat/restlet/resources/files/DIRResource.java index f93495f5bdbb77bf7e93b296c516f946cf598486..f3415e18b69e1377d773cc555c20d83570f08501 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/files/DIRResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/files/DIRResource.java @@ -19,6 +19,7 @@ import org.nrg.xdat.om.XnatSubjectassessordata; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.XFTTable; import org.nrg.xft.schema.Wrappers.XMLWrapper.SAXWriter; +import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.representations.ZipRepresentation; import org.nrg.xnat.restlet.resources.SecureResource; import org.nrg.xnat.turbine.utils.ArcSpecManager; @@ -43,7 +44,8 @@ public class DIRResource extends SecureResource { public DIRResource(Context context, Request request, Response response) { super(context, request, response); - if(user==null){ + final UserI user = getUser(); + if(user==null || user.isGuest()){ response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); return; } @@ -83,10 +85,11 @@ public class DIRResource extends SecureResource { } else { mt=overrideVariant(variant); } - - if(user==null){ - this.getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); - return null; + + final UserI user = getUser(); + if (user == null || user.isGuest()) { + getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); + return null; } if(expt instanceof XnatSubjectassessordata){ @@ -104,7 +107,7 @@ public class DIRResource extends SecureResource { try { final List<File> src; if(filepath.equals("")){ - src=new ArrayList<File>(); + src= new ArrayList<>(); src.add(session_dir); }else{ src=getFiles(session_dir,filepath,true); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/files/FileList.java b/src/main/java/org/nrg/xnat/restlet/resources/files/FileList.java index 4ab61dee747826c5e2f692d6d00c3f65e297c367..4421fb9023f10866173cafd748d267bd947f2c99 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/files/FileList.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/files/FileList.java @@ -34,6 +34,7 @@ import org.nrg.xft.event.EventUtils; import org.nrg.xft.event.persist.PersistentWorkflowI; import org.nrg.xft.event.persist.PersistentWorkflowUtils; import org.nrg.xft.exception.ElementNotFoundException; +import org.nrg.xft.security.UserI; import org.nrg.xft.utils.FileUtils; import org.nrg.xft.utils.SaveItemHelper; import org.nrg.xnat.services.messaging.file.MoveStoredFileRequest; @@ -84,8 +85,9 @@ public class FileList extends XNATCatalogTemplate { async = isQueryVariableTrue("async", request); notifyList = isQueryVariableTrue("notify", request) ? getQueryVariable("notify").split(",") : new String[0]; try { + final UserI user = getUser(); if (resource_ids != null) { - List<Integer> alreadyAdded = new ArrayList<Integer>(); + List<Integer> alreadyAdded = new ArrayList<>(); if (catalogs != null && catalogs.size() > 0) { for (Object[] row : catalogs.rows()) { Integer id = (Integer) row[0]; @@ -205,7 +207,7 @@ public class FileList extends XNATCatalogTemplate { catalogs.resetRowCursor(); for (Hashtable<String, Object> rowHash : catalogs.rowHashs()) { Object o = rowHash.get("xnat_abstractresource_id"); - XnatAbstractresource res = XnatAbstractresource.getXnatAbstractresourcesByXnatAbstractresourceId(o, user, false); + XnatAbstractresource res = XnatAbstractresource.getXnatAbstractresourcesByXnatAbstractresourceId(o, getUser(), false); if (rowHash.containsKey("resource_path")) res.setBaseURI((String) rowHash.get("resource_path")); resources.add(res); } @@ -228,6 +230,7 @@ public class FileList extends XNATCatalogTemplate { public void handlePost() { if (parent != null && security != null) { try { + final UserI user = getUser(); if (Permissions.canEdit(user,security)) { if (proj == null) { if (parent.getItem().instanceOf("xnat:experimentData")) { @@ -350,6 +353,7 @@ public class FileList extends XNATCatalogTemplate { public void handleDelete() { if (resource != null && parent != null && security != null) { try { + final UserI user = getUser(); if (Permissions.canDelete(user,security)) { if (!((security).getItem().isActive() || (security).getItem().isQuarantine())) { //cannot modify it if it isn't active @@ -365,7 +369,7 @@ public class FileList extends XNATCatalogTemplate { } if (resource instanceof XnatResourcecatalog) { - Collection<CatEntryI> entries = new ArrayList<CatEntryI>(); + Collection<CatEntryI> entries = new ArrayList<>(); final XnatResourcecatalog catResource = (XnatResourcecatalog) resource; @@ -522,7 +526,7 @@ public class FileList extends XNATCatalogTemplate { final Map<String, String> valuesToReplace; if (structure.equalsIgnoreCase("legacy") || structure.equalsIgnoreCase("simplified")) { - valuesToReplace = new Hashtable<String, String>(); + valuesToReplace = new Hashtable<>(); } else { valuesToReplace = getReMaps(); } @@ -543,12 +547,15 @@ public class FileList extends XNATCatalogTemplate { } final String relative; - if (structure.equals("improved")) { - relative = pathForZip; - } else if (structure.equals("simplified")) { - relative = RestFileUtils.buildRelativePath(pathForZip, session_mapping, valuesToReplace, row[cat_IDIndex], (String) row[collectionIndex]).replace("/resources", "").replace("/files", ""); - } else { - relative = RestFileUtils.buildRelativePath(pathForZip, session_mapping, valuesToReplace, row[cat_IDIndex], (String) row[collectionIndex]); + switch (structure) { + case "improved": + relative = pathForZip; + break; + case "simplified": + relative = RestFileUtils.buildRelativePath(pathForZip, session_mapping, valuesToReplace, row[cat_IDIndex], (String) row[collectionIndex]).replace("/resources", "").replace("/files", ""); + break; + default: + relative = RestFileUtils.buildRelativePath(pathForZip, session_mapping, valuesToReplace, row[cat_IDIndex], (String) row[collectionIndex]); } rep.addEntry(relative, child); @@ -1153,7 +1160,7 @@ public class FileList extends XNATCatalogTemplate { String replacing = session.getArchiveDirectoryName(); if (subjectIncludedInPath) { if (session instanceof XnatImagesessiondata) { - XnatSubjectdata subject = XnatSubjectdata.getXnatSubjectdatasById(((XnatImagesessiondata) session).getSubjectId(), user, false); + XnatSubjectdata subject = XnatSubjectdata.getXnatSubjectdatasById(((XnatImagesessiondata) session).getSubjectId(), getUser(), false); replacing = subject.getLabel() + "/" + replacing; } } @@ -1178,7 +1185,7 @@ public class FileList extends XNATCatalogTemplate { } private ArrayList<String> getSessionIds() { - ArrayList<String> session_ids = new ArrayList<String>(); + ArrayList<String> session_ids = new ArrayList<>(); if (assesseds.size() > 0) { for (XnatExperimentdata session : assesseds) { session_ids.add(session.getArchiveDirectoryName()); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/files/FileResource.java b/src/main/java/org/nrg/xnat/restlet/resources/files/FileResource.java index 2847162d5fcd67dcb7498c0c6bb2a44af3b49102..24c7858dab8eecf50418afac35cf1051f128ec4d 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/files/FileResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/files/FileResource.java @@ -20,6 +20,7 @@ import org.nrg.xft.ItemI; import org.nrg.xft.XFTTable; import org.nrg.xft.exception.ElementNotFoundException; import org.nrg.xft.search.CriteriaCollection; +import org.nrg.xft.security.UserI; import org.nrg.xft.utils.FileUtils; import org.nrg.xnat.restlet.resources.ItemResource; import org.nrg.xnat.restlet.resources.ScanResource; @@ -52,193 +53,194 @@ public class FileResource extends ItemResource { String index=null; String filename=null; - - - + + public FileResource(Context context, Request request, Response response) { super(context, request, response); - - String pID= (String)getParameter(request,"PROJECT_ID"); - if(pID!=null){ - proj = XnatProjectdata.getXnatProjectdatasById(pID, user, false); + + final UserI user = getUser(); + + final String pID = (String) getParameter(request, "PROJECT_ID"); + if (pID != null) { + proj = XnatProjectdata.getXnatProjectdatasById(pID, user, false); + } + + String subID = (String) getParameter(request, "SUBJECT_ID"); + if (subID != null) { + if (this.proj != null) { + sub = XnatSubjectdata.GetSubjectByProjectIdentifier(proj.getId(), subID, user, false); } - - String subID= (String)getParameter(request,"SUBJECT_ID"); - if(subID!=null){ - if(this.proj!=null) - sub=XnatSubjectdata.GetSubjectByProjectIdentifier(proj.getId(), subID,user, false); - - if(sub==null){ - sub=XnatSubjectdata.getXnatSubjectdatasById(subID, user, false); - } + + if (sub == null) { + sub = XnatSubjectdata.getXnatSubjectdatasById(subID, user, false); } - - String assessid= (String)getParameter(request,"ASSESSED_ID"); - if(assessid!=null){ - assessed=XnatImagesessiondata.getXnatImagesessiondatasById(assessid, user, false); - - if(assessed==null){ - assessed=(XnatImagesessiondata)XnatImagesessiondata.GetExptByProjectIdentifier(proj.getId(), assessid,user, false); - } + } + + String assessid = (String) getParameter(request, "ASSESSED_ID"); + if (assessid != null) { + assessed = XnatImagesessiondata.getXnatImagesessiondatasById(assessid, user, false); + + if (assessed == null) { + assessed = (XnatImagesessiondata) XnatImagesessiondata.GetExptByProjectIdentifier(proj.getId(), assessid, user, false); } - - String exptID= (String)getParameter(request,"EXPT_ID"); - if(exptID!=null){ - expt=XnatImagesessiondata.getXnatImagesessiondatasById(exptID, user, false); - - if(expt==null){ - expt=(XnatImagesessiondata)XnatImagesessiondata.GetExptByProjectIdentifier(proj.getId(), exptID,user, false); - } + } + + String exptID = (String) getParameter(request, "EXPT_ID"); + if (exptID != null) { + expt = XnatImagesessiondata.getXnatImagesessiondatasById(exptID, user, false); + + if (expt == null) { + expt = (XnatImagesessiondata) XnatImagesessiondata.GetExptByProjectIdentifier(proj.getId(), exptID, user, false); } + } - String scanID= (String)getParameter(request,"SCAN_ID"); - if(scanID!=null && this.assessed!=null){ - CriteriaCollection cc= new CriteriaCollection("AND"); - cc.addClause("xnat:imageScanData/ID", scanID); - cc.addClause("xnat:imageScanData/image_session_ID", assessed.getId()); - ArrayList<XnatImagescandata> scans=XnatImagescandata.getXnatImagescandatasByField(cc, user, completeDocument); - if(scans.size()>0){ - scan=scans.get(0); - } - } + String scanID = (String) getParameter(request, "SCAN_ID"); + if (scanID != null && this.assessed != null) { + CriteriaCollection cc = new CriteriaCollection("AND"); + cc.addClause("xnat:imageScanData/ID", scanID); + cc.addClause("xnat:imageScanData/image_session_ID", assessed.getId()); + ArrayList<XnatImagescandata> scans = XnatImagescandata.getXnatImagescandatasByField(cc, user, completeDocument); + if (scans.size() > 0) { + scan = scans.get(0); + } + } + + type = (String) getParameter(request, "TYPE"); - type= (String)getParameter(request,"TYPE"); + String reconID = (String) getParameter(request, "RECON_ID"); + if (reconID != null) { + CriteriaCollection cc = new CriteriaCollection("AND"); + cc.addClause("xnat:reconstructedImageData/ID", reconID); + cc.addClause("xnat:reconstructedImageData/image_session_ID", assessed.getId()); + ArrayList<XnatReconstructedimagedata> scans = XnatReconstructedimagedata.getXnatReconstructedimagedatasByField(cc, user, completeDocument); + if (scans.size() > 0) { + recon = scans.get(0); + } + } + + String resourceID = (String) getParameter(request, "RESOURCE_ID"); + try { + Integer.parseInt(resourceID); + } catch (NumberFormatException e1) { + //This should be a number, if not something shady is going on. + AdminUtils.sendAdminEmail(user, "Possible SQL Injection attempt.", "User passed " + resourceID + " as a resource identifier."); + this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); + return; + } - String reconID= (String)getParameter(request,"RECON_ID"); - if(reconID!=null){ - CriteriaCollection cc= new CriteriaCollection("AND"); - cc.addClause("xnat:reconstructedImageData/ID", reconID); - cc.addClause("xnat:reconstructedImageData/image_session_ID", assessed.getId()); - ArrayList<XnatReconstructedimagedata> scans=XnatReconstructedimagedata.getXnatReconstructedimagedatasByField(cc, user, completeDocument); - if(scans.size()>0){ - recon=scans.get(0); + index = (String) getParameter(request, "INDEX"); + filename = (String) getParameter(request, "FILENAME"); + + String query = "SELECT res.xnat_abstractresource_id,format,description,content,label,uri "; + if (recon != null) { + security = this.assessed; + parent = recon; + if (type != null) { + if (type.equals("in")) { + query += " FROM recon_in_resource map " + + " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + + " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; + query += " WHERE xnat_reconstructedimagedata_xnat_reconstructedimagedata_id=" + recon.getXnatReconstructedimagedataId(); + query += " AND map.xnat_abstractresource_xnat_abstractresource_id=" + resourceID; + } else { + query += " FROM recon_out_resource map " + + " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + + " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; + query += " WHERE xnat_reconstructedimagedata_xnat_reconstructedimagedata_id=" + recon.getXnatReconstructedimagedataId() + ""; + query += " AND map.xnat_abstractresource_xnat_abstractresource_id=" + resourceID; } + } else { + //resources + query += " FROM recon_out_resource map " + + " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + + " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; + query += " WHERE xnat_imageassessordata_id='" + expt.getId() + "'"; + query += " AND map.xnat_abstractresource_xnat_abstractresource_id=" + resourceID; } - - String resourceID= (String)getParameter(request,"RESOURCE_ID"); + } else if (scan != null) { + security = this.assessed; + parent = scan; + query += " FROM xnat_abstractresource abst" + + " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; + query += " WHERE xnat_imagescandata_xnat_imagescandata_id=" + scan.getXnatImagescandataId() + ""; + query += " AND abst.xnat_abstractresource_id=" + resourceID; + } else if (expt != null) { + security = this.expt; + parent = this.expt; try { - Integer.parseInt(resourceID); - } catch (NumberFormatException e1) { - //This should be a number, if not something shady is going on. - AdminUtils.sendAdminEmail(user,"Possible SQL Injection attempt.", "User passed "+ resourceID+" as a resource identifier."); - this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); - return; - } - - index= (String)getParameter(request,"INDEX"); - filename= (String)getParameter(request,"FILENAME"); - - String query="SELECT res.xnat_abstractresource_id,format,description,content,label,uri "; - if(recon!=null){ - security=this.assessed; - parent=recon; - if(type!=null){ - if(type.equals("in")){ - query+=" FROM recon_in_resource map " + - " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + - " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; - query+=" WHERE xnat_reconstructedimagedata_xnat_reconstructedimagedata_id=" + recon.getXnatReconstructedimagedataId(); - query+=" AND map.xnat_abstractresource_xnat_abstractresource_id="+resourceID; - }else{ - query+=" FROM recon_out_resource map " + - " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + - " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; - query+=" WHERE xnat_reconstructedimagedata_xnat_reconstructedimagedata_id=" + recon.getXnatReconstructedimagedataId() + ""; - query+=" AND map.xnat_abstractresource_xnat_abstractresource_id="+resourceID; - } - }else{ - //resources - query+=" FROM recon_out_resource map " + - " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + - " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; - query+=" WHERE xnat_imageassessordata_id='" + expt.getId() + "'"; - query+=" AND map.xnat_abstractresource_xnat_abstractresource_id="+resourceID; - } - }else if(scan!=null){ - security=this.assessed; - parent=scan; - query+=" FROM xnat_abstractresource abst" + - " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; - query+= " WHERE xnat_imagescandata_xnat_imagescandata_id="+scan.getXnatImagescandataId() + ""; - query+=" AND abst.xnat_abstractresource_id="+resourceID; - }else if(expt!=null){ - security=this.expt; - parent=this.expt; - try { - if(expt.getItem().instanceOf("xnat:imageAssessorData")){ - security=this.expt; - parent=this.expt; - if(type!=null){ - if(type.equals("in")){ - query+=" FROM img_assessor_in_resource map " + - " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + - " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; - query+=" WHERE xnat_imageassessordata_id='" + expt.getId() + "'"; - query+=" AND map.xnat_abstractresource_xnat_abstractresource_id="+resourceID; - }else{ - query+=" FROM img_assessor_out_resource map " + - " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + - " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; - query+=" WHERE xnat_imageassessordata_id='" + expt.getId() + "'"; - query+=" AND map.xnat_abstractresource_xnat_abstractresource_id="+resourceID; - } - }else{ - //resources - query+=" FROM xnat_experimentdata_resource map " + - " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + - " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; - query+= " WHERE xnat_experimentdata_id='"+expt.getId() + "'"; - query+=" AND map.xnat_abstractresource_xnat_abstractresource_id="+resourceID; + if (expt.getItem().instanceOf("xnat:imageAssessorData")) { + security = this.expt; + parent = this.expt; + if (type != null) { + if (type.equals("in")) { + query += " FROM img_assessor_in_resource map " + + " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + + " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; + query += " WHERE xnat_imageassessordata_id='" + expt.getId() + "'"; + query += " AND map.xnat_abstractresource_xnat_abstractresource_id=" + resourceID; + } else { + query += " FROM img_assessor_out_resource map " + + " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + + " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; + query += " WHERE xnat_imageassessordata_id='" + expt.getId() + "'"; + query += " AND map.xnat_abstractresource_xnat_abstractresource_id=" + resourceID; } - }else{ + } else { //resources - query+=" FROM xnat_experimentdata_resource map " + - " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + - " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; - query+= " WHERE xnat_experimentdata_id='"+expt.getId() + "'"; - query+=" AND map.xnat_abstractresource_xnat_abstractresource_id="+resourceID; + query += " FROM xnat_experimentdata_resource map " + + " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + + " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; + query += " WHERE xnat_experimentdata_id='" + expt.getId() + "'"; + query += " AND map.xnat_abstractresource_xnat_abstractresource_id=" + resourceID; } - } catch (ElementNotFoundException e) { - e.printStackTrace(); + } else { + //resources + query += " FROM xnat_experimentdata_resource map " + + " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + + " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; + query += " WHERE xnat_experimentdata_id='" + expt.getId() + "'"; + query += " AND map.xnat_abstractresource_xnat_abstractresource_id=" + resourceID; } - }else if(sub!=null){ - security=this.sub; - parent=this.sub; - //resources - query+=" FROM xnat_subjectdata_resource map " + - " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + - " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; - query+=" WHERE xnat_subjectdata_id='" + sub.getId() + "'"; - query+=" AND map.xnat_abstractresource_xnat_abstractresource_id="+resourceID; - }else if(proj!=null){ - security=this.proj; - parent=this.proj; - //resources - query+=" FROM xnat_projectdata_resource map " + - " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + - " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; - query+=" WHERE xnat_projectdata_id='" + proj.getId() + "'"; - query+=" AND map.xnat_abstractresource_xnat_abstractresource_id="+resourceID; - }else{ - query+=" FROM xnat_abstractresource abst" + - " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; - query += " WHERE res.xnat_abstractresource_id IS NULL"; + } catch (ElementNotFoundException e) { + e.printStackTrace(); } - - try { - XFTTable table=XFTTable.Execute(query, user.getDBName(), userName); - if(table.size()>0){ - resource=XnatAbstractresource.getXnatAbstractresourcesByXnatAbstractresourceId(resourceID, user, false); - this.getVariants().add(new Variant(MediaType.ALL)); - }else{ - response.setStatus(Status.CLIENT_ERROR_FORBIDDEN,"Invalid read permissions"); - } - } catch (Exception e) { - logger.error("",e); + } else if (sub != null) { + security = this.sub; + parent = this.sub; + //resources + query += " FROM xnat_subjectdata_resource map " + + " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + + " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; + query += " WHERE xnat_subjectdata_id='" + sub.getId() + "'"; + query += " AND map.xnat_abstractresource_xnat_abstractresource_id=" + resourceID; + } else if (proj != null) { + security = this.proj; + parent = this.proj; + //resources + query += " FROM xnat_projectdata_resource map " + + " LEFT JOIN xnat_abstractresource abst ON map.xnat_abstractresource_xnat_abstractresource_id=abst.xnat_abstractresource_id" + + " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; + query += " WHERE xnat_projectdata_id='" + proj.getId() + "'"; + query += " AND map.xnat_abstractresource_xnat_abstractresource_id=" + resourceID; + } else { + query += " FROM xnat_abstractresource abst" + + " LEFT JOIN xnat_resource res ON abst.xnat_abstractresource_id=res.xnat_abstractresource_id"; + query += " WHERE res.xnat_abstractresource_id IS NULL"; + } + + try { + XFTTable table = XFTTable.Execute(query, user.getDBName(), userName); + if (table.size() > 0) { + resource = XnatAbstractresource.getXnatAbstractresourcesByXnatAbstractresourceId(resourceID, user, false); + this.getVariants().add(new Variant(MediaType.ALL)); + } else { + response.setStatus(Status.CLIENT_ERROR_FORBIDDEN, "Invalid read permissions"); } + } catch (Exception e) { + logger.error("", e); + } } - @Override public boolean allowDelete() { return true; @@ -248,7 +250,7 @@ public class FileResource extends ItemResource { public void handleDelete(){ if(resource!=null && this.parent!=null && this.security!=null){ try { - if(Permissions.canEdit(user,this.security)){ + if(Permissions.canEdit(getUser(),this.security)){ if(proj==null){ if(parent.getItem().instanceOf("xnat:experimentData")){ @@ -292,15 +294,12 @@ public class FileResource extends ItemResource { } }else{ this.getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND,"File missing"); - return; } }else{ this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN,"User account doesn't have permission to modify this session."); - return; } } catch (Exception e) { this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,e.getMessage()); - return; } } } @@ -342,7 +341,7 @@ public class FileResource extends ItemResource { } @Override - public Representation getRepresentation(Variant variant) { + public Representation represent(Variant variant) { MediaType mt = overrideVariant(variant); if(resource!=null){ diff --git a/src/main/java/org/nrg/xnat/restlet/resources/files/XNATCatalogTemplate.java b/src/main/java/org/nrg/xnat/restlet/resources/files/XNATCatalogTemplate.java index 7d2027244c37237e0162f0c9d6a9ca229df5e032..7017f2a15bd3926866d6f5dc13a4fa3fa480abd8 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/files/XNATCatalogTemplate.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/files/XNATCatalogTemplate.java @@ -174,7 +174,7 @@ public class XNATCatalogTemplate extends XNATTemplate { } Date d=EventUtils.getEventDate(ci, false); - return XnatResourceInfo.buildResourceInfo(description, format, content, tags,user,d,d,EventUtils.getEventId(ci)); + return XnatResourceInfo.buildResourceInfo(description, format, content, tags,getUser(),d,d,EventUtils.getEventId(ci)); } protected ResourceModifierA buildResourceModifier(final boolean overwrite,EventMetaI ci) throws Exception{ @@ -212,6 +212,6 @@ public class XNATCatalogTemplate extends XNATTemplate { throw new Exception("Unknown resource"); } - return builder.buildResourceModifier(overwrite,user,ci); + return builder.buildResourceModifier(overwrite,getUser(),ci); } } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/files/XNATTemplate.java b/src/main/java/org/nrg/xnat/restlet/resources/files/XNATTemplate.java index 56190dcc6cb764f6531cb5e43b99aacc4f2f3eb7..a856ff0f78ae2766aa55bd79a785dc4f6eb09253 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/files/XNATTemplate.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/files/XNATTemplate.java @@ -20,10 +20,10 @@ import org.nrg.xft.db.PoolDBUtils; import org.nrg.xft.event.EventMetaI; import org.nrg.xft.schema.Wrappers.GenericWrapper.GenericWrapperElement; import org.nrg.xft.search.CriteriaCollection; +import org.nrg.xft.security.UserI; import org.nrg.xft.utils.FileUtils; import org.nrg.xft.utils.SaveItemHelper; import org.nrg.xft.utils.XftStringUtils; -import org.nrg.xnat.exceptions.InvalidArchiveStructure; import org.nrg.xnat.restlet.resources.SecureResource; import org.nrg.xnat.restlet.util.XNATRestConstants; import org.restlet.Context; @@ -65,7 +65,8 @@ public class XNATTemplate extends SecureResource { super(context, request, response); String pID= (String)getParameter(request,"PROJECT_ID"); - if(pID!=null){ + final UserI user = getUser(); + if(pID != null){ proj = XnatProjectdata.getProjectByIDorAlias(pID, user, false); if(proj==null){ @@ -79,11 +80,11 @@ public class XNATTemplate extends SecureResource { if(subID!=null){ if(this.proj!=null) sub = XnatSubjectdata.GetSubjectByProjectIdentifier(proj - .getId(), subID,user, false); + .getId(), subID, user, false); if(sub==null){ sub = XnatSubjectdata.getXnatSubjectdatasById(subID, user, - false); + false); if(sub!=null && (proj!=null && !sub.hasProject(proj.getId()))){ sub=null; } @@ -101,7 +102,7 @@ public class XNATTemplate extends SecureResource { if(assessid!=null){ for(String s: XftStringUtils.CommaDelimitedStringToArrayList(assessid)){ XnatExperimentdata assessed = XnatImagesessiondata.getXnatImagesessiondatasById( - s, user, false); + s, user, false); if(assessed!=null && (proj!=null && !assessed.hasProject(proj.getId()))){ assessed=null; @@ -110,7 +111,7 @@ public class XNATTemplate extends SecureResource { if (assessed == null && proj!=null) { assessed = (XnatImagesessiondata) XnatImagesessiondata .GetExptByProjectIdentifier(proj.getId(), s, - user, false); + user, false); } if(assessed!=null){ @@ -135,12 +136,12 @@ public class XNATTemplate extends SecureResource { if(exptID!=null){ for(String s: XftStringUtils.CommaDelimitedStringToArrayList(exptID)){ XnatExperimentdata expt = XnatExperimentdata.getXnatExperimentdatasById(s, - user, false); + user, false); if (expt == null && proj!=null) { expt = (XnatExperimentdata) XnatExperimentdata .GetExptByProjectIdentifier(proj.getId(), s, - user, false); + user, false); } if (expt != null && assesseds.size()>0) { @@ -242,7 +243,7 @@ public class XNATTemplate extends SecureResource { scans = XnatImagescandata .getXnatImagescandatasByField(cc, user, - completeDocument); + completeDocument); if (scans.size() != 1 && !this.getRequest().getMethod().equals(Method.GET)) { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND, @@ -303,7 +304,7 @@ public class XNATTemplate extends SecureResource { recons = XnatReconstructedimagedata .getXnatReconstructedimagedatasByField(cc, user, - completeDocument); + completeDocument); if (recons.size() > 0) { if(type==null){ type="out"; @@ -355,7 +356,8 @@ public class XNATTemplate extends SecureResource { XnatExperimentdata assessed=null; if(this.assesseds.size()==1)assessed=assesseds.get(0); - if (recons.size()>0) { + final UserI user = getUser(); + if (recons.size() > 0) { //reconstruction if (assessed == null) { this.getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND, @@ -410,7 +412,7 @@ public class XNATTemplate extends SecureResource { recon.setOut_file(catResource); } - SaveItemHelper.authorizedSave(recon,user, false, false,ci); + SaveItemHelper.authorizedSave(recon, user, false, false, ci); return true; } else if (scans.size()>0) { XnatImagescandata scan=scans.get(0); @@ -463,7 +465,7 @@ public class XNATTemplate extends SecureResource { scan.setFile(catResource); - SaveItemHelper.authorizedSave(scan,user, false, false,ci); + SaveItemHelper.authorizedSave(scan, user, false, false, ci); return true; } else if (expts.size()>0) { // experiment @@ -527,13 +529,13 @@ public class XNATTemplate extends SecureResource { iad.setOut_file(catResource); } - SaveItemHelper.authorizedSave(iad,user, false, false,ci); + SaveItemHelper.authorizedSave(iad, user, false, false, ci); }else{ XnatExperimentdata copy=session.getLightCopy(); copy.setResources_resource(catResource); - SaveItemHelper.authorizedSave(copy,user, false, false,ci); + SaveItemHelper.authorizedSave(copy, user, false, false, ci); } return true; }else if(sub!=null){ @@ -573,7 +575,7 @@ public class XNATTemplate extends SecureResource { XnatSubjectdata copy=sub.getLightCopy(); copy.setResources_resource(catResource); - SaveItemHelper.authorizedSave(copy,user, false, false,ci); + SaveItemHelper.authorizedSave(copy, user, false, false, ci); return true; }else if(proj!=null){ String dest_path=null; @@ -609,7 +611,7 @@ public class XNATTemplate extends SecureResource { catResource.setUri(dest.getAbsolutePath()); proj.setResources_resource(catResource); - SaveItemHelper.authorizedSave(proj,user, false, false,ci); + SaveItemHelper.authorizedSave(proj, user, false, false, ci); return true; } return true; @@ -1178,6 +1180,6 @@ public class XNATTemplate extends SecureResource { query.append(" WHERE xnat_abstractresource_id IS NULL"); } - return XFTTable.Execute(query.toString(), user.getDBName(), userName); + return XFTTable.Execute(query.toString(), getUser().getDBName(), userName); } } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcScanResource.java b/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcScanResource.java index 2991c2c756c74d2cf7ec0f6d11097402979838bf..1dc16f988c6cd3ed3bf7f278302e28b09c55d2c4 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcScanResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcScanResource.java @@ -76,7 +76,7 @@ public class PrearcScanResource extends PrearcSessionResourceA { File srcXML; try { try { - sessionDIR = PrearcUtils.getPrearcSessionDir(user, project, timestamp, session,false); + sessionDIR = PrearcUtils.getPrearcSessionDir(getUser(), project, timestamp, session,false); srcXML=new File(sessionDIR.getAbsolutePath()+".xml"); } catch (InvalidPermissionException e) { logger.error("",e); @@ -160,7 +160,7 @@ public class PrearcScanResource extends PrearcSessionResourceA { final File sessionDIR; final File srcXML; try { - sessionDIR = PrearcUtils.getPrearcSessionDir(user, project, timestamp, session,false); + sessionDIR = PrearcUtils.getPrearcSessionDir(getUser(), project, timestamp, session,false); srcXML=new File(sessionDIR.getAbsolutePath()+".xml"); } catch (InvalidPermissionException e) { logger.error("",e); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcSessionListResource.java b/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcSessionListResource.java index dac3dee8635ab0727f9287cb5ea70728df1968a3..94e6b40fcda13db319f2a88fd0e86234a18c72e3 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcSessionListResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcSessionListResource.java @@ -13,6 +13,7 @@ package org.nrg.xnat.restlet.resources.prearchive; import org.apache.commons.lang3.StringUtils; import org.nrg.xdat.security.helpers.Roles; import org.nrg.xft.XFTTable; +import org.nrg.xft.security.UserI; import org.nrg.xnat.helpers.prearchive.*; import org.nrg.xnat.restlet.resources.SecureResource; import org.restlet.Context; @@ -54,7 +55,7 @@ public final class PrearcSessionListResource extends SecureResource { getVariants().add(new Variant(MediaType.TEXT_HTML)); getVariants().add(new Variant(MediaType.TEXT_XML)); - if (request.getMethod() == Method.PUT && !Roles.isSiteAdmin(user)) { + if (request.getMethod() == Method.PUT && !Roles.isSiteAdmin(getUser())) { response.setStatus(Status.CLIENT_ERROR_FORBIDDEN, "Only administrators can request a rebuild of the prearchive."); } } @@ -87,8 +88,9 @@ public final class PrearcSessionListResource extends SecureResource { final MediaType mt = overrideVariant(variant); XFTTable table; - - if(this.getQueryVariable("tag")!=null){ + + final UserI user = getUser(); + if(this.getQueryVariable("tag") != null){ final String tag=getQueryVariable("tag"); try { if(!Roles.isSiteAdmin(user)){ diff --git a/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcSessionResource.java b/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcSessionResource.java index 98bcad9be393db5291be735669c5847bb1cabaf7..adcceb15156ecc9f0663adb8e0cbcb326d28220f 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcSessionResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcSessionResource.java @@ -21,6 +21,7 @@ import org.nrg.framework.constants.PrearchiveCode; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xft.XFTTable; import org.nrg.xft.exception.InvalidPermissionException; +import org.nrg.xft.security.UserI; import org.nrg.xnat.archive.FinishImageUpload; import org.nrg.xnat.helpers.prearchive.*; import org.nrg.xnat.helpers.prearchive.PrearcDatabase.SyncFailedException; @@ -127,8 +128,9 @@ public final class PrearcSessionResource extends SecureResource { } final File sessionDir; + final UserI user = getUser(); try { - sessionDir = PrearcUtils.getPrearcSessionDir(user, project, timestamp, session,true); + sessionDir = PrearcUtils.getPrearcSessionDir(user, project, timestamp, session, true); } catch (InvalidPermissionException e) { logger.error("",e); this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, e.getMessage()); @@ -145,7 +147,7 @@ public final class PrearcSessionResource extends SecureResource { try { if (PrearcDatabase.setStatus(session, timestamp, project, PrearcUtils.PrearcStatus.BUILDING)) { PrearcDatabase.buildSession(sessionDir, session, timestamp, project, (String) params.get(VISIT), (String) params.get(PROTOCOL), (String) params.get(TIMEZONE), (String) params.get(SOURCE)); - PrearcUtils.resetStatus(user, project, timestamp, session,true); + PrearcUtils.resetStatus(user, project, timestamp, session, true); returnString(wrapPartialDataURI(PrearcUtils.buildURI(project,timestamp,session)), MediaType.TEXT_URI_LIST,Status.SUCCESS_OK); } else { this.getResponse().setStatus(Status.CLIENT_ERROR_CONFLICT, "session document locked"); @@ -162,7 +164,7 @@ public final class PrearcSessionResource extends SecureResource { } else if (POST_ACTION_RESET.equals(action)) { try { final String tag= getQueryVariable("tag"); - PrearcUtils.resetStatus(user, project, timestamp, session,tag,true); + PrearcUtils.resetStatus(user, project, timestamp, session, tag, true); returnString(wrapPartialDataURI(PrearcUtils.buildURI(project,timestamp,session)), MediaType.TEXT_URI_LIST,Status.SUCCESS_OK); } catch (InvalidPermissionException e) { logger.error("",e); @@ -215,9 +217,9 @@ public final class PrearcSessionResource extends SecureResource { PrearcDatabase.setAutoArchive(session, timestamp, project, PrearchiveCode.code(p.getArcSpecification().getPrearchiveCode())); } PrearcDatabase.buildSession(sessionDir, session, timestamp, project, (String) params.get(VISIT), (String) params.get(PROTOCOL), (String) params.get(TIMEZONE), (String) params.get(SOURCE)); - PrearcUtils.resetStatus(user, project, timestamp, session,true); + PrearcUtils.resetStatus(user, project, timestamp, session, true); - final FinishImageUpload uploader=new FinishImageUpload(null, user, new PrearcSession(project,timestamp,session,params,user), null, false, true, false); + final FinishImageUpload uploader=new FinishImageUpload(null, user, new PrearcSession(project, timestamp, session, params, user), null, false, true, false); try { if(uploader.isAutoArchive()){ returnString(wrapPartialDataURI(uploader.call()),Status.REDIRECTION_PERMANENT); @@ -266,10 +268,11 @@ public final class PrearcSessionResource extends SecureResource { this.getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, ""); return; } - + + final UserI user = getUser(); try { //checks if the user can access this session - PrearcUtils.getPrearcSessionDir(user, project, timestamp, session,false); + PrearcUtils.getPrearcSessionDir(user, project, timestamp, session, false); } catch (InvalidPermissionException e) { logger.error("",e); this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, e.getMessage()); @@ -307,8 +310,9 @@ public final class PrearcSessionResource extends SecureResource { @Override public Representation getRepresentation(final Variant variant){ final File sessionDir; + final UserI user = getUser(); try { - sessionDir = PrearcUtils.getPrearcSessionDir(user, project, timestamp, session,false); + sessionDir = PrearcUtils.getPrearcSessionDir(user, project, timestamp, session, false); } catch (InvalidPermissionException e) { this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN, e.getMessage()); return null; diff --git a/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcSessionResourceA.java b/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcSessionResourceA.java index 6114a771b059cd09c0eba116450f9ebfa7fe49bd..2ec5d52ab5fb103feaf4a530a633e1e01bef91f3 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcSessionResourceA.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/prearchive/PrearcSessionResourceA.java @@ -69,7 +69,7 @@ public abstract class PrearcSessionResourceA extends SecureResource { File sessionDIR; File srcXML; try { - sessionDIR = PrearcUtils.getPrearcSessionDir(user, project, timestamp, session,false); + sessionDIR = PrearcUtils.getPrearcSessionDir(getUser(), project, timestamp, session,false); srcXML=new File(sessionDIR.getAbsolutePath()+".xml"); } catch (InvalidPermissionException e) { logger.error("",e); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/prearchive/RecentPrearchiveSessions.java b/src/main/java/org/nrg/xnat/restlet/resources/prearchive/RecentPrearchiveSessions.java index 6d12e936afbbb445b0934e08fa727e51cd7fac1d..d651712c86fbfbe43b332f29c2348bf20f31e9d9 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/prearchive/RecentPrearchiveSessions.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/prearchive/RecentPrearchiveSessions.java @@ -122,8 +122,8 @@ public class RecentPrearchiveSessions extends SecureResource { ArrayList<ArrayList<Object>> rows = new ArrayList<ArrayList<Object>>(); for (SessionData s: mostRecent) { - if (UserHelper.getUserHelperService(user).hasEditAccessToSessionDataByTag(s.getProject())){ - ArrayList<Object> row= new ArrayList<Object>(); + if (UserHelper.getUserHelperService(getUser()).hasEditAccessToSessionDataByTag(s.getProject())){ + ArrayList<Object> row= new ArrayList<>(); for (DatabaseSession v : DatabaseSession.values()) { // replace internal url with the external one that doesn't have // local filesystem information. diff --git a/src/main/java/org/nrg/xnat/restlet/resources/search/CachedSearchColumnResource.java b/src/main/java/org/nrg/xnat/restlet/resources/search/CachedSearchColumnResource.java index 930d4533e0c51ee9150929be354f2cea218bc968..92dd225974c0e0cdabfc792b04503ba12eae19cb 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/search/CachedSearchColumnResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/search/CachedSearchColumnResource.java @@ -10,10 +10,10 @@ */ package org.nrg.xnat.restlet.resources.search; -import org.apache.log4j.Logger; import org.nrg.xft.XFTTable; import org.nrg.xft.db.MaterializedView; import org.nrg.xft.db.MaterializedViewI; +import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.resources.SecureResource; import org.restlet.Context; import org.restlet.data.MediaType; @@ -22,12 +22,14 @@ import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.resource.Representation; import org.restlet.resource.Variant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.sql.SQLException; import java.util.Hashtable; public class CachedSearchColumnResource extends SecureResource { - static org.apache.log4j.Logger logger = Logger.getLogger(CachedSearchResource.class); + private static final Logger logger = LoggerFactory.getLogger(CachedSearchResource.class); String tableName=null; String columnName=null; @@ -45,8 +47,8 @@ public class CachedSearchColumnResource extends SecureResource { @Override - public Representation getRepresentation(Variant variant) { - Hashtable<String,Object> params=new Hashtable<String,Object>(); + public Representation represent(Variant variant) { + Hashtable<String,Object> params= new Hashtable<>(); if(tableName!=null){ params.put("ID", tableName); } @@ -56,8 +58,8 @@ public class CachedSearchColumnResource extends SecureResource { XFTTable table=null; try { - - MaterializedViewI mv = MaterializedView.retrieveView(tableName, user); + final UserI user = getUser(); + final MaterializedViewI mv = MaterializedView.retrieveView(tableName, user); if(mv.getUser_name().equals(user.getLogin())){ table=mv.getColumnValues(columnName); } diff --git a/src/main/java/org/nrg/xnat/restlet/resources/search/CachedSearchResource.java b/src/main/java/org/nrg/xnat/restlet/resources/search/CachedSearchResource.java index 9afcb2684ca8cc6b225e80c99825df10bf4bcca8..cae8a82cdfcfbca2c0f4c28cfc42c83b2d0d6f49 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/search/CachedSearchResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/search/CachedSearchResource.java @@ -11,9 +11,7 @@ package org.nrg.xnat.restlet.resources.search; import com.noelios.restlet.ext.servlet.ServletCall; - import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.nrg.xdat.search.DisplaySearch; import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xdat.turbine.utils.TurbineUtils; @@ -21,7 +19,7 @@ import org.nrg.xft.XFTTable; import org.nrg.xft.db.MaterializedView; import org.nrg.xft.db.MaterializedViewI; import org.nrg.xft.db.PoolDBUtils; -import org.nrg.xft.utils.XftStringUtils; +import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.presentation.RESTHTMLPresenter; import org.nrg.xnat.restlet.resources.SecureResource; import org.restlet.Context; @@ -31,67 +29,69 @@ import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.resource.Representation; import org.restlet.resource.Variant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.sql.SQLException; import java.util.Hashtable; public class CachedSearchResource extends SecureResource { - static org.apache.log4j.Logger logger = Logger.getLogger(CachedSearchResource.class); + private static final Logger logger = LoggerFactory.getLogger(CachedSearchResource.class); String tableName=null; Integer offset=null; Integer rowsPerPage=null; String sortBy=null; String sortOrder="ASC"; - + public CachedSearchResource(Context context, Request request, Response response) { super(context, request, response); - tableName=(String)getParameter(request,"CACHED_SEARCH_ID"); - - if (this.getQueryVariable("offset")!=null){ - try { - offset=Integer.valueOf(this.getQueryVariable("offset")); - } catch (NumberFormatException e) { - response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); - return; - } - } - - if (this.getQueryVariable("limit")!=null){ - try { - rowsPerPage=Integer.valueOf(this.getQueryVariable("limit")); - } catch (NumberFormatException e) { - response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); - return; - } + tableName = (String) getParameter(request, "CACHED_SEARCH_ID"); + + final UserI user = getUser(); + + if (this.getQueryVariable("offset") != null) { + try { + offset = Integer.valueOf(this.getQueryVariable("offset")); + } catch (NumberFormatException e) { + response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); + return; } - - if (this.getQueryVariable("sortBy")!=null){ - sortBy=this.getQueryVariable("sortBy"); - if(PoolDBUtils.HackCheck(sortBy)){ - AdminUtils.sendAdminEmail(user,"Possible SQL Injection Attempt", "SORT BY:" + sortOrder); - response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); - return; - } - sortBy= StringUtils.replace(sortBy, " ", ""); + } + + if (this.getQueryVariable("limit") != null) { + try { + rowsPerPage = Integer.valueOf(this.getQueryVariable("limit")); + } catch (NumberFormatException e) { + response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); + return; } - - if (this.getQueryVariable("sortOrder")!=null){ - sortOrder=this.getQueryVariable("sortOrder"); - if(PoolDBUtils.HackCheck(sortOrder)){ - AdminUtils.sendAdminEmail(user,"Possible SQL Injection Attempt", "SORT ORDER:" + sortOrder); - response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); - return; - } - sortOrder=StringUtils.replace(sortOrder, " ", ""); + } + + if (this.getQueryVariable("sortBy") != null) { + sortBy = this.getQueryVariable("sortBy"); + if (PoolDBUtils.HackCheck(sortBy)) { + AdminUtils.sendAdminEmail(user, "Possible SQL Injection Attempt", "SORT BY:" + sortOrder); + response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); + return; } - - this.getVariants().add(new Variant(MediaType.APPLICATION_JSON)); - this.getVariants().add(new Variant(MediaType.TEXT_HTML)); - this.getVariants().add(new Variant(MediaType.TEXT_XML)); - } + sortBy = StringUtils.replace(sortBy, " ", ""); + } + if (this.getQueryVariable("sortOrder") != null) { + sortOrder = this.getQueryVariable("sortOrder"); + if (PoolDBUtils.HackCheck(sortOrder)) { + AdminUtils.sendAdminEmail(user, "Possible SQL Injection Attempt", "SORT ORDER:" + sortOrder); + response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); + return; + } + sortOrder = StringUtils.replace(sortOrder, " ", ""); + } + this.getVariants().add(new Variant(MediaType.APPLICATION_JSON)); + this.getVariants().add(new Variant(MediaType.TEXT_HTML)); + this.getVariants().add(new Variant(MediaType.TEXT_XML)); + } @Override public Representation getRepresentation(Variant variant) { @@ -102,12 +102,12 @@ public class CachedSearchResource extends SecureResource { XFTTable table=null; try { - + final UserI user = getUser(); MaterializedViewI mv = MaterializedView.retrieveView(tableName, user); if(mv.getUser_name().equals(user.getLogin())){ MediaType mt = this.getRequestedMediaType(); if (mt!=null && (mt.equals(SecureResource.APPLICATION_XLIST))){ - DisplaySearch ds = mv.getDisplaySearch(this.user); + DisplaySearch ds = mv.getDisplaySearch(user); //table=(XFTTable)ds.execute(new RESTHTMLPresenter(TurbineUtils.GetRelativePath(ServletCall.getRequest(this.getRequest())),null),user.getLogin()); table=mv.getData((sortBy!=null)?sortBy + " " + sortOrder:null, offset, rowsPerPage); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/search/SavedSearchListResource.java b/src/main/java/org/nrg/xnat/restlet/resources/search/SavedSearchListResource.java index 91eeabe3a901e8dc5b1cb5ba8767732ebc1d7a3e..3d224a7f0bfd924264d1b9aee910292670934aba 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/search/SavedSearchListResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/search/SavedSearchListResource.java @@ -11,9 +11,9 @@ package org.nrg.xnat.restlet.resources.search; import com.google.common.collect.Lists; -import org.apache.log4j.Logger; import org.nrg.xft.XFTTable; import org.nrg.xft.exception.DBPoolException; +import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.resources.SecureResource; import org.restlet.Context; import org.restlet.data.MediaType; @@ -22,13 +22,15 @@ import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.resource.Representation; import org.restlet.resource.Variant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.sql.SQLException; import java.util.Hashtable; import java.util.List; public class SavedSearchListResource extends SecureResource { - static org.apache.log4j.Logger logger = Logger.getLogger(SavedSearchListResource.class); + private static final Logger logger = LoggerFactory.getLogger(SavedSearchListResource.class); public SavedSearchListResource(Context context, Request request, Response response) { super(context, request, response); @@ -38,6 +40,7 @@ public class SavedSearchListResource extends SecureResource { } public List<String> retrieveAllTags(){ + final UserI user = getUser(); try { return (List<String>)(XFTTable.Execute("SELECT tag from xdat_stored_search", user.getDBName(), user.getLogin()).convertColumnToArrayList("tag")); } catch (SQLException e) { @@ -54,6 +57,7 @@ public class SavedSearchListResource extends SecureResource { MediaType mt = overrideVariant(variant); XFTTable table=null; try { + final UserI user = getUser(); String query="SELECT DISTINCT xss.* FROM xdat_stored_search xss LEFT JOIN xdat_stored_search_allowed_user xssau ON xss.id=xssau.xdat_stored_search_id LEFT JOIN xdat_stored_search_groupid xssag ON xss.id=xssag.allowed_groups_groupid_xdat_sto_id LEFT JOIN xdat_user_groupid ON xssag.groupid=xdat_user_groupid.groupid WHERE (xss.secure=0 OR xssau.login='" + user.getLogin() +"' OR groups_groupid_xdat_user_xdat_user_id="+ user.getID() + ")"; String includeTagged = this.getQueryVariable("includeTag"); if(includeTagged!=null){ @@ -82,7 +86,7 @@ public class SavedSearchListResource extends SecureResource { return null; } - Hashtable<String,Object> params=new Hashtable<String,Object>(); + Hashtable<String,Object> params= new Hashtable<>(); params.put("title", "Stored Searches"); return this.representTable(table, mt, params); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/search/SavedSearchResource.java b/src/main/java/org/nrg/xnat/restlet/resources/search/SavedSearchResource.java index ceb1700c66a2a3537bb1f281fb60d0c4608aef67..02a95154a38e693e9a3d5b479c9c9deadcb38f4a 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/search/SavedSearchResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/search/SavedSearchResource.java @@ -32,6 +32,7 @@ import org.nrg.xft.exception.ElementNotFoundException; import org.nrg.xft.exception.XFTInitException; import org.nrg.xft.schema.Wrappers.XMLWrapper.SAXReader; import org.nrg.xft.search.ItemSearch; +import org.nrg.xft.security.UserI; import org.nrg.xft.utils.SaveItemHelper; import org.nrg.xnat.restlet.presentation.RESTHTMLPresenter; import org.nrg.xnat.restlet.representations.ItemXMLRepresentation; @@ -88,7 +89,8 @@ public class SavedSearchResource extends ItemResource { @Override public Representation represent(Variant variant) { - MediaType mt = overrideVariant(variant); + MediaType mt = overrideVariant(variant); + final UserI user = getUser(); if (xss == null && sID != null) { if (sID.startsWith("@")) { @@ -248,6 +250,7 @@ public class SavedSearchResource extends ItemResource { @Override public void handlePut() { try { + final UserI user = getUser(); Reader sax = this.getRequest().getEntity().getReader(); SAXReader reader = new SAXReader(user); @@ -365,6 +368,7 @@ public class SavedSearchResource extends ItemResource { @Override public void handleDelete() { if (sID != null) { + final UserI user = getUser(); try { XdatStoredSearch search = XdatStoredSearch.getXdatStoredSearchsById(sID, user, false); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/search/SearchElementListResource.java b/src/main/java/org/nrg/xnat/restlet/resources/search/SearchElementListResource.java index 46ed6fcef97b7a6beab22f86abb83114c1fdc80c..3071337217f43b164bfbb0abad321823ec66a4e7 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/search/SearchElementListResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/search/SearchElementListResource.java @@ -16,6 +16,7 @@ import java.util.Map; import org.nrg.xdat.security.ElementSecurity; import org.nrg.xdat.security.helpers.UserHelper; import org.nrg.xft.XFTTable; +import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.resources.SecureResource; import org.restlet.Context; import org.restlet.data.MediaType; @@ -64,8 +65,9 @@ public class SearchElementListResource extends SecureResource { } Map counts = null; - - if(this.getQueryVariable("readable")!=null){ + + final UserI user = getUser(); + if(this.getQueryVariable("readable") != null){ counts=UserHelper.getUserHelperService(user).getReadableCounts(); }else{ counts=UserHelper.getUserHelperService(user).getTotalCounts(); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/search/SearchFieldListResource.java b/src/main/java/org/nrg/xnat/restlet/resources/search/SearchFieldListResource.java index abc34721807be0576d33bb40e6844b46a41dd5b9..120635f6de3dccdea6d3dfc3302a3777cb396807 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/search/SearchFieldListResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/search/SearchFieldListResource.java @@ -32,6 +32,7 @@ import org.nrg.xft.exception.FieldNotFoundException; import org.nrg.xft.exception.InvalidValueException; import org.nrg.xft.exception.XFTInitException; import org.nrg.xft.schema.Wrappers.GenericWrapper.GenericWrapperElement; +import org.nrg.xft.security.UserI; import org.nrg.xft.utils.XftStringUtils; import org.nrg.xnat.restlet.resources.SecureResource; import org.restlet.Context; @@ -112,7 +113,7 @@ public class SearchFieldListResource extends SecureResource{ if (XFTTool.ValidateElementName(elementName)) { try { - XFTItem found=XFTItem.NewItem(elementName, user); + XFTItem found=XFTItem.NewItem(elementName, getUser()); SchemaElement se = SchemaElement.GetElement(elementName); if ((!this.isQueryVariableFalse("secure")) && se.hasField(se.getFullXMLName() + "/project") && se.hasField(se.getFullXMLName() + "/sharing/share/project")){ @@ -221,7 +222,9 @@ public class SearchFieldListResource extends SecureResource{ } try { - List<List> custom_fields=UserHelper.getUserHelperService(user).getQueryResultsAsArrayList("SELECT DISTINCT ON (name) dtp.xnat_projectdata_id AS project, fdgf.name, fdgf.datatype AS type FROM xnat_abstractprotocol dtp LEFT JOIN xnat_datatypeprotocol_fieldgroups dtp_fg ON dtp.xnat_abstractprotocol_id=dtp_fg.xnat_datatypeprotocol_xnat_abstractprotocol_id LEFT JOIN xnat_fielddefinitiongroup fdg ON dtp_fg.xnat_fielddefinitiongroup_xnat_fielddefinitiongroup_id=fdg.xnat_fielddefinitiongroup_id LEFT JOIN xnat_fielddefinitiongroup_field fdgf ON fdg.xnat_fielddefinitiongroup_id=fdgf.fields_field_xnat_fielddefiniti_xnat_fielddefinitiongroup_id WHERE dtp.data_type='" + en + "' AND fdgf.type='custom'"); + final UserI user = getUser(); + + List<List> custom_fields =UserHelper.getUserHelperService(user).getQueryResultsAsArrayList("SELECT DISTINCT ON (name) dtp.xnat_projectdata_id AS project, fdgf.name, fdgf.datatype AS type FROM xnat_abstractprotocol dtp LEFT JOIN xnat_datatypeprotocol_fieldgroups dtp_fg ON dtp.xnat_abstractprotocol_id=dtp_fg.xnat_datatypeprotocol_xnat_abstractprotocol_id LEFT JOIN xnat_fielddefinitiongroup fdg ON dtp_fg.xnat_fielddefinitiongroup_xnat_fielddefinitiongroup_id=fdg.xnat_fielddefinitiongroup_id LEFT JOIN xnat_fielddefinitiongroup_field fdgf ON fdg.xnat_fielddefinitiongroup_id=fdgf.fields_field_xnat_fielddefiniti_xnat_fielddefinitiongroup_id WHERE dtp.data_type='" + en + "' AND fdgf.type='custom'"); DisplayField pi=ed.getProjectIdentifierField(); diff --git a/src/main/java/org/nrg/xnat/restlet/resources/search/SearchResource.java b/src/main/java/org/nrg/xnat/restlet/resources/search/SearchResource.java index 722a41cc4a95d8ee308d6aa571dc837865db48b7..2e10e81a26213d8920f2aa0016cb6f56b558e321 100644 --- a/src/main/java/org/nrg/xnat/restlet/resources/search/SearchResource.java +++ b/src/main/java/org/nrg/xnat/restlet/resources/search/SearchResource.java @@ -90,6 +90,7 @@ public class SearchResource extends SecureResource { XFTItem item = null; Representation entity = getRequest().getEntity(); + final UserI user = getUser(); if (entity != null && entity.getMediaType() != null && entity.getMediaType().getName().equals(MediaType.MULTIPART_FORM_DATA.getName())) { try { @SuppressWarnings("deprecation") org.apache.commons.fileupload.DefaultFileItemFactory factory = new org.apache.commons.fileupload.DefaultFileItemFactory(); @@ -468,6 +469,7 @@ public class SearchResource extends SecureResource { boolean allowed = false; if (StringUtils.isNotBlank(search.getId())) { //need to check against unmodified stored search + final UserI user = getUser(); final org.nrg.xdat.om.XdatStoredSearch stored = XdatStoredSearch.getXdatStoredSearchsById(search.getId(), user, true); //if the user was added to the search diff --git a/src/main/java/org/nrg/xnat/restlet/services/AliasTokenRestlet.java b/src/main/java/org/nrg/xnat/restlet/services/AliasTokenRestlet.java index 93920f1a6f61334231c5ee31928d4aeb8d81f490..17206c71c0dfd8ba1d926ccf6160bb12ced27597 100644 --- a/src/main/java/org/nrg/xnat/restlet/services/AliasTokenRestlet.java +++ b/src/main/java/org/nrg/xnat/restlet/services/AliasTokenRestlet.java @@ -16,6 +16,7 @@ import org.nrg.xdat.XDAT; import org.nrg.xdat.entities.AliasToken; import org.nrg.xdat.security.helpers.Roles; import org.nrg.xdat.services.AliasTokenService; +import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.resources.SecureResource; import org.nrg.framework.services.SerializerService; import org.restlet.Context; @@ -59,6 +60,7 @@ public class AliasTokenRestlet extends SecureResource { @Override public Representation represent() throws ResourceException { if (OP_ISSUE.equals(_operation)) { + final UserI user = getUser(); if (!StringUtils.isBlank(_username) && !Roles.isSiteAdmin(user)) { throw new ResourceException(Status.CLIENT_ERROR_FORBIDDEN, "Only admins can create proxy tokens."); } diff --git a/src/main/java/org/nrg/xnat/restlet/services/ArchiveValidator.java b/src/main/java/org/nrg/xnat/restlet/services/ArchiveValidator.java index e8b5e2f7303258a50e88b5b3660bf970499f0bb1..b305c9912c7bf2ba849c9e4c0a253c53aa1df6e2 100644 --- a/src/main/java/org/nrg/xnat/restlet/services/ArchiveValidator.java +++ b/src/main/java/org/nrg/xnat/restlet/services/ArchiveValidator.java @@ -15,6 +15,7 @@ import org.nrg.action.ActionException; import org.nrg.action.ClientException; import org.nrg.xft.XFTTable; import org.nrg.xft.exception.InvalidPermissionException; +import org.nrg.xft.security.UserI; import org.nrg.xnat.archive.PrearcSessionValidator; import org.nrg.xnat.archive.PrearcSessionValidator.Notice; import org.nrg.xnat.helpers.PrearcImporterHelper; @@ -61,20 +62,20 @@ public class ArchiveValidator extends SecureResource { protected List<String> srcs = new ArrayList<String>(); @Override - public void handleParam(final String key,final Object value) throws ClientException { - if(value !=null){ - if(key.equals(PROJECT)){ - additionalValues.put("project",value); - }else if(key.equals(PrearcUtils.PREARC_TIMESTAMP)){ - timestamp=(String)value; - }else if(key.equals(PrearcUtils.PREARC_SESSION_FOLDER)){ - sessionFolder.add((String)value); - }else if(key.equals(DEST)){ - dest=(String)value; - }else if(key.equals(BatchPrearchiveActionsA.SRC)){ - srcs.add((String)value); - }else{ - additionalValues.put(key,value); + public void handleParam(final String key, final Object value) throws ClientException { + if (value != null) { + if (key.equals(PROJECT)) { + additionalValues.put("project", value); + } else if (key.equals(PrearcUtils.PREARC_TIMESTAMP)) { + timestamp = (String) value; + } else if (key.equals(PrearcUtils.PREARC_SESSION_FOLDER)) { + sessionFolder.add((String) value); + } else if (key.equals(DEST)) { + dest = (String) value; + } else if (key.equals(BatchPrearchiveActionsA.SRC)) { + srcs.add((String) value); + } else { + additionalValues.put(key, value); } } } @@ -91,13 +92,14 @@ public class ArchiveValidator extends SecureResource { @Override public void handlePost() { - //build fileWriters - try { + try { + final UserI user = getUser(); + loadQueryVariables(); loadBodyVariables(); - final List<PrearcSession> sessions=new ArrayList<PrearcSession>(); + final List<PrearcSession> sessions= new ArrayList<>(); project_id=PrearcImporterHelper.identifyProject(additionalValues); @@ -186,10 +188,7 @@ public class ArchiveValidator extends SecureResource { } getResponse().setEntity(representTable(t,overrideVariant(getPreferredVariant()),new Hashtable<String, Object>())); - - return; - - }else{ + }else{ throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Cannot validate multiple sessions in one request."); } } catch (ActionException e) { @@ -199,11 +198,9 @@ public class ArchiveValidator extends SecureResource { if(e.cause!=null && e.cause instanceof ActionException){ logger.error("",e.cause); this.getResponse().setStatus(((ActionException)e.cause).getStatus(), e.cause.getMessage()); - return; }else{ logger.error("",e); this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,e); - return; } } catch (ResourceException e) { logger.error("",e); @@ -214,7 +211,6 @@ public class ArchiveValidator extends SecureResource { } catch (Exception e) { logger.error("",e); this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,e); - return; } } } diff --git a/src/main/java/org/nrg/xnat/restlet/services/Archiver.java b/src/main/java/org/nrg/xnat/restlet/services/Archiver.java index c7948346acb4e1f5e46c4abd3f3fe041e93c3ffa..ef5300005a30ef2e8014da32210287210e8d3ccc 100644 --- a/src/main/java/org/nrg/xnat/restlet/services/Archiver.java +++ b/src/main/java/org/nrg/xnat/restlet/services/Archiver.java @@ -141,8 +141,9 @@ public class Archiver extends BatchPrearchiveActionsA { final List<PrearcSession> sessions=new ArrayList<PrearcSession>(); project_id=PrearcImporterHelper.identifyProject(additionalValues); - - if((project_id==null || timestamp==null || sessionFolder==null) && (srcs==null)){ + + final UserI user = getUser(); + if((project_id == null || timestamp == null || sessionFolder == null) && (srcs == null)){ this.getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND, "Unknown prearchive session."); return; }else if(srcs!=null){ @@ -160,7 +161,7 @@ public class Archiver extends BatchPrearchiveActionsA { } try { - sessions.add(new PrearcSession((URIManager.PrearchiveURI)data,additionalValues,user)); + sessions.add(new PrearcSession((URIManager.PrearchiveURI)data, additionalValues, user)); } catch (InvalidPermissionException e) { throw new ResourceException(Status.CLIENT_ERROR_FORBIDDEN, data.getUri()); } catch (Exception e) { @@ -183,7 +184,7 @@ public class Archiver extends BatchPrearchiveActionsA { }else{ for(final String s:sessionFolder){ try { - sessions.add(new PrearcSession(project_id, timestamp, s, additionalValues,user)); + sessions.add(new PrearcSession(project_id, timestamp, s, additionalValues, user)); } catch (InvalidPermissionException e) { throw new ResourceException(Status.CLIENT_ERROR_FORBIDDEN, String.format("/prearchive/projects/%s/%s/%s not found.",project_id, timestamp, s)); } catch (Exception e) { @@ -217,7 +218,7 @@ public class Archiver extends BatchPrearchiveActionsA { if(PrearcDatabase.setStatus(session.getFolderName(), session.getTimestamp(), session.getProject(), PrearcStatus.ARCHIVING)){ FinishImageUpload.setArchiveReason(session, false); - _return = "/data" +PrearcDatabase.archive(session, allowDataDeletion, overwrite,overwrite_files, user, listeners); + _return = "/data" +PrearcDatabase.archive(session, allowDataDeletion, overwrite, overwrite_files, user, listeners); }else{ this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN,"Operation already in progress on this prearchive entry."); return; @@ -243,7 +244,7 @@ public class Archiver extends BatchPrearchiveActionsA { ps.getAdditionalValues().put(EventUtils.EVENT_REASON, "Batch archive"); } - m=PrearcDatabase.archive(sessions, allowDataDeletion, overwrite,overwrite_files, user, listeners); + m=PrearcDatabase.archive(sessions, allowDataDeletion, overwrite, overwrite_files, user, listeners); getResponse().setEntity(updatedStatusRepresentation(m.keySet(),overrideVariant(getPreferredVariant()))); diff --git a/src/main/java/org/nrg/xnat/restlet/services/AuditRestlet.java b/src/main/java/org/nrg/xnat/restlet/services/AuditRestlet.java index 1c3619ed761d1fd27d200041b623cf2e0a751703..9fba1c1ecb601895b20b039a23fb84bc9713ccdd 100644 --- a/src/main/java/org/nrg/xnat/restlet/services/AuditRestlet.java +++ b/src/main/java/org/nrg/xnat/restlet/services/AuditRestlet.java @@ -67,7 +67,7 @@ public class AuditRestlet extends SecureResource { cc.addClause(xsiType+"/"+pks.get(i), ids.get(i)); } - return ItemSearch.GetItems(xsiType, cc, this.user, false).getFirst(); + return ItemSearch.GetItems(xsiType, cc, getUser(), false).getFirst(); } public ItemI retrieveItemByIds(final String xsiType, List<String> ids) throws ActionException{ @@ -88,7 +88,7 @@ public class AuditRestlet extends SecureResource { } if(i!=null){ - Authorizer.getInstance().authorizeRead(i.getItem(), user); + Authorizer.getInstance().authorizeRead(i.getItem(), getUser()); } return i; @@ -133,7 +133,7 @@ public class AuditRestlet extends SecureResource { params.put("hideTopBar",isQueryVariableTrue("hideTopBar")); - return new ItemHTMLRepresentation(item.getItem(), MediaType.TEXT_HTML, getRequest(), user,screen,params); + return new ItemHTMLRepresentation(item.getItem(), MediaType.TEXT_HTML, getRequest(), getUser(),screen,params); }else{ return buildChangesets(item.getItem(), key, mt); } diff --git a/src/main/java/org/nrg/xnat/restlet/services/FeatureDefinitionRestlet.java b/src/main/java/org/nrg/xnat/restlet/services/FeatureDefinitionRestlet.java index 21aa94687256275359691772274137e1fe72e545..fd9c5ba6ad54b49843860b3e08bf2f5c67a111da 100644 --- a/src/main/java/org/nrg/xnat/restlet/services/FeatureDefinitionRestlet.java +++ b/src/main/java/org/nrg/xnat/restlet/services/FeatureDefinitionRestlet.java @@ -1,11 +1,6 @@ package org.nrg.xnat.restlet.services; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; -import java.util.Hashtable; -import java.util.List; - +import com.google.common.collect.Lists; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; @@ -14,20 +9,16 @@ import org.json.JSONException; import org.json.JSONObject; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.security.UserGroupI; -import org.nrg.xdat.security.UserGroupI; import org.nrg.xdat.security.helpers.FeatureDefinitionI; import org.nrg.xdat.security.helpers.Features; import org.nrg.xdat.security.helpers.Groups; import org.nrg.xdat.security.helpers.Roles; import org.nrg.xdat.security.services.RoleRepositoryServiceI.RoleDefinitionI; import org.nrg.xft.XFTTable; +import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.resources.SecureResource; import org.restlet.Context; -import org.restlet.data.MediaType; -import org.restlet.data.Method; -import org.restlet.data.Request; -import org.restlet.data.Response; -import org.restlet.data.Status; +import org.restlet.data.*; import org.restlet.resource.Representation; import org.restlet.resource.ResourceException; import org.restlet.resource.StringRepresentation; @@ -35,7 +26,11 @@ import org.restlet.resource.Variant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.collect.Lists; +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.Hashtable; +import java.util.List; public class FeatureDefinitionRestlet extends SecureResource { public FeatureDefinitionRestlet(Context context, Request request, Response response) { @@ -68,10 +63,11 @@ public class FeatureDefinitionRestlet extends SecureResource { Collection<String> siteWideEnabled=Features.getEnabledFeatures(); Collection<String> siteWideBanned=Features.getBannedFeatures(); - - - JSONArray projects = new JSONArray(); - for(String tag:tags){ + + + final UserI user = getUser(); + final JSONArray projects = new JSONArray(); + for(String tag:tags){ XnatProjectdata proj=XnatProjectdata.getProjectByIDorAlias(tag, user, false); try { @@ -190,7 +186,8 @@ public class FeatureDefinitionRestlet extends SecureResource { } String key = json.getString("key"); - + + final UserI user = getUser(); if(getQueryVariable("type")==null && getQueryVariable("group")==null){ if (!Roles.isSiteAdmin(user)) { diff --git a/src/main/java/org/nrg/xnat/restlet/services/Importer.java b/src/main/java/org/nrg/xnat/restlet/services/Importer.java index db5d926bcc3586ad1413cc76b5f6f926e389edff..493dcdab67d9f185bbc4dc5dc265b1abc62dfa1f 100644 --- a/src/main/java/org/nrg/xnat/restlet/services/Importer.java +++ b/src/main/java/org/nrg/xnat/restlet/services/Importer.java @@ -20,6 +20,7 @@ import org.nrg.status.StatusList; import org.nrg.xdat.XDAT; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.turbine.utils.TurbineUtils; +import org.nrg.xft.security.UserI; import org.nrg.xnat.helpers.file.StoredFile; import org.nrg.xnat.helpers.prearchive.PrearcUtils; import org.nrg.xnat.helpers.transactions.HTTPSessionStatusManagerQueue; @@ -140,6 +141,7 @@ public class Importer extends SecureResource { @Override public void handlePost() { //build fileWriters + final UserI user = getUser(); try { final Request request = getRequest(); if (logger.isDebugEnabled()) { @@ -481,7 +483,7 @@ public class Importer extends SecureResource { throw new ClientException(Status.CLIENT_ERROR_BAD_REQUEST,"src uri is invalid.",new Exception()); } - File f=org.nrg.xdat.security.helpers.Users.getUserCacheFile(user, (String)map.get("XNAME"), (String)map.get("FILE")); + File f=org.nrg.xdat.security.helpers.Users.getUserCacheFile(getUser(), (String)map.get("XNAME"), (String)map.get("FILE")); if(f.exists()){ return new StoredFile(f,true); @@ -490,7 +492,7 @@ public class Importer extends SecureResource { } } - public String convertListToString(final List<String> response, boolean wrapPartialDataURI){ + private String convertListToString(final List<String> response, boolean wrapPartialDataURI){ final StringBuffer sb = new StringBuffer(); for(final String s:response){ sb.append((wrapPartialDataURI) ? wrapPartialDataURI(s) : s).append(CRLF); diff --git a/src/main/java/org/nrg/xnat/restlet/services/MoveFiles.java b/src/main/java/org/nrg/xnat/restlet/services/MoveFiles.java index 8f65fd6dca2b8fb3f8bf82e611f11c72a6a317ba..550dd026b6094f4774576654e5645d5833ff3574 100644 --- a/src/main/java/org/nrg/xnat/restlet/services/MoveFiles.java +++ b/src/main/java/org/nrg/xnat/restlet/services/MoveFiles.java @@ -20,6 +20,7 @@ import org.nrg.xft.event.EventMetaI; import org.nrg.xft.event.EventUtils; import org.nrg.xft.event.persist.PersistentWorkflowI; import org.nrg.xft.event.persist.PersistentWorkflowUtils; +import org.nrg.xft.security.UserI; import org.nrg.xnat.helpers.move.FileMover; import org.nrg.xnat.helpers.uri.URIManager; import org.nrg.xnat.helpers.uri.UriParserUtils; @@ -139,16 +140,17 @@ public class MoveFiles extends SecureResource { } - EventMetaI ci; - PersistentWorkflowI work=PersistentWorkflowUtils.getWorkflowByEventId(user, getEventId()); + EventMetaI ci; + final UserI user = getUser(); + PersistentWorkflowI work =PersistentWorkflowUtils.getWorkflowByEventId(user, getEventId()); if(work!=null){ ci=work.buildEvent(); }else{ - ci = EventUtils.DEFAULT_EVENT(user,null); + ci = EventUtils.DEFAULT_EVENT(user, null); } //this should allow injection of a different implementation- TO - final FileMover mover =new FileMover(overwrite,user,otherParams); + final FileMover mover =new FileMover(overwrite, user, otherParams); for(Map.Entry<URIManager.UserCacheURI,ResourceURII> entry: moves.entrySet()){ mover.call(entry.getKey(),entry.getValue(),ci); diff --git a/src/main/java/org/nrg/xnat/restlet/services/RefreshCatalog.java b/src/main/java/org/nrg/xnat/restlet/services/RefreshCatalog.java index 7fdab7b3206367bd4cb083c1e81d79e16d3f7f83..9fcfc791ef415e9989772e0daf4152b37c4d8f86 100644 --- a/src/main/java/org/nrg/xnat/restlet/services/RefreshCatalog.java +++ b/src/main/java/org/nrg/xnat/restlet/services/RefreshCatalog.java @@ -5,12 +5,6 @@ * All Rights Reserved * * Released under the Simplified BSD. - * - * Last modified 7/30/13 2:58 PM - */ - -/** - * */ package org.nrg.xnat.restlet.services; @@ -115,7 +109,7 @@ public class RefreshCatalog extends SecureResource { ArchivableItem existenceCheck = resourceURI.getSecurityItem(); if (existenceCheck != null) { //call refresh operation - ResourceUtils.refreshResourceCatalog(resourceURI, user, this.newEventInstance(EventUtils.CATEGORY.DATA, "Catalog(s) Refreshed"), populateStats, checksum, delete, append); + ResourceUtils.refreshResourceCatalog(resourceURI, getUser(), this.newEventInstance(EventUtils.CATEGORY.DATA, "Catalog(s) Refreshed"), populateStats, checksum, delete, append); } } 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 b12052286a58b969040e19215d509db46e711b05..87c81c918e0cb2b69c210af43ae09d8a4d3c63ea 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 @@ -10,8 +10,8 @@ */ package org.nrg.xnat.restlet.services.mail; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nrg.action.ClientException; @@ -20,7 +20,6 @@ import org.nrg.xdat.XDAT; import org.nrg.xdat.security.helpers.Users; import org.nrg.xdat.security.user.exceptions.UserInitException; import org.nrg.xdat.security.user.exceptions.UserNotFoundException; -import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xft.security.UserI; import org.nrg.xnat.restlet.resources.SecureResource; import org.nrg.xnat.restlet.util.FileWriterWrapperI; @@ -40,12 +39,12 @@ import java.util.List; import java.util.Map; public class MailRestlet extends SecureResource { - public static final String PARAM_BCC = "bcc"; - public static final String PARAM_CC = "cc"; - public static final String PARAM_TO = "to"; - public static final String PARAM_HTML = "html"; - public static final String PARAM_SUBJECT = "subject"; - public static final String PARAM_TEXT = "text"; + private static final String PARAM_BCC = "bcc"; + private static final String PARAM_CC = "cc"; + private static final String PARAM_TO = "to"; + private static final String PARAM_HTML = "html"; + private static final String PARAM_SUBJECT = "subject"; + private static final String PARAM_TEXT = "text"; public MailRestlet(Context context, Request request, Response response) { super(context, request, response); @@ -79,7 +78,7 @@ public class MailRestlet extends SecureResource { // 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(XDAT.getSiteConfigPreferences().getAdminEmail()); - message.setOnBehalfOf(user.getEmail()); + message.setOnBehalfOf(getUser().getEmail()); // Handle all the addresses. String[] tos = getAddresses(PARAM_TO); @@ -196,7 +195,7 @@ public class MailRestlet extends SecureResource { } catch (NumberFormatException | UserNotFoundException exception) { // If not an integer, we'll try it as an email address. It has to match an existing email address in the system! List<UserI> users = Users.getUsersByEmail(id); - if (users.size() == 0) { + if (users == null || users.size() == 0) { addIssue(String.format("The user email %s was not found in the system and was not included on the email.", id)); } else { addresses.add(id); diff --git a/src/main/java/org/nrg/xnat/restlet/services/prearchive/PrearchiveBatchDelete.java b/src/main/java/org/nrg/xnat/restlet/services/prearchive/PrearchiveBatchDelete.java index 9fad708a03753905451aa5accb3539cb121e5870..f3df5e2372f616c5cef5a9c0275743d6abbcdf31 100644 --- a/src/main/java/org/nrg/xnat/restlet/services/prearchive/PrearchiveBatchDelete.java +++ b/src/main/java/org/nrg/xnat/restlet/services/prearchive/PrearchiveBatchDelete.java @@ -1,22 +1,17 @@ /* * org.nrg.xnat.restlet.services.prearchive.PrearchiveBatchDelete * XNAT http://www.xnat.org - * Copyright (c) 2014, Washington University School of Medicine + * Copyright (c) 2016, Washington University School of Medicine * All Rights Reserved * * Released under the Simplified BSD. - * - * Last modified 12/19/13 3:01 PM */ -/** - * - */ package org.nrg.xnat.restlet.services.prearchive; -import org.apache.log4j.Logger; import org.nrg.action.ClientException; import org.nrg.xdat.XDAT; +import org.nrg.xft.security.UserI; import org.nrg.xnat.helpers.prearchive.PrearcDatabase; import org.nrg.xnat.helpers.prearchive.PrearcUtils; import org.nrg.xnat.helpers.prearchive.SessionData; @@ -26,6 +21,8 @@ import org.restlet.Context; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Status; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; @@ -36,7 +33,7 @@ import java.util.List; * */ public class PrearchiveBatchDelete extends BatchPrearchiveActionsA { - static org.apache.log4j.Logger logger = Logger.getLogger(PrearchiveBatchDelete.class); + private static final Logger logger = LoggerFactory.getLogger(PrearchiveBatchDelete.class); public PrearchiveBatchDelete(Context context, Request request, Response response) { super(context, request, response); @@ -55,12 +52,13 @@ public class PrearchiveBatchDelete extends BatchPrearchiveActionsA { return; } - List<SessionDataTriple> ss=new ArrayList<SessionDataTriple>(); + List<SessionDataTriple> ss= new ArrayList<>(); for(final String src:srcs){ File sessionDir; try { SessionDataTriple s=buildSessionDataTriple(src); + final UserI user = getUser(); if (!PrearcUtils.canModify(user, s.getProject())) { this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN,"Invalid permissions for new project."); return; @@ -83,8 +81,7 @@ public class PrearchiveBatchDelete extends BatchPrearchiveActionsA { response.setEntity(updatedStatusRepresentation(ss,overrideVariant(getPreferredVariant()))); } catch (Exception e) { logger.error("",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,e); - return; + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,e); } } } diff --git a/src/main/java/org/nrg/xnat/restlet/services/prearchive/PrearchiveBatchMove.java b/src/main/java/org/nrg/xnat/restlet/services/prearchive/PrearchiveBatchMove.java index 0e5552d6fb59952eddd80be18896b640fbb715db..778a9f12baeaeabb8dbae701a1a018f7f28e03cb 100644 --- a/src/main/java/org/nrg/xnat/restlet/services/prearchive/PrearchiveBatchMove.java +++ b/src/main/java/org/nrg/xnat/restlet/services/prearchive/PrearchiveBatchMove.java @@ -8,14 +8,11 @@ * * Last modified 12/19/13 3:01 PM */ - -/** - * - */ package org.nrg.xnat.restlet.services.prearchive; import org.nrg.action.ClientException; import org.nrg.xdat.XDAT; +import org.nrg.xft.security.UserI; import org.nrg.xnat.helpers.prearchive.PrearcDatabase; import org.nrg.xnat.helpers.prearchive.PrearcUtils; import org.nrg.xnat.helpers.prearchive.SessionData; @@ -82,6 +79,7 @@ public class PrearchiveBatchMove extends BatchPrearchiveActionsA { return; } + final UserI user = getUser(); if (newProject == null) { getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Move operation requires 'newProject'"); return; diff --git a/src/main/java/org/nrg/xnat/restlet/services/prearchive/PrearchiveBatchRebuild.java b/src/main/java/org/nrg/xnat/restlet/services/prearchive/PrearchiveBatchRebuild.java index f30c8c114f914ffa0b0a2c4a79308f9bfb44a392..0839f478d81485c50e14678b7b444b6a5b6f9211 100644 --- a/src/main/java/org/nrg/xnat/restlet/services/prearchive/PrearchiveBatchRebuild.java +++ b/src/main/java/org/nrg/xnat/restlet/services/prearchive/PrearchiveBatchRebuild.java @@ -9,14 +9,12 @@ * Last modified 7/10/13 9:04 PM */ -/** - * - */ package org.nrg.xnat.restlet.services.prearchive; import org.apache.log4j.Logger; import org.nrg.action.ClientException; import org.nrg.xdat.XDAT; +import org.nrg.xft.security.UserI; import org.nrg.xnat.helpers.prearchive.PrearcDatabase; import org.nrg.xnat.helpers.prearchive.PrearcUtils; import org.nrg.xnat.helpers.prearchive.SessionData; @@ -56,14 +54,15 @@ public class PrearchiveBatchRebuild extends BatchPrearchiveActionsA { for(final String src:srcs){ File sessionDir; try { - SessionDataTriple s=buildSessionDataTriple(src); - ss.add(s); - sessionDir = PrearcUtils.getPrearcSessionDir(user, s.getProject(), s.getTimestamp(), s.getFolderName(), false); + final UserI user = getUser(); + final SessionDataTriple triple = buildSessionDataTriple(src); + ss.add(triple); + sessionDir = PrearcUtils.getPrearcSessionDir(user, triple.getProject(), triple.getTimestamp(), triple.getFolderName(), false); final boolean overrideLock = hasQueryVariable("overrideLock") && Boolean.parseBoolean(getQueryVariable("overrideLock")); - if (PrearcDatabase.setStatus(s.getFolderName(), s.getTimestamp(), s.getProject(), PrearcUtils.PrearcStatus.QUEUED_BUILDING, overrideLock)) { - SessionData sessionData = PrearcDatabase.getSession(s.getFolderName(), s.getTimestamp(), s.getProject()); + if (PrearcDatabase.setStatus(triple.getFolderName(), triple.getTimestamp(), triple.getProject(), PrearcUtils.PrearcStatus.QUEUED_BUILDING, overrideLock)) { + SessionData sessionData = PrearcDatabase.getSession(triple.getFolderName(), triple.getTimestamp(), triple.getProject()); PrearchiveOperationRequest request = new PrearchiveOperationRequest(user, sessionData, sessionDir, "Rebuild"); XDAT.sendJmsRequest(request); } diff --git a/src/main/java/org/nrg/xnat/security/XnatBasicAuthenticationFilter.java b/src/main/java/org/nrg/xnat/security/XnatBasicAuthenticationFilter.java index 49340a9e7471ef311fadb178ebe4dcec96648f4c..8b4a57eebbe992cf7fe15bf5268bae3a806342c5 100644 --- a/src/main/java/org/nrg/xnat/security/XnatBasicAuthenticationFilter.java +++ b/src/main/java/org/nrg/xnat/security/XnatBasicAuthenticationFilter.java @@ -111,14 +111,11 @@ public class XnatBasicAuthenticationFilter extends BasicAuthenticationFilter { UsernamePasswordAuthenticationToken authRequest = _providerManager.buildUPTokenForAuthMethod(_providerManager.retrieveAuthMethod(username), username, password); authRequest.setDetails(_authenticationDetailsSource.buildDetails(request)); - Authentication authResult; + final Authentication authResult; try { authResult = getAuthenticationManager().authenticate(authRequest); - _authenticationStrategy.onAuthentication(authResult, request, response); - - } catch (AuthenticationException failed) { // Authentication failed if (debug) { diff --git a/src/main/java/org/nrg/xnat/security/XnatExpiredPasswordFilter.java b/src/main/java/org/nrg/xnat/security/XnatExpiredPasswordFilter.java index 3db8387c66b81d8981b5a66a267c6f707b1e93d6..2387ccc0dcc2d67d554aa7e614e6789e0caae3cd 100644 --- a/src/main/java/org/nrg/xnat/security/XnatExpiredPasswordFilter.java +++ b/src/main/java/org/nrg/xnat/security/XnatExpiredPasswordFilter.java @@ -91,7 +91,7 @@ public class XnatExpiredPasswordFilter extends GenericFilterBean { //If the arc spec has not yet been set, have the user configure the arc spec before changing their password. This prevents a negative interaction with the arc spec filter. chain.doFilter(request, response); } else { - if (user == null) { + if (user == null || user.isGuest()) { //If the user is not logged in, do not send them to the expired password page. String header = request.getHeader("Authorization"); diff --git a/src/main/java/org/nrg/xnat/security/XnatInitCheckFilter.java b/src/main/java/org/nrg/xnat/security/XnatInitCheckFilter.java index 8bc71dca80b2a2d09e5efa09a1de514e967a4de8..d485f0f5d70daaafd53b01df64e999bcae73193a 100644 --- a/src/main/java/org/nrg/xnat/security/XnatInitCheckFilter.java +++ b/src/main/java/org/nrg/xnat/security/XnatInitCheckFilter.java @@ -48,11 +48,12 @@ public class XnatInitCheckFilter extends GenericFilterBean { chain.doFilter(req, res); } else { // We're going to use the user for logging. - final UserI user = XDAT.getUserDetails(); + final UserI user = XDAT.getUserDetails(); + final boolean isAnonymous = user == null || user.isGuest(); final String uri = request.getRequestURI(); - if (user == null) { + if (isAnonymous) { String header = request.getHeader("Authorization"); if (header != null && header.startsWith("Basic ") && !isInitializerPath(uri)) { // Users that authenticated using basic authentication receive an error message informing @@ -75,7 +76,7 @@ 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 { - if (user == null) { + if (isAnonymous) { // 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). diff --git a/src/main/java/org/nrg/xnat/services/XnatAppInfo.java b/src/main/java/org/nrg/xnat/services/XnatAppInfo.java index edd493666fec68e05c5bf677d65e17cd06617556..6de0ba19878b0695717da20eac86121ce83d957f 100644 --- a/src/main/java/org/nrg/xnat/services/XnatAppInfo.java +++ b/src/main/java/org/nrg/xnat/services/XnatAppInfo.java @@ -1,5 +1,6 @@ package org.nrg.xnat.services; + import org.nrg.prefs.exceptions.InvalidPreferenceName; import org.nrg.xdat.XDAT; import org.slf4j.Logger; @@ -7,6 +8,12 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.EmptyResultDataAccessException; + +import org.nrg.framework.utilities.BasicXnatResourceLocator; +import org.python.google.common.collect.ImmutableMap; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PropertiesLoaderUtils; + import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Component; @@ -104,7 +111,14 @@ public class XnatAppInfo { if (_foundPreferences.size() == 0) { return null; } - return new HashMap<>(_foundPreferences); + + //return new HashMap<>(_foundPreferences); + + for (final Resource resource : BasicXnatResourceLocator.getResources("classpath*:META-INF/xnat/**/*-plugin.properties")) { + final Properties properties = PropertiesLoaderUtils.loadProperties(resource); + _plugins.put(properties.getProperty("name"), properties); + } + _template = template; } /** @@ -277,6 +291,15 @@ public class XnatAppInfo { return buffer.toString(); } + /** + * Returns the properties for all of the installed and active plugins in the deployed XNAT server. + * + * @return A map of all of the plugins installed on the server. + */ + public Map<String, Properties> getPluginProperties() throws IOException { + return ImmutableMap.copyOf(_plugins); + } + private static final Logger _log = LoggerFactory.getLogger(XnatAppInfo.class); private static final List<String> PRIMARY_MANIFEST_ATTRIBUTES = Arrays.asList("Build-Number", "Build-Date", "Implementation-Version", "Implementation-Sha"); @@ -289,5 +312,6 @@ public class XnatAppInfo { private final Properties _properties = new Properties(); private final Map<String, Map<String, String>> _attributes = new HashMap<>(); private boolean _initialized = false; + private final Map<String, Properties> _plugins = new HashMap<>(); } 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 73d77bda5d7ff9af0b43c80246ef770a9911a9d1..b4847ca0c4f76128d17c77eafc96bbb879c0d5de 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 @@ -10,10 +10,6 @@ */ package org.nrg.xnat.turbine.modules.actions; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Map; - import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.apache.turbine.util.RunData; @@ -30,7 +26,6 @@ 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.modules.actions.SecureAction; -import org.nrg.xdat.turbine.utils.AdminUtils; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.event.EventMetaI; import org.nrg.xft.event.EventUtils; @@ -41,6 +36,10 @@ import org.nrg.xft.security.UserI; import org.nrg.xnat.turbine.utils.ProjectAccessRequest; import org.nrg.xnat.utils.WorkflowUtils; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Map; + public class ProcessAccessRequest extends SecureAction { static Logger logger = Logger.getLogger(ProcessAccessRequest.class); @@ -110,7 +109,7 @@ public class ProcessAccessRequest extends SecureAction { //data.setScreenTemplate("XDATScreen_manage_xnat_projectData.vm"); //data.setScreenTemplate("/xnat_projectData/xnat_projectData_summary_management.vm"); TurbineUtils.SetSearchProperties(data, project); - data.getParameters().setString("topTab", "Access"); + //data.getParameters().setString("topTab", "Access"); this.redirectToReportScreen("XDATScreen_report_xnat_projectData.vm", project, data); } @@ -153,7 +152,7 @@ public class ProcessAccessRequest extends SecureAction { try { for (Map.Entry<String, UserGroupI> entry:Groups.getGroupsForUser(user).entrySet()){ - if (entry.getValue().getTag().equals(project.getId())){ + if (entry.getValue()!=null && entry.getValue().getTag()!=null && entry.getValue().getTag().equals(project.getId())){ Groups.removeUserFromGroup(other, entry.getValue().getId(), c); } } @@ -183,7 +182,7 @@ public class ProcessAccessRequest extends SecureAction { //data.setScreenTemplate("XDATScreen_manage_xnat_projectData.vm"); //data.setScreenTemplate("/xnat_projectData/xnat_projectData_summary_management.vm"); TurbineUtils.SetSearchProperties(data, project); - data.getParameters().setString("topTab", "Access"); + //data.getParameters().setString("topTab", "Access"); this.redirectToReportScreen("XDATScreen_report_xnat_projectData.vm", project, data); } diff --git a/src/main/java/org/nrg/xnat/turbine/modules/screens/BulkDeleteActionScreen.java b/src/main/java/org/nrg/xnat/turbine/modules/screens/BulkDeleteActionScreen.java index 1631eda0455fb08185369a383949e30507baa209..657ad4ad4a57d55cf335715d87b5a95b31844fb5 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/screens/BulkDeleteActionScreen.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/screens/BulkDeleteActionScreen.java @@ -10,10 +10,6 @@ */ package org.nrg.xnat.turbine.modules.screens; -import java.util.ArrayList; -import java.util.Date; -import java.util.Hashtable; - import org.apache.turbine.util.RunData; import org.apache.velocity.context.Context; import org.nrg.xdat.search.DisplaySearch; @@ -23,6 +19,10 @@ import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.XFTTable; import org.nrg.xft.security.UserI; +import java.util.ArrayList; +import java.util.Date; +import java.util.Hashtable; + public class BulkDeleteActionScreen extends SecureScreen { // Enumeration to determine what type of item is stored in an ItemContainer object. @@ -81,6 +81,7 @@ public class BulkDeleteActionScreen extends SecureScreen { }else{ context.put("errMsg", "There is nothing to delete."); } + context.put("turbineUtils", TurbineUtils.GetInstance()); } /** @@ -225,7 +226,7 @@ public class BulkDeleteActionScreen extends SecureScreen { public String canDelete(UserI u, String searchType){ try{ // Is the user allowed to delete this item - boolean canDelete = Permissions.canAny(u,this.xsi + "/project", this.project, "delete"); + boolean canDelete = Permissions.canAny(u,this.xsi, this.project, "delete"); // The search type determines which items a user is allowed to delete. if(searchType.equals("subject")){ diff --git a/src/main/java/org/nrg/xnat/turbine/modules/screens/PublicProjectView.java b/src/main/java/org/nrg/xnat/turbine/modules/screens/PublicProjectView.java index ea63bfe240a917111acdc82f8442b961ccc81917..540372e0219db3db8e17ca2e377e0323384c4e3a 100644 --- a/src/main/java/org/nrg/xnat/turbine/modules/screens/PublicProjectView.java +++ b/src/main/java/org/nrg/xnat/turbine/modules/screens/PublicProjectView.java @@ -10,42 +10,39 @@ */ package org.nrg.xnat.turbine.modules.screens; -import java.util.ArrayList; - import org.apache.turbine.modules.screens.VelocityScreen; import org.apache.turbine.util.RunData; import org.apache.velocity.context.Context; +import org.nrg.xdat.XDAT; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.security.SecurityManager; import org.nrg.xdat.security.helpers.Permissions; -import org.nrg.xdat.security.helpers.Users; -import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.security.UserI; -public class PublicProjectView extends VelocityScreen { +import java.util.ArrayList; +import java.util.List; - /* (non-Javadoc) - * @see org.apache.turbine.modules.screens.VelocityScreen#doBuildTemplate(org.apache.turbine.util.RunData, org.apache.velocity.context.Context) +@SuppressWarnings("unused") +public class PublicProjectView extends VelocityScreen { + /** + * {@inheritDoc} */ @Override protected void doBuildTemplate(RunData data, Context context) throws Exception { - UserI user = TurbineUtils.getUser(data); - - if (user==null){ - user=Users.getGuest(); - TurbineUtils.setUser(data, user); - } - ArrayList allProjects = new ArrayList(); - - for(XnatProjectdata p :XnatProjectdata.getAllXnatProjectdatas(user, false)){ - if (Permissions.can(user,p.getItem(), SecurityManager.ACTIVATE)){ + UserI user = XDAT.getUserDetails(); + + if (user == null) { + XDAT.setGuestUserDetails(); + } + + final List<XnatProjectdata> allProjects = new ArrayList<>(); + + for (XnatProjectdata p : XnatProjectdata.getAllXnatProjectdatas(user, false)) { + if (Permissions.can(user, p.getItem(), SecurityManager.ACTIVATE)) { allProjects.add(p); } } - + context.put("projects", allProjects); - } - - } 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 758bf687598bcbf2a9b0c0fc726a5f0d2a96d20a..e36656dd3350f8e94f17d1e088993ea79cdc279a 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 @@ -49,13 +49,9 @@ public class XDATScreen_UpdateUser extends SecureScreen { c.put("displayManager", DisplayManager.GetInstance()); c.put("systemName", TurbineUtils.GetSystemName()); c.put("esc", new EscapeTool()); - c.put("showReason", XDAT.getSiteConfigPreferences().getShowChangeJustification()); c.put("requireReason", XDAT.getSiteConfigPreferences().getRequireChangeJustification()); - c.put("siteConfig", XDAT.getSiteConfigPreferences()); - - doBuildTemplate(data, c); } diff --git a/src/main/resources/META-INF/xnat/security/configured-urls.yaml b/src/main/resources/META-INF/xnat/security/configured-urls.yaml index b968bd4b3b05964b88e7aaa0a12b41bb34f49786..f86e9aa027318ae3019d35b5443d56cd1dda967f 100644 --- a/src/main/resources/META-INF/xnat/security/configured-urls.yaml +++ b/src/main/resources/META-INF/xnat/security/configured-urls.yaml @@ -22,6 +22,7 @@ openUrls: - /REST/services/auth* - /data/services/sendemailverification* - /REST/services/sendemailverification* + - /xapi/siteConfig/buildInfo - /images/** - /scripts/** - /style/** 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 c1d5acb1f2277b5dcb42df02dc1ed8a4b23ffd50..aa8e83ea147d18e1cc7c479e0cf970724c983631 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 @@ -12,7 +12,6 @@ tabGroups: siteId: kind: panel.input.text - id: siteId name: siteId label: Site ID validation: required id onblur @@ -26,24 +25,20 @@ siteDescriptionPage: tag: input element: type: text - id: siteDescriptionPage name: siteDescriptionPage size: 30 after: "<p class='description'>Specify a velocity template file to display on the login page</p>" siteDescriptionText: - tag: textarea + tag: textarea|data-code-editor;data-code-language=html element: - id: siteDescriptionText name: siteDescriptionText rows: 8 after: "<p class='description'>Specify a simple text description of this site.</p>" passwordExpirationInterval: tag: input - before: - label: - tag: br + before: '<br>' element: type: text id: passwordExpirationInterval @@ -54,9 +49,7 @@ passwordExpirationInterval: passwordExpirationDate: tag: input - before: - label: - tag: br + before: '<br>' element: type: text id: passwordExpirationDate @@ -68,6 +61,8 @@ siteDescriptionType: #id: siteDescriptionType #name: siteDescriptionType label: Site Description + info: > + <p>The site description will show up on the login page and can be utilized to describe the purpose of this site, or notify users of important application status messages (ie. "The system is down for maintenance").</p><p>Administrators can opt to display a simple text message, or specify a velocity template reference containing the content to be displayed.</p> contents: info: tag: p @@ -79,7 +74,6 @@ siteDescriptionType: element: type: radio name: siteDescriptionType - id: siteDescriptionTypePage value: Page after: label: @@ -90,7 +84,6 @@ siteDescriptionType: element: type: radio name: siteDescriptionType - id: siteDescriptionTypeText value: Text after: label: @@ -111,33 +104,28 @@ siteDescriptionType: siteLoginLanding: kind: panel.input.text - id: siteLoginLanding name: siteLoginLanding label: Site Login Landing description: "The page users will land on immediately after logging in." 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 description: "The page users will land on by clicking the XNAT logo in the menu bar." siteHomeLayout: kind: panel.input.text - id: siteHomeLayout name: siteHomeLayout label: Site Home Layout siteUrl: kind: panel.input.text - id: siteUrl name: siteUrl label: Site Url validation: required url @@ -149,7 +137,6 @@ siteUrl: adminEmail: kind: panel.input.email - id: adminEmail name: adminEmail label: Site Admin Email description: > @@ -168,7 +155,6 @@ fileSystemSettingsWarning: fontWeight: bold archivePath: kind: panel.input.text - id: archivePath name: archivePath label: Archive Path validation: required path @@ -177,47 +163,40 @@ archivePath: disabled: true cachePath: kind: panel.input.text - id: cachePath name: cachePath label: Cache Path validation: required path description: "" prearchivePath: kind: panel.input.text - id: prearchivePath name: prearchivePath label: Prearchive Path validation: required path description: "" ftpPath: kind: panel.input.text - id: ftpPath name: ftpPath label: FTP Path validation: required path description: "" buildPath: kind: panel.input.text - id: buildPath name: buildPath label: Build Path validation: required id onblur description: "" pipelinePath: kind: panel.input.text - id: pipelinePath name: pipelinePath label: Pipeline Path validation: required id onblur description: "" zipExtensions: kind: panel.input.text - id: zipExtensions name: zipExtensions label: Zip Extensions checksums: kind: panel.input.checkbox - id: checksums name: checksums label: Checksums? description: > @@ -272,7 +251,6 @@ generalSecuritySettings: contents: securityChannel: kind: panel.select.single - id: securityChannel name: ":security.channel" label: Security Channel options: @@ -286,23 +264,19 @@ generalSecuritySettings: label: https value: https element: - id: security-channel title: Security Channel requireLogin: kind: panel.input.checkbox - id: requireLogin 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." restrictUserListAccessToAdmins: kind: panel.input.checkbox - id: restrictUserListAccessToAdmins name: restrictUserListAccessToAdmins label: "Restrict user list access <br>to site administrators?" description: "Should this site restrict access to the list of system users to site administrators only? If turned on, the site is more secure, but this restricts project owners from being able to administer users in their projects directly." uiAllowNonAdminProjectCreation: kind: panel.input.checkbox - id: uiAllowNonAdminProjectCreation name: ":UI.allow-non-admin-project-creation" label: "Allow non-administrators <br>to create projects?" description: "Should this site allow non-administrator users to create new projects? If turned on, the site is more secure, but this can make it more difficult for regular users to create new projects for their research efforts." @@ -319,7 +293,6 @@ userLoginsSessionControls: contents: sessionTimeout: kind: panel.input.text - id: sessionTimeout name: sessionTimeout label: Session Timeout description: > @@ -327,7 +300,6 @@ userLoginsSessionControls: <a target="_blank" href="http://www.postgresql.org/docs/9.0/static/functions-datetime.html">PostgreSQL interval notation</a> aliasTokenTimeout: kind: panel.input.text - id: aliasTokenTimeout name: aliasTokenTimeout label: Alias Token Timeout description: > @@ -335,7 +307,6 @@ userLoginsSessionControls: <a target="_blank" href="http://www.postgresql.org/docs/9.0/static/functions-datetime.html">PostgreSQL interval notation</a> aliasTokenTimeoutSchedule: kind: panel.input.text - id: aliasTokenTimeoutSchedule name: aliasTokenTimeoutSchedule label: Alias Token Timeout Schedule description: > @@ -343,9 +314,9 @@ userLoginsSessionControls: <a target="_blank" href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html">Cron notation</a> sessionTimeoutMessage: kind: panel.textarea - id: sessionTimeoutMessage name: sessionTimeoutMessage label: Session Timeout Message + code: html description: Alert message provided to users after a session timeout. TIMEOUT_TIME will be replaced by the timeout time. # allowResumeOnNextLogin: # kind: panel.input.checkbox @@ -355,26 +326,23 @@ userLoginsSessionControls: # description: Allow user to resume where they left off, if logging back in after a session timeout? maximumConcurrentSessions: kind: panel.input.number - id: maximumConcurrentSessions name: ":sessions.concurrent_max" label: Maximum Concurrent Sessions description: The maximum number of permitted sessions a user can have open simultaneously loginFailureMessage: kind: panel.textarea - id: loginFailureMessage name: ":UI.login_failure_message" label: Login Failure Message + code: html description: Text to show when a user fails to login # value: "?? XNAT:data:siteConfig:UI.login_failure_message" maximumFailedLogins: kind: panel.input.number - id: maximumFailedLogins name: maxFailedLogins label: Maximum Failed Logins description: Number of failed login attempts before accounts are temporarily locked. (-1 disables feature) failedLoginLockoutDuration: kind: panel.input.text - id: failedLoginLockoutDuration name: maxFailedLoginsLockoutDuration label: Failed Logins Lockout Duration description: > @@ -382,7 +350,6 @@ userLoginsSessionControls: <a target="_blank" href="http://www.postgresql.org/docs/9.0/static/functions-datetime.html">PostgreSQL interval notation</a> resetFailedLoginsSchedule: kind: panel.input.text - id: resetFailedLoginsSchedule name: resetFailedLoginsSchedule label: Reset Failed Logins Schedule description: > @@ -390,7 +357,6 @@ userLoginsSessionControls: <a target="_blank" href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html">Cron notation</a> userInactivityLockout: kind: panel.input.text - id: userInactivityLockout name: inactivityBeforeLockout label: User Inactivity Lockout description: > @@ -398,7 +364,6 @@ userLoginsSessionControls: <a target="_blank" href="http://www.postgresql.org/docs/9.0/static/functions-datetime.html">PostgreSQL interval notation</a> inactivityBeforeLockoutSchedule: kind: panel.input.text - id: inactivityBeforeLockoutSchedule name: inactivityBeforeLockoutSchedule label: Inactivity Lockout Schedule description: > @@ -417,18 +382,19 @@ passwords: contents: passwordComplexity: kind: panel.input.text - id: passwordComplexity name: passwordComplexity label: Password Complexity description: Must be a valid regular expression. passwordComplexityMessage: kind: panel.textarea - id: passwordComplexityMessage name: passwordComplexityMessage label: Password Complexity Message + code: html passwordExpiration: kind: panel.element label: Password Expiration + info: > + <p>A <b>password expiration interval</b> specifies the length of time users have before they must change their passwords (Specified in <a target="_blank" href="http://www.postgresql.org/docs/9.0/static/functions-datetime.html">PostgreSQL interval notation</a>)</p><p>Alternatively, a <b>password expiration date</b> can be configured to expire passwords that were last changed before it. This is useful for purging access to obsolete accounts.</p> contents: info: tag: p @@ -523,13 +489,11 @@ csrf: contents: enableCsrfToken: kind: panel.input.checkbox - id: enableCsrfToken name: enableCsrfToken label: Require CSRF Token? description: Should this site require the use of a token to prevent CSRF attacks on POST, PUT, and DELETEs? csrfEmailAlert: kind: panel.input.checkbox - id: csrfEmailAlert name: csrfEmailAlert label: CSRF Email Alert description: "Should this site send an email to the site admin whenever a CSRF attack is attempted?" @@ -546,22 +510,22 @@ securityServices: contents: securityServicesFeatureDefault: kind: panel.input.text - id: securityServicesFeatureDefault +# id: securityServicesFeatureDefault name: ":security.services.feature.default" label: Feature Default securityServicesFeatureRepoDefault: kind: panel.input.text - id: securityServicesFeatureRepoDefault +# id: securityServicesFeatureRepoDefault name: ":security.services.featureRepository.default" label: Feature Repository Default securityServicesRoleDefault: kind: panel.input.text - id: securityServicesRoleDefault +# id: securityServicesRoleDefault name: ":security.services.role.default" label: Role Default securityServicesRoleRepositoryDefault: kind: panel.input.text - id: securityServicesRoleRepositoryDefault +# id: securityServicesRoleRepositoryDefault name: ":security.services.roleRepository.default" label: Role Repository Default @@ -577,7 +541,6 @@ emailServerSettings: contents: smtpEnabled: kind: panel.input.checkbox - id: smtpEnabled name: ":smtp.enabled" label: "Enable SMTP?" hostname: @@ -640,7 +603,6 @@ notifications: contents: helpContactInfo: kind: panel.input.email - id: helpContactInfo name: ":notifications.helpContactInfo" label: "Help Contact Info" # value: "!? XNAT.data.notifications['notifications.helpContactInfo'] || XNAT.data.siteConfig.adminEmail" @@ -651,21 +613,21 @@ notifications: emailMessageUserRegistration: kind: panel.textarea - id: emailMessageUserRegistration name: ":notifications.emailMessageUserRegistration" label: "User Registration" + code: html description: "Text of message emailed to users upon registration. Link for email validation is auto-populated." emailMessageForgotUsernameRequest: kind: panel.textarea - id: emailMessageForgotUsernameRequest name: ":notifications.emailMessageForgotUsernameRequest" label: "Forgot Username Request" + code: html description: "Text of message emailed to users upon lost username request." emailMessageForgotPasswordReset: kind: panel.textarea - id: emailMessageForgotPasswordReset name: ":notifications.emailMessageForgotPasswordReset" label: "Password Reset" + code: html description: "Text of message emailed to users upon lost password reset. Link for password reset is auto-populated" # notifyAdminSubhead: @@ -707,28 +669,24 @@ notifications: emailRecipientErrorMessages: kind: panel.input.email - id: emailRecipientErrorMessages name: ":notifications.emailRecipientErrorMessages" label: "Error Messages" description: "What email address(es) should receive error emails. Separate multiple email addresses with commas. If empty, emails will be sent to the site administrator email address." value: "!? XNAT.data.notifications['notifications.emailRecipientErrorMessages'] || XNAT.data.siteConfig.adminEmail" emailRecipientIssueReports: kind: panel.input.email - id: emailRecipientIssueReports name: ":notifications.emailRecipientIssueReports" label: "Issue Reports" description: "What email address(es) should receive issue reports. Separate multiple email addresses with commas. If empty, emails will be sent to the site administrator email address." value: "!? XNAT.data.notifications['notifications.emailRecipientIssueReports'] || XNAT.data.siteConfig.adminEmail" emailRecipientNewUserAlert: kind: panel.input.email - id: emailRecipientNewUserAlert name: ":notifications.emailRecipientNewUserAlert" label: "New User Alert" description: "What email address(es) should receive New User Registration emails. Separate multiple email addresses with commas. If empty, emails will be sent to the site administrator email address." value: "!? XNAT.data.notifications['notifications.emailRecipientNewUserAlert'] || XNAT.data.siteConfig.adminEmail" emailRecipientUpdate: kind: panel.input.email - id: emailRecipientUpdate name: ":notifications.emailRecipientUpdate" label: "Updates" description: "What email address(es) should receive update emails. Separate multiple email addresses with commas. If empty, emails will be sent to the site administrator email address." @@ -740,7 +698,6 @@ notifications: emailAllowNonuserSubscribers: kind: panel.input.checkbox - id: emailAllowNonuserSubscribers name: emailAllowNonuserSubscribers label: "Allow Nonuser Subscribers" description: "Indicates whether this site should restrict email addresses for site notifications to addresses that are associated with valid active users of the XNAT installation. If turned on, the site is more secure from exploitation as a spam relay, but restricts the addresses that can be used when alerting administrators to system events." @@ -805,12 +762,10 @@ authenticationMethods: contents: xnatInternal: kind: panel.input.checkbox - id: xnatInternal name: ":provider.providers.xnatInternal" label: XNAT (Internal) ldapProvider: kind: panel.input.checkbox - id: ldapProvider name: ":provider.providers.ldap" label: LDAP # oauthProvider: @@ -830,17 +785,14 @@ genericAuthenticationProvider: contents: providerDbName: kind: panel.input.text - id: providerDbName name: providerDbName label: "Provider DB Name" providerDbId: kind: panel.input.text - id: providerDbId name: providerDbId label: "Provider DB ID" providerDbType: kind: panel.input.text - id: providerDbType name: providerDbType label: "Provider DB Type" @@ -856,42 +808,34 @@ ldapAuthentication: contents: ldapName: kind: panel.input.text - id: ldapName name: ldapName label: "LDAP Name" ldapId: kind: panel.input.text - id: ldapId name: ldapId label: "LDAP ID" ldapType: kind: panel.input.text - id: ldapType name: ldapType label: "LDAP Type" ldapAddress: kind: panel.input.text - id: ldapAddress name: ldapAddress label: "LDAP Address" ldapUserDomain: kind: panel.input.text - id: ldapUserDomain name: ldapUserDomain label: "LDAP User Domain" ldapPassword: kind: panel.input.text - id: ldapPassword name: ldapPassword label: "LDAP Password" ldapSearchBase: kind: panel.input.text - id: ldapSearchBase name: ldapSearchBase label: "LDAP Search Base" ldapSearchFilter: kind: panel.input.text - id: ldapSearchFilter name: ldapSearchFilter label: "LDAP Search Filter" @@ -919,7 +863,6 @@ registrationOptions: contents: requireEmailVerificationToRegister: kind: panel.input.checkbox - id: requireEmailVerificationToRegister name: emailVerification label: "Require Email Verification <br>to Register?" description: > @@ -929,18 +872,16 @@ registrationOptions: before using their account. Either way the administrator receives an email notification when a user registers. emailVerificationMessage: kind: panel.textarea - id: emailVerificationMessage name: emailVerificationMessage label: "Email Verification Message" + code: html description: Email message sent to newly registered users who have to verify their email address. FULL_NAME will be replaced by the user's first and last name and VERIFICATION_URL will be replaced by the URL where they can verify their email. emailVerificationExpiration: kind: panel.input.number - id: emailVerificationExpiration name: emailVerificationExpiration label: "Email Verification Expiration" autoEnableUserRegistration: kind: panel.input.checkbox - id: autoEnableUserRegistration name: userRegistration label: "Auto-enable <br>User Registration?" description: > @@ -949,7 +890,6 @@ registrationOptions: receives an email notification when a user registers. autoEnablePar: kind: panel.input.checkbox - id: autoEnablePar name: par label: "Auto-enable with <br>Project Access Request?" description: > @@ -959,7 +899,6 @@ registrationOptions: when a user registers. uiAllowNewUserComments: kind: panel.input.checkbox - id: uiAllowNewUserComments name: ":UI.allow-new-user-comments" label: "Allow User Comments <br>on Registration?" @@ -975,12 +914,10 @@ manageDataTypes: contents: displayNameForGenericImageSessionSingular: kind: panel.input.text - id: displayNameForGenericImageSessionSingular name: ":displayNameForGenericImageSession.singular" label: "Singular Display Name For Generic Image Session Singular" displayNameForGenericImageSessionPlural: kind: panel.input.text - id: displayNameForGenericImageSessionPlural name: ":displayNameForGenericImageSession.plural" label: "Plural Display Name For Generic Image Session Singular" @@ -996,7 +933,6 @@ sessionBuilder: contents: sessionXmlRebuilderRepeat: kind: panel.input.number - id: sessionXmlRebuilderRepeat name: sessionXmlRebuilderRepeat label: Session Idle Check Interval placeholder: Interval in milliseconds @@ -1006,7 +942,6 @@ sessionBuilder: milliseconds and defaults to 60,000 ms or one minute. sessionXmlRebuilderInterval: kind: panel.input.number - id: sessionXmlRebuilderInterval name: sessionXmlRebuilderInterval label: Session Idle Time placeholder: Time in minutes @@ -1027,14 +962,13 @@ anonymization: contents: enableSitewideAnonymizationScript: kind: panel.input.checkbox - id: enableSitewideAnonymizationScript name: enableSitewideAnonymizationScript label: "Enable Site-wide <br>Anonymization Script?" sitewideAnonymizationScript: kind: panel.textarea - id: sitewideAnonymizationScript name: sitewideAnonymizationScript label: "Edit Anonymization Script" + code: text description: > This is the site-wide anonymization script applied to all incoming and archiving DICOM resources. This script can also be supplemented by anonymization operations specified at the project level. The script must conform to <a href="http://nrg.wustl.edu/software/dicomedit/dicomedit-reference/" target="_blank">DicomEdit</a> format.<br><br>Note that if the site-wide anonymization is enabled, even with an empty script, it will add a deidentification method status entry to DICOM headers. To allow DICOM files to be imported without any changes, disable site-wide anonymization. @@ -1050,31 +984,24 @@ seriesImportFilter: contents: enableSitewideSeriesImportFilter: kind: panel.input.checkbox - id: enableSitewideSeriesImportFilter name: enableSitewideSeriesImportFilter label: "Enable Site-wide <br>Series Import Filter?" sitewideSeriesImportFilterMode: kind: panel.select.single - id: sitewideSeriesImportFilterMode name: sitewideSeriesImportFilterMode label: Filter Mode description: > Creating a <b>whitelist</b> means that <i>only</i> DICOM series with a series description that matches one of series filter patterns will be considered by XNAT import tools such as the upload applet. Creating a <b>blacklist</b> means that all DICOM series will be considered <i>except</i> for series that have one of the specified series filter patterns. A <b>modality map</b> lets you specify boolean expressions in JavaScript that can use DICOM header values from incoming DICOM objects to decide the appropriate modality for the destination session. options: - whitelist: - label: Whitelist - value: whitelist - blacklist: - label: Blacklist - value: blacklist - modalityMap: - label: Modality Map - value: modalityMap + #value: Label + whitelist: Whitelist + blacklist: Blacklist + modalityMap: Modality Map sitewideSeriesImportFilter: kind: panel.textarea - id: sitewideSeriesImportFilter name: sitewideSeriesImportFilter label: "Edit Series Import Filter" + code: text description: > The series filters can be written as exact string matches, but also can be regular expressions. The regular expressions are evaluated using the <a href="http://docs.oracle.com/javase/tutorial/essential/regex/" target="_blank">Java regular expression syntax</a>. These expressions are case-insensitive, @@ -1092,9 +1019,9 @@ petTracers: contents: sitewidePetTracers: kind: panel.textarea - id: sitewidePetTracers name: sitewidePetTracers label: "Pet Tracers" + code: text description: > This is the site-wide list of PET tracers. List entries should be separated by whitespace. This list can also be replaced at the project level. @@ -1110,21 +1037,15 @@ petMr: contents: petMr: kind: panel.select.single - id: sitewidePetMr name: sitewidePetMr label: "Separate PET-MR?" description: > Should data generated by PET-MR scanners be created as a single PET/MR imaging session, created as a single PET imaging session, or separated into PET and MR sessions? options: - petmr: - label: Create as PET/MR session - value: petmr - pet: - label: Create as PET session - value: pet - separate: - label: Separate into PET and MR sessions - value: separate + #value: Label + petmr: Create as PET/MR session + pet: Create as PET session + separate: Separate into PET and MR sessions sessionUploadMethod: kind: panel.form @@ -1156,15 +1077,14 @@ sessionUploadMethod: # description: "Enable to display link to Upload Applet on various XNAT pages." enableProjectAppletScript: kind: panel.input.checkbox - id: enableProjectAppletScript name: enableProjectAppletScript label: Enable Project Applet Script description: "The site-wide applet settings script can be supplemented by applet settings specified at the project level if this setting is enabled." appletScript: kind: panel.textarea - id: appletScript name: appletScript label: "Applet Script" + code: text description: > Details on how to configure an Upload Applet script may be found <a href="https://wiki.xnat.org/display/XKB/Adding+parameters+and+launch+requirements+for+the+upload+applet" target="_blank">here</a>. @@ -1203,12 +1123,14 @@ dicomScpReceivers: id: scp-title name: aeTitle label: AE Title +# description: AE Title for DICOM Receiver validation: required port: kind: panel.input.number id: scp-port name: port label: Port +# description: Port for DICOM Receiver validation: required naturalNoZero # fileNamer: # kind: panel.input.text @@ -1225,63 +1147,6 @@ dicomScpReceivers: element: src: /scripts/xnat/admin/dicomScpManager.js -dicomScpReceiversOld: - kind: panel.form - name: dicomScpReceiversOld - label: DICOM SCP Receivers - method: POST - action: /xapi/dicomscp - contentType: json - load: /xapi/dicomscp - contents: - enableDicomReceiver: - kind: panel.input.checkbox - id: enableDicomReceiver - name: enableDicomReceiver - label: DICOM Receiver Enabled? - description: "Should the DICOM receiver listen for connections?" - someInfo: - tag: div.message - element: - 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 - 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" - dicomHost: - kind: panel.input.text - id: dicomHost - name: dicomHost - label: DICOM Host - description: "Hostname(s) for DICOM Receiver(s)" - dicomAeTitle: - kind: panel.input.text - id: dicomAeTitle - name: dicomAeTitle - label: DICOM AE Title - description: "AE Title(s) for DICOM Receiver(s)" - dicomPortNumber: - kind: panel.input.number - id: dicomPortNumber - name: dicomPortNumber - label: DICOM Port - description: "Port for DICOM Receiver(s)" - defaultDicomReceiver: - kind: panel.select.single - id: defaultDicomReceiver - name: ":services.dicom.scp.aetitle" - label: Default DICOM Receiver - description: "AE Title for default DICOM receiver" - receivedFileUser: - kind: panel.input.text - id: receivedFileUser - name: receivedFileUser - label: "Default DICOM Receiver: User" - description: "User account for default DICOM receiver" - fileSystem: kind: panel.form name: fileSystem @@ -1315,7 +1180,6 @@ misc: contents: scanTypeMapping: kind: panel.input.checkbox - id: scanTypeMapping name: scanTypeMapping label: Scan Type Mapping? development: diff --git a/src/main/webapp/WEB-INF/tags/page/init.tag b/src/main/webapp/WEB-INF/tags/page/init.tag index ffe47ff0335db6dc620a2884bbce64f82316cab9..0d8a0825f7385f3171e5aede9007207aa53db9c9 100755 --- a/src/main/webapp/WEB-INF/tags/page/init.tag +++ b/src/main/webapp/WEB-INF/tags/page/init.tag @@ -9,6 +9,7 @@ <c:set var="loggedIn" value="false" scope="session"/> <c:set var="username" value="-" scope="session"/> <c:set var="isAdmin" value="false" scope="session"/> + <c:set var="isGuest" value="false" scope="session"/> <%-- set vars for user --%> <sec:authorize access="isAuthenticated()"> @@ -21,10 +22,14 @@ <%--<c:redirect url="/app/template/Login.vm"/>--%> </c:if> - <sec:authorize access="hasAnyRole('Administrator', 'administrator', 'Admin', 'admin', 'ADMIN')"> + <sec:authorize access="hasAnyRole('ADMIN')"> <c:set var="isAdmin" value="true" scope="session"/> </sec:authorize> + <sec:authorize access="hasAnyRole('ANONYMOUS')"> + <c:set var="isGuest" value="true" scope="session"/> + </sec:authorize> + <c:set var="themeName" value="${cookie.THEME_NAME.value}" scope="session"/> <%-- if there's a theme specified in the request, use that --%> diff --git a/src/main/webapp/WEB-INF/tags/page/xnat.tag b/src/main/webapp/WEB-INF/tags/page/xnat.tag index 88f301eb7a40504cd57f055e6e72c7ef5217611c..228401f46f1ea29f91576ddf604ff3bbc9a234d8 100644 --- a/src/main/webapp/WEB-INF/tags/page/xnat.tag +++ b/src/main/webapp/WEB-INF/tags/page/xnat.tag @@ -155,6 +155,9 @@ <!-- YUI css --> <%--<link rel="stylesheet" type="text/css" href="${SITE_ROOT}/scripts/yui/build/assets/skins/sam/skin.css?v=1.7.0a1">--%> + + <!-- Icon sets --> + <link rel="stylesheet" type="text/css" href="${SITE_ROOT}/style/icons.css?${versionString}"> <!-- xdat.css and xnat.css loaded last to override YUI styles --> <link rel="stylesheet" type="text/css" href="${SITE_ROOT}/style/app.css?${versionString}"> @@ -203,7 +206,7 @@ ${bodyTop} <div id="user_bar"> <div class="inner"> - <c:if test="${_user != '-'}"> + <c:if test="${_user != '-' || sessionScope.isGuest}"> <img id="attention_icon" src="${SITE_ROOT}/images/attention.png" style="display:none;" alt="attention needed - click for more info" title="attention needed - click for more info"> <span id="user_info">Logged in as: <a href="${SITE_ROOT}/app/template/XDATScreen_UpdateUser.vm">${_user}</a> <b>|</b> diff --git a/src/main/webapp/WEB-INF/views/error.jsp b/src/main/webapp/WEB-INF/views/error.jsp new file mode 100644 index 0000000000000000000000000000000000000000..fde1ab7fabccb5acc9e1b76f2074df9e07466d04 --- /dev/null +++ b/src/main/webapp/WEB-INF/views/error.jsp @@ -0,0 +1,44 @@ +<%@ page session="true" contentType="text/html" pageEncoding="UTF-8" language="java" %> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="pg" tagdir="/WEB-INF/tags/page" %> + +<jsp:useBean id="status" scope="request" type="org.springframework.http.HttpStatus"/> +<jsp:useBean id="url" scope="request" type="java.lang.String"/> +<jsp:useBean id="message" scope="request" type="java.lang.String"/> +<jsp:useBean id="exception" scope="request" type="java.lang.Throwable"/> + +<pg:wrapper> + <pg:xnat> + + <h3>An error has occurred</h3> + <table> + <tr> + <td><strong>Status:</strong></td> + <td>${status}</td> + </tr> + <tr> + <td><strong>Request URL:</strong></td> + <td>${url}</td> + </tr> + <tr> + <td><strong>Message:</strong></td> + <td>${message}</td> + </tr> + <c:if test="${not empty exception}"> + <tr> + <td><strong>Exception:</strong></td> + <td>${exception.message}</td> + </tr> + <tr> + <td><strong>Stacktrace:</strong></td> + <td> + <c:forEach var="element" items="exception.stackTrace"> + ${element.toString()}<br/> + </c:forEach> + </td> + </tr> + </c:if> + </table> + + </pg:xnat> +</pg:wrapper> diff --git a/src/main/webapp/page/admin/content.jsp b/src/main/webapp/page/admin/content.jsp index d6e095f4bdd6fad28aa6661fe2d2a85554e1bf08..bf022db330f008f5eccbd1b21abafdbbd26ceb4b 100755 --- a/src/main/webapp/page/admin/content.jsp +++ b/src/main/webapp/page/admin/content.jsp @@ -82,6 +82,7 @@ var adminTabs = XNAT.spawner.spawn(data); adminTabs.render(XNAT.tabs.container, 500, function(){ + initInfoLinks(); //if (window.location.hash) { // XNAT.ui.tab.select(getUrlHashValue()); //} @@ -94,6 +95,14 @@ }); })(); + + function initInfoLinks(){ + $('.infolink').click(function(e){ + var idx = this.id.substr(9); + var help = infoContent[idx]; + xmodal.message(help.title, help.content); + }); + }; </script> </div> diff --git a/src/main/webapp/scripts/globals.js b/src/main/webapp/scripts/globals.js index 0cb04e035a502eabb752768258ca84dfb560bc72..74784137ff60b1c3f4cb373550e6f6ea498270cc 100644 --- a/src/main/webapp/scripts/globals.js +++ b/src/main/webapp/scripts/globals.js @@ -656,27 +656,21 @@ autoID = randomID; // set 'forceLower' === true (or omit argument) // to ensure output is lowercase -function toDashed(name){ - return name.replace(/([A-Z])/g, function(u) { - return '-' + u.toLowerCase(); - }); +function toDashed(str){ + return str.replace(/[A-Z]/g, function(u) { + return '-' + u; + }).replace(/[A-Z]-/g, function(c){ + return c.replace(/-$/, ''); + }).toLowerCase().replace(/\W+|_+/g, '-').replace(/^-*|-*$/g, ''); } //hyphenate = toDashed; //dashify = toDashed; -function toDashedLower(name){ - return name.replace(/([A-Z])/g, function(u) { - return '-' + u.toLowerCase(); - }); -} - // set 'forceLower' === true (or omit argument) // to ensure *only* 'cameled' letters are uppercase -function toCamelCase(name, forceLower) { - if (isUndefined(forceLower) || isTrue(forceLower)){ - name = name.toLowerCase(); - } - return name.replace(/\-./g, function(u){ +function toCamelCase(str) { + // 'sanitize' by running str through toDashed() + return toDashed(str).replace(/-./g, function(u){ return u.substr(1).toUpperCase(); }); } @@ -686,20 +680,12 @@ function toCamelCase(name, forceLower) { //camelify = toCamelCase; //camelfy = toCamelCase; -function toCamelLower(name){ - return toCamelCase(name, true); -} - // put on the String prototype just for kicks // or don't //String.prototype.toDashed = function(forceLower){ // return toDashed(this, forceLower); //}; // -//String.prototype.toDashedLower = function(){ -// return toDashedLower(this); -//}; -// //String.prototype.toCamel = function(forceLower){ // return toCamel(this, forceLower); //}; @@ -784,8 +770,8 @@ function parseOptions(obj_or_str, str, delim, sep){ obj = obj_or_str; } - delim = delim || /,|;|\|/; // default delimiters ( , ; | - comma or semicolon or pipe) - sep = sep || /:|=/; // default key:value separators ( : = - colon or equals) + delim = delim || /[,;|]/; // default delimiters ( , ; | - comma or semicolon or pipe) + sep = sep || /[:=]/; // default key:value separators ( : = - colon or equals) var parts = isString(str) ? str.split(delim) : []; diff --git a/src/main/webapp/scripts/lib/form2js/src/form2js.js b/src/main/webapp/scripts/lib/form2js/src/form2js.js index 55c9bac720e93c52afc21b818f1cf1cebb652124..61a977db1e8e2a5d8f1e34a5a5d2cabc2397f7f3 100755 --- a/src/main/webapp/scripts/lib/form2js/src/form2js.js +++ b/src/main/webapp/scripts/lib/form2js/src/form2js.js @@ -258,7 +258,7 @@ function extractNodeValues(node, nodeCallback, useIdIfEmptyName, getDisabled) { if (node.disabled && !getDisabled) return []; - var callbackResult, fieldValue, result, fieldName = getFieldName(node, useIdIfEmptyName); + var callbackResult, hasValue, fieldValue, result, fieldName = getFieldName(node, useIdIfEmptyName); callbackResult = nodeCallback && nodeCallback(node); @@ -267,7 +267,17 @@ } else if (fieldName != '' && node.nodeName.match(/INPUT|TEXTAREA/i)) { fieldValue = getFieldValue(node, getDisabled); - if (null === fieldValue) { + + hasValue = !!fieldValue; + + // convert items with 'array-list' class to an actual array + if (hasValue && /array-list|list-array/i.test(node.className)) { + fieldValue = fieldValue.split(',').map(function(item, i){ + return item.trim(); + }); + } + + if (!hasValue) { result = []; } else { result = [ { name: fieldName, value: fieldValue} ]; diff --git a/src/main/webapp/scripts/lib/jquery-plugins/jquery.dataAttr.js b/src/main/webapp/scripts/lib/jquery-plugins/jquery.dataAttr.js index 0728d1217b0ab52533844aa14dc7cac97a15ec28..27f7d1453856701811ced73c644ce65bdc061232 100644 --- a/src/main/webapp/scripts/lib/jquery-plugins/jquery.dataAttr.js +++ b/src/main/webapp/scripts/lib/jquery-plugins/jquery.dataAttr.js @@ -118,16 +118,19 @@ $.fn.dataAttr = function(name, value){ } } - function toCamelCase(str){ - return str.toLowerCase().replace(/\-./g, function(u){ - return u.substr(1).toUpperCase(); - }); - } - function toDashed(str){ - return str.replace(/([A-Z])/g, function(u){ + return str.replace(/[A-Z]/g, function(u) { return '-' + u; - }).toLowerCase(); + }).replace(/[A-Z]-/g, function(c){ + return c.replace(/-$/, ''); + }).toLowerCase().replace(/\W+|_+/g, '-').replace(/^-*|-*$/g, ''); + } + + function toCamelCase(str) { + // 'sanitize' by running str through toDashed() + return toDashed(str).replace(/-./g, function(u){ + return u.substr(1).toUpperCase(); + }); } // return the jQuery object for chaining diff --git a/src/main/webapp/scripts/lib/spawn/spawn.js b/src/main/webapp/scripts/lib/spawn/spawn.js index be270f8641faf1cb2a948dbda49de2bd9022c167..9f8282994ed039fd12afbc0838b47b55c7d39ae3 100644 --- a/src/main/webapp/scripts/lib/spawn/spawn.js +++ b/src/main/webapp/scripts/lib/spawn/spawn.js @@ -102,6 +102,39 @@ }); } + function hasClassName(el, className){ + var elClasses = el.className.split(/\s+/); + return elClasses.indexOf(className.trim()) > -1; + } + + + // add new element class without destroying existing class + function addClassName(el, newClass){ + el.className = el.className || ''; + var classes = el.className.split(/\s+/); // existing classes + var newClasses = [].concat(newClass||[]).join(' ').split(/\s+/); + // don't add duplicate classes + newClasses.forEach(function(cls){ + if (!cls) return; + if (!hasClassName(el, cls)) { + classes.push(cls); + } + }); + // set the className and return the string + return el.className = classes.join(' ').trim(); + } + + + // add new data object item to be used for [data-] attribute(s) + function addDataObjects(el, attrs){ + el.data = el.data || {}; + forOwn(attrs, function(name, prop){ + el.data[name] = prop; + }); + // set the data attributes and return the new data object + return el.data; + } + function appendChildren(el, children, fn){ [].concat(children).forEach(function(child){ @@ -258,9 +291,7 @@ } // allow use of 'classes' property for classNames - if (opts.className || opts.classes || opts.addClass){ - el.className = [].concat(opts.className||[], opts.classes||[], opts.addClass||[]).join(' ').trim(); - } + addClassName(el, [].concat(opts.className||[], opts.classes||[], opts.addClass||[])); // IE *REALLY* hates method="PUT" on forms var methodPut = (opts.method && /put/i.test(opts.method)); diff --git a/src/main/webapp/scripts/project/userMgmt.js b/src/main/webapp/scripts/project/userMgmt.js index 5fa583af2d86360ba92bce7c340864fb6fbfec3f..ac7725bc4c050b461c4d0ca177ba580d1078a724 100644 --- a/src/main/webapp/scripts/project/userMgmt.js +++ b/src/main/webapp/scripts/project/userMgmt.js @@ -271,7 +271,15 @@ function UserManager(user_mgmt_div_id, pID, retrieveAllUsers){ }; this.allUsersFailure=function(o){ - this.displayError("ERROR " + o.status+ ": Failed to load complete user list."); + // We'll make note of non-403 errors. 403 is OK if the system is set to restrict non-admin access to the user list. + if (o.status != 403) { + this.displayError("ERROR " + o.status+ ": Failed to load complete user list."); + } else { + this.setFormDisabled(false); + document.getElementById("popup_all_users_button").disabled = true; + document.getElementById("popup_all_users_button_container1").style.visibility = "hidden"; + document.getElementById("popup_all_users_button_container2").style.visibility = "hidden"; + } this.allLoader.close(); }; diff --git a/src/main/webapp/scripts/restDeleter.js b/src/main/webapp/scripts/restDeleter.js index 1b8a02297989186b0d47a601bd8524c745cab750..f538147182c84d172bd5a0e3872cc24a7bf8c26b 100644 --- a/src/main/webapp/scripts/restDeleter.js +++ b/src/main/webapp/scripts/restDeleter.js @@ -20,22 +20,24 @@ RestDeleter = function(_array,_config) { t.width="100%"; var tb=t.appendChild(document.createElement("tbody")); for(var aC=0;aC<this.a.length;aC++){ - if(this.a[aC].canRead && (this.a[aC].allowDelete==undefined||this.a[aC].allowDelete==true)){ - var tr=tb.appendChild(document.createElement("tr")); - tr.entry=this.a[aC]; - - var td1=tr.appendChild(document.createElement("td")); - var td2=tr.appendChild(document.createElement("td")); - tr.td1=td1; - tr.td2=td2; - - td1.innerHTML=this.a[aC].label; - tr.pDivColor=td2.appendChild(document.createElement("div")); - tr.pDivColor.style.width="100%"; - tr.pDivColor.style.backgroundColor="gray"; - tr.pDivColor.style.color="white"; - tr.pDivColor.innerHTML=" waiting..."; - this.trArray.push(tr); + if(this.a[aC].canRead && (this.a[aC].allowDelete==undefined||this.a[aC].allowDelete==true)) { + if (!(this.a[aC].label == "Select All" && this.a[aC].xsiType == null)) { + var tr = tb.appendChild(document.createElement("tr")); + tr.entry = this.a[aC]; + + var td1 = tr.appendChild(document.createElement("td")); + var td2 = tr.appendChild(document.createElement("td")); + tr.td1 = td1; + tr.td2 = td2; + + td1.innerHTML = this.a[aC].label; + tr.pDivColor = td2.appendChild(document.createElement("div")); + tr.pDivColor.style.width = "100%"; + tr.pDivColor.style.backgroundColor = "gray"; + tr.pDivColor.style.color = "white"; + tr.pDivColor.innerHTML = " waiting..."; + this.trArray.push(tr); + } } } var NUMSPACES=(this.config.defaultHeight/25)-4; diff --git a/src/main/webapp/scripts/xnat/admin/pwExpType.js b/src/main/webapp/scripts/xnat/admin/pwExpType.js index 029720d556e4c13aaa6ce1a5d950c2b52ed56809..7128d2337473ec3610d71cbd3d3e5dc4d05cbc7e 100644 --- a/src/main/webapp/scripts/xnat/admin/pwExpType.js +++ b/src/main/webapp/scripts/xnat/admin/pwExpType.js @@ -1,4 +1,7 @@ // interactions with 'Security Passwords' section of admin ui + +console.log('pwExpType.js'); + (function(){ var fieldInterval, fieldDate, sdtDisabled, sdtInterval, sdtDate, openCal; setTimeout(function(){ @@ -13,7 +16,7 @@ fieldDate.datetimepicker({ timepicker:false, format:'m/d/Y', - maxDate:'1970/01/01' // today is max date, disallow future date selection + maxDate:'+1970/01/01' // today is max date, disallow future date selection }); sdtDisabled = $('#passwordExpirationTypeDisabled'); sdtInterval = $('#passwordExpirationTypeInterval'); @@ -22,6 +25,11 @@ sdtInterval.click(changePasswordExpirationType); sdtDate.click(changePasswordExpirationType); changePasswordExpirationType(XNAT.data.siteConfig.passwordExpirationType); + reuseDisabled = $('#passwordReuseTypeDisabled'); + reuseHistorical = $('#passwordReuseTypeHistorical'); + reuseDisabled.click(changePasswordReuseType); + reuseHistorical.click(changePasswordReuseType); + changePasswordReuseType(XNAT.data.siteConfig.passwordReuseRestriction); }, 1); function openCalendar(){ @@ -70,4 +78,26 @@ intervalUnits.hide(); } } + + function changePasswordReuseType(eventOrValue){ + var value = eventOrValue; + if (typeof eventOrValue === 'object') { + if (eventOrValue.target.id == "passwordReuseTypeHistorical") { + value = 'Historical'; + } else { + value = 'Disabled'; + } + } + reuseDisabled.val(value); + reuseHistorical.val(value); + var interval = $('div.input-bundle.reuseInterval'); + if (value == 'Disabled') { + reuseDisabled.prop('checked', true); + interval.val(-1); + interval.hide(); + } else if (value == 'Historical') { + reuseHistorical.prop('checked', true); + interval.show(); + } + } })(); diff --git a/src/main/webapp/scripts/xnat/admin/siteInfo.js b/src/main/webapp/scripts/xnat/admin/siteInfo.js index 3f102f37a2d7f3f3a1f8ed495bda5aa941efa303..2e491e0af226a862146e2e7b824963fb81b93004 100644 --- a/src/main/webapp/scripts/xnat/admin/siteInfo.js +++ b/src/main/webapp/scripts/xnat/admin/siteInfo.js @@ -1,45 +1,22 @@ // interractions with 'Site Info' section of admin ui (function(){ - var sdtPage, sdtText; - - setTimeout(function(){ - sdtPage = $('#siteDescriptionTypePage'); - sdtText = $('#siteDescriptionTypeText'); - sdtPage.click(changeSiteDescriptionType); - sdtText.click(changeSiteDescriptionType); - changeSiteDescriptionType(XNAT.data.siteConfig.siteDescriptionType); - }, 1); - - function changeSiteDescriptionType(eventOrValue){ - - var value = eventOrValue; - - if (typeof eventOrValue === 'object') { - if (eventOrValue.target.id == "siteDescriptionTypeText") { - value = 'Text'; - } - else { - value = 'Page'; - } - } - - sdtText.val(value); - sdtPage.val(value); - - var text = $('div.input-bundle.text'); - var page = $('div.input-bundle.page'); - - if (value == 'Text') { - sdtText.prop('checked', true); - text.show(); - page.hide(); - } - else { - sdtPage.prop('checked', true); - page.show(); - text.hide(); - } + var $container = $('[data-name="siteDescriptionType"]'); + var $bundles = $container.find('div.input-bundle'); + + $container.find('input[name="siteDescriptionType"]').on('change', function(){ + changeSiteDescriptionType(this.value); + }); + + changeSiteDescriptionType(XNAT.data.siteConfig.siteDescriptionType); + + function changeSiteDescriptionType(value){ + + value = (value || 'page').toLowerCase(); + + $bundles.hide(); + $bundles.filter('.' + value).show(); + } })(); diff --git a/src/main/webapp/scripts/xnat/app/codeEditor.js b/src/main/webapp/scripts/xnat/app/codeEditor.js index 15303d04a76c0f3cfc27af878333a38c47c0ebf4..bd109a80a2b3da3c079362d451b26d61d4b328cd 100644 --- a/src/main/webapp/scripts/xnat/app/codeEditor.js +++ b/src/main/webapp/scripts/xnat/app/codeEditor.js @@ -39,7 +39,9 @@ var XNAT = getObject(XNAT || {}); this.isInput = (function(){ return _this.$source.is(':input') })(); - this.isUrl = !this.source && this.opts.url; + this.isUrl = !this.source && (this.opts.loadUrl || this.opts.load || this.opts.url); + + this.loadUrl = this.isUrl ? (this.opts.loadUrl || this.opts.load || this.opts.url) : null; // set default language for editor // add [data-code-language="javascript"] to source code element @@ -51,19 +53,24 @@ var XNAT = getObject(XNAT || {}); // set source to null or empty string // and opts.url = '/url/to/data' to // pull code from a REST call - this.code = ''; + return XNAT.xhr.get(this.loadUrl); } else { // extract code from the source this.code = this.isInput ? this.$source.val() : this.$source.html(); } - return this.code + return this.code; + // return { + // done: function(callback){ + // callback.call(_this, _this.code); + // } + // } }; // this.getSourceCode(); - }; + } Editor.fn = Editor.prototype; @@ -83,8 +90,8 @@ var XNAT = getObject(XNAT || {}); if (this.isUrl){ // save via ajax return xhr.request(extend(true, { - method: method, - url: url, + method: method || _this.opts.submitMethod || _this.opts.method, + url: url || _this.opts.submitUrl || _this.opts.url, success: function(){ _this.dialog.close() } @@ -158,16 +165,18 @@ var XNAT = getObject(XNAT || {}); opts = cloneObject(opts); // insert additional content above editor - if (opts.before || opts.contentTop) { - modal.content += opts.before || opts.contentTop; + if (opts.before) { + modal.content += '<div class="before-editor">' + opts.before + '</div>'; + delete opts.before; // don't pass this to xmodal.open() } // div container for code editor modal.content += '<div class="code-editor" style="width:840px;height:440px;position:relative;"></div>'; // insert additional content BELOW editor - if (opts.after || opts.contentBottom) { - modal.content += opts.after || opts.contentBottom; + if (opts.after) { + modal.content += '<div class="after-editor">' + opts.after + '</div>'; + delete opts.after; // don't pass this to xmodal.open() } modal.title = 'XNAT Code Editor'; @@ -221,5 +230,25 @@ var XNAT = getObject(XNAT || {}); return new Editor(source, opts); }; -})(XNAT); + // bind codeEditor to elements with [data-code-editor] attribute + // <textarea name="foo" data-code-editor="language:html;" data-code-dialog="title:Edit The Code;width:500;height:300;"></textarea> + $('body').on('dblclick', '[data-code-editor]', function(){ + + var $source = $(this), + opts = parseOptions($source.dataAttr('codeEditor')), + dialog = parseOptions($source.dataAttr('codeDialog')); + + var editor = codeEditor.init(this, opts); + // if there's no title specified in [data-code-dialog] + // and there IS a [title] on the source element, + // use that title for the dialog + if (!dialog.title && opts.title) { + dialog.title = opts.title; + } + + editor.openEditor(dialog); + + }); + +})(XNAT); diff --git a/src/main/webapp/scripts/xnat/spawner.js b/src/main/webapp/scripts/xnat/spawner.js index 6088de02d8efd6427a6efefe0d5dc4ab744bc33e..66fa3444633a1df93b642c74a16d7416afb35c70 100644 --- a/src/main/webapp/scripts/xnat/spawner.js +++ b/src/main/webapp/scripts/xnat/spawner.js @@ -65,6 +65,8 @@ var XNAT = getObject(XNAT); // lastly use the object's own name prop.name = prop.name || item; + prop.id = prop.id || prop.element.id || toDashed(prop.name); + // accept 'kind' or 'type' property name // but 'kind' will take priority // with a fallback to a generic div @@ -146,7 +148,8 @@ var XNAT = getObject(XNAT); } else { - spawner.notSpawned.push(item); + if (hasConsole) console.log('not spawned: ' + prop); + spawner.notSpawned.push(prop); } } diff --git a/src/main/webapp/scripts/xnat/ui/breadcrumbs.js b/src/main/webapp/scripts/xnat/ui/breadcrumbs.js index 95a71d58c34cb135bdc52161b26f12e6f9b9c303..7e39f6be1c77bb6c40f194e945014fe55dba179f 100644 --- a/src/main/webapp/scripts/xnat/ui/breadcrumbs.js +++ b/src/main/webapp/scripts/xnat/ui/breadcrumbs.js @@ -35,7 +35,7 @@ var XNAT = getObject(XNAT||{}); if (i === len-1){ last = true; - html += ' class="nolink last"' + html += ' class="last"' } if (crumb.id){ diff --git a/src/main/webapp/scripts/xnat/ui/input.js b/src/main/webapp/scripts/xnat/ui/input.js index 5d5137f501af7908924c642584f97e938926394f..66875c5a49e0cb3f17d0a4aa399c38bc025b49d5 100644 --- a/src/main/webapp/scripts/xnat/ui/input.js +++ b/src/main/webapp/scripts/xnat/ui/input.js @@ -112,7 +112,7 @@ var XNAT = getObject(XNAT); otherTypes = [ 'password', 'date', 'file', - 'radio', 'button', 'hidden' + 'button', 'hidden' ]; otherTypes.forEach(function(type){ input[type] = function(config){ @@ -129,19 +129,33 @@ var XNAT = getObject(XNAT); // }; return setupType('checkbox', '', config); }; - - // create an input with display: block style - input.text.block = function(config){ - config = extend(true, {}, config, config.element, { - $: { addClass: 'text block' }, - style: { display: 'block' } - }); - return input.text(config); + + // radio buttons are special too + input.radio = function(config){ + otherTypes.push('radio'); + config = extend(true, {}, config, config.element); + return setupType('radio', '', config); }; // save a list of all available input types input.types = [].concat(textTypes, numberTypes, otherTypes); + // create display: block versions of ALL input types + input.types.forEach(function(type, i){ + input[type]['block'] = function(config){ + config = extend(true, {}, config, config.element, { + $: { addClass: 'display-block' }, + style: { display: 'block' } + }); + return input[type](config); + } + }); + + // // not *technically* an <input> element, but a form input nonetheless + // input.textarea = function(config){ + // + // }; + // after the page is finished loading, set empty // input values from [data-lookup] attribute $(window).on('load', function(){ diff --git a/src/main/webapp/scripts/xnat/ui/panel.js b/src/main/webapp/scripts/xnat/ui/panel.js index f185ac63545be063d2f15eb0763b296be6fd4ff0..3373652ec1898c9d97f4855ccbf8384127fe1132 100644 --- a/src/main/webapp/scripts/xnat/ui/panel.js +++ b/src/main/webapp/scripts/xnat/ui/panel.js @@ -21,19 +21,34 @@ var XNAT = getObject(XNAT || {}); XNAT.ui.panel = panel = getObject(XNAT.ui.panel || {}); + function hasClassName(el, className){ + var elClasses = el.className.split(/\s+/); + return elClasses.indexOf(className.trim()) > -1; + } + // add new element class without destroying existing class function addClassName(el, newClass){ - el.className = [].concat(el.className||[], newClass).join(' ').trim(); - return el.className; + el.className = el.className || ''; + var classes = el.className.split(/\s+/); // existing classes + var newClasses = newClass.split(/\s+/); + // don't add duplicate classes + newClasses.forEach(function(cls){ + if (!hasClassName(el, cls)) { + classes.push(cls); + } + }); + // set the className and return the string + return el.className = classes.join(' ').trim(); } // add new data object item to be used for [data-] attribute(s) - function addDataObjects(obj, attrs){ - obj.data = obj.data || {}; + function addDataObjects(el, attrs){ + el.data = el.data || {}; forOwn(attrs, function(name, prop){ - obj.data[name] = prop; + el.data[name] = prop; }); - return obj.data; + // set the data attributes and return the new data object + return el.data; } // string that indicates to look for a namespaced object value @@ -146,6 +161,7 @@ var XNAT = getObject(XNAT || {}); } // creates a panel that's a form that can be submitted + // TODO: REFACTOR THIS BEAST panel.form = function panelForm(opts, callback){ opts = cloneObject(opts); @@ -211,21 +227,30 @@ var XNAT = getObject(XNAT || {}); // find all form inputs with a name attribute $$(form).find(':input').each(function(){ + var $this = $(this); var val = lookupObjectValue(dataObj, this.name||this.title); //if (!val) return; if (Array.isArray(val)) { val = val.join(', '); + $this.addClass('array-list') } else { val = stringable(val) ? val : JSON.stringify(val); } - $(this).changeVal(val); + $this.not(':checkbox, :radio').changeVal(val); - if (/checkbox|radio/i.test(this.type)) { - this.checked = !!this.value; + if (/checkbox/i.test(this.type)) { + this.checked = realValue(val); + } + + if (/radio/i.test(this.type)) { + this.checked = isEqual(this.value, val); + if (this.checked) { + $this.trigger('change'); + } } }); @@ -478,7 +503,7 @@ var XNAT = getObject(XNAT || {}); if (/json/i.test(opts.contentType||'')){ // ajaxConfig.data = JSON.stringify(formToJSON(this)); // ajaxConfig.data = JSON.stringify(form2js(this, /[:\[\]]/)); - ajaxConfig.data = JSON.stringify(form2js(this, ':')); + ajaxConfig.data = JSON.stringify(form2js(this, ':', false)); ajaxConfig.processData = false; ajaxConfig.contentType = 'application/json'; $.ajax(ajaxConfig); @@ -651,6 +676,12 @@ var XNAT = getObject(XNAT || {}); // 'contents' will be inserted into the 'target' element _target = spawn('div.element-wrapper'); + // add a help info icon if one is specified + if (opts.info){ + _inner.push(['span#infolink-'+infoId+'.infolink.icon.icon-sm.icon-status.icon-qm','']); + infoContent[infoId++] = {label:opts.label, content:opts.info}; + } + // add the target to the content array _inner.push(_target); @@ -763,17 +794,15 @@ var XNAT = getObject(XNAT || {}); return XNAT.ui.template.panelInput(opts).spawned; }; - panel.input.radio = function panelInputCheckbox(opts){ + panel.input.radio = function panelInputRadio(opts){ opts = cloneObject(opts); opts.type = 'radio'; addClassName(opts, 'radio'); return XNAT.ui.template.panelInput(opts).spawned; }; - panel.input.hidden = function panelInputHidden(opts){ opts = cloneObject(opts); - opts.type = 'hidden'; opts.element = extend(true, { type: 'hidden', className: opts.className || opts.classes || '', @@ -781,17 +810,13 @@ var XNAT = getObject(XNAT || {}); id: opts.id || toDashed(opts.name), value: opts.value || '' }, opts.element); - addClassName(opts.element, 'hidden'); - if (opts.validation || opts.validate) { - extend(true, opts.element, { - data: { - validate: opts.validation || opts.validate - } - }) + addDataObjects(opts.element, { + validate: opts.validation || opts.validate + }); } - + // no need to wrap this in panel-specific elements return spawn('input', opts.element); }; @@ -842,10 +867,13 @@ var XNAT = getObject(XNAT || {}); }; panel.textarea = function(opts){ + opts = cloneObject(opts); opts.element = opts.element || opts.config || {}; + if (opts.id) opts.element.id = opts.id; if (opts.name) opts.element.name = opts.name; + opts.element.html = opts.element.html || opts.element.value || @@ -859,23 +887,32 @@ var XNAT = getObject(XNAT || {}); if (opts.code || opts.codeLanguage) { opts.code = opts.code || opts.codeLanguage; addDataObjects(opts.element, { - codeLanguage: opts.code + codeEditor: opts.code, + codeLanguage: opts.codeLanguage || opts.code }); + // open code editor on double-click + // opts.element.ondblclick = function(){ + // var panelTextarea = XNAT.app.codeEditor.init(this, { language: opts.code || 'html' }); + // panelTextarea.openEditor(); + // }; } - // open code editor on double-click - opts.element.ondblclick = function(){ - var panelTextarea = XNAT.app.codeEditor.init(this, { language: opts.code || 'html' }); - panelTextarea.openEditor(); - }; - - opts.element.rows = 10; + opts.element.rows = opts.rows || opts.element.rows || 10; var textarea = spawn('textarea', opts.element); + return XNAT.ui.template.panelDisplay(opts, textarea).spawned; + }; panel.input.textarea = panel.textarea; + panel.textarea.arrayList = function(opts){ + opts = extend(true, {}, { + element: { $: { addClass: 'array-list' } } + }, opts); + return panel.textarea(opts); + }; + ////////////////////////////////////////////////// // SELECT MENU PANEL ELEMENTS ////////////////////////////////////////////////// @@ -1332,3 +1369,4 @@ var XNAT = getObject(XNAT || {}); })(XNAT, jQuery, window); +var infoId = 0, infoContent = []; diff --git a/src/main/webapp/scripts/xnat/ui/tabs.js b/src/main/webapp/scripts/xnat/ui/tabs.js index 0930a6de21ed253e8c3382bc0106b95fa0cc3f0e..d885fd9311c22d6e4fa5915ecb077fd85d65e940 100755 --- a/src/main/webapp/scripts/xnat/ui/tabs.js +++ b/src/main/webapp/scripts/xnat/ui/tabs.js @@ -172,40 +172,58 @@ var XNAT = getObject(XNAT || {}); tabs.init = function tabsInit(obj){ var layout, container, $container, - navTabs, tabContent; + navTabs, $navTabs, tabContent, $tabContent, + NAV_TABS = 'div.xnat-nav-tabs', + TAB_CONTENT = 'div.xnat-tab-content'; // set container and layout before spawning: // XNAT.tabs.container = 'div.foo'; container = obj.container || tabs.container || 'div.xnat-tab-container'; + // the main container - contains tabs and content + $container = $$(container).hide(); + + // use existing tabs if already present + if ($container.find(NAV_TABS).length) { + navTabs = $container.find(NAV_TABS)[0] + } + else { + navTabs = spawn(NAV_TABS); + $container.append(navTabs); + } + + // use existing content container if already present + if ($container.find(TAB_CONTENT).length) { + tabContent = $container.find(TAB_CONTENT)[0]; + } + else { + tabContent = spawn(TAB_CONTENT); + $container.append(tabContent); + } + + $navTabs = $(navTabs); + $tabContent = $(tabContent); + layout = obj.layout || tabs.layout || 'left'; - navTabs = spawn('div.xnat-nav-tabs'); - tabContent = spawn('div.xnat-tab-content'); + if (layout === 'left') { + $navTabs.addClass('side pull-left'); + $tabContent.addClass('side pull-right'); + } // copy values to XNAT.tabs object for use elsewhere tabs.container = container; tabs.layout = layout; tabs.navTabs = navTabs; - if (layout === 'left') { - navTabs.className += ' side pull-left'; - tabContent.className += ' side pull-right'; - } - - $container = $$(container).hide(); - - $container.append(navTabs); - $container.append(tabContent); - // set up the group elements, if present if (obj.meta && obj.meta.tabGroups){ tabs.hasGroups = true; - $(navTabs).append(tab.groups(obj.meta.tabGroups)); + $navTabs.append(tab.groups(obj.meta.tabGroups)); } else { tabs.hasGroups = false; - $(navTabs).spawn('ul.tab-group'); + $navTabs.spawn('ul.tab-group'); } // bind tab click events diff --git a/src/main/webapp/scripts/xnat/ui/templates.js b/src/main/webapp/scripts/xnat/ui/templates.js index 0239e1e19f3cac2a79924129fad0f4263c2056bb..44c568feda7b22579680648d23c3e0fc546dc95b 100644 --- a/src/main/webapp/scripts/xnat/ui/templates.js +++ b/src/main/webapp/scripts/xnat/ui/templates.js @@ -128,7 +128,7 @@ var XNAT = getObject(XNAT); opts = cloneObject(opts); opts.id = opts.id||toDashed(opts.name||''); - opts.label = opts.label||opts.title||opts.name||''; + opts.label = opts.label||''; // pass in an element or create a new 'div' element element = @@ -140,7 +140,10 @@ var XNAT = getObject(XNAT); }, opts.element)); return template.panelElement(opts, [ - ['label.element-label|for='+element.id||opts.id, opts.label], + + // only add a label if specified + (opts.label ? ['label.element-label|for='+element.id||opts.id, opts.label] : ''), + ['div.element-wrapper', [].concat( (opts.beforeElement ? opts.beforeElement : []), @@ -256,7 +259,7 @@ var XNAT = getObject(XNAT); var hiddenInput; // check buttons if value is true - if (/checkbox|radio/i.test(element.type||'')) { + if (/checkbox/i.test(element.type||'')) { element.checked = /true|checked/i.test((opts.checked||element.value||'').toString()); @@ -298,44 +301,6 @@ var XNAT = getObject(XNAT); // ======================================== - // ======================================== - // select element for form panels - // template.panelSelect = function(opts){ - // - // opts = cloneObject(opts); - // - // opts.name = opts.name || opts.id || randomID('select-', false); - // opts.id = opts.id || toDashed(opts.name||''); - // opts.element = extend({ - // id: opts.id, - // name: opts.name, - // className: opts.className||'', - // //size: 25, - // title: opts.title||opts.name||opts.id||'', - // value: opts.value||'' - // }, opts.element); - // - // var _select = spawn('select', opts.element, [['option', 'Select']]); - // - // // add the options - // $.each(opts.options||{}, function(name, prop){ - // var _option = spawn('option', extend(true, { - // html: prop.html || prop.text || prop.label || prop.value || prop, - // value: prop.value || name - // }, prop.element)); - // // select the option if it's the select element's value - // if (prop.value === opts.value){ - // _option.selected = true; - // } - // _select.appendChild(_option) - // }); - // - // return template.panelInput(opts, _select); - // - // }; - // ======================================== - - template.panelElementGroup = function(opts, elements){ opts = cloneObject(opts); return template.panelElement(opts, [ diff --git a/src/main/webapp/scripts/xnat/url.js b/src/main/webapp/scripts/xnat/url.js index 2b180a957f32d69c21d6951c612bb1eddd3f4fbe..07282412b8da0b1542a14490c9814a001f4ff06b 100644 --- a/src/main/webapp/scripts/xnat/url.js +++ b/src/main/webapp/scripts/xnat/url.js @@ -352,10 +352,12 @@ var XNAT = getObject(XNAT||{}); // ['format=json','sort=asc'], or // { format: 'json', sort: 'asc' } + var urlParts = XNAT.url.splitUrl(url); + // need to get a query object first // so we can add the XNAT_CSRF and // XNAT_XHR params to the end - params = (params) ? XNAT.url.toQueryObject(params) : {}; + params = extend(urlParts.params, XNAT.url.toQueryObject(params)); if ((window.csrfToken || XNAT.csrfToken) && (isTrue(csrf))) { params.XNAT_CSRF = (window.csrfToken || XNAT.csrfToken); @@ -369,7 +371,7 @@ var XNAT = getObject(XNAT||{}); } } - return urlSetup(url, '', params); + return urlSetup(urlParts.base, '', params, urlParts.hash); }; diff --git a/src/main/webapp/scripts/xnat/xhr.js b/src/main/webapp/scripts/xnat/xhr.js index ba70ab21074a188527cf64687aaddf90c2f5e266..4fc01234a90d602b3ce37f6286544ad6e5eb3fd2 100755 --- a/src/main/webapp/scripts/xnat/xhr.js +++ b/src/main/webapp/scripts/xnat/xhr.js @@ -551,9 +551,9 @@ var XNAT = getObject(XNAT||{}), // intercept form submissions with 'ajax' or 'json' class // using namespaced event handler submit.json - $('body').on('submit.json, submit.ajax', 'form.ajax, form.json', function(){ - return xhr.form(this); - }); + //$('body').on('submit.json, submit.ajax', 'form.ajax, form.json', function(){ + // return xhr.form(this); + //}); // special case for YUI 'GET' request xhr.get.yui = function( /* url, data/null, opts_or_callback, callback */ ){ diff --git a/src/main/webapp/xdat-templates/macros/TurbineMacros.vm b/src/main/webapp/xdat-templates/macros/TurbineMacros.vm index 48da23a9aed352683201def948fc0fb6d597d03d..221f0065299ee54b383c392cbf8b2fe53bc8db12 100644 --- a/src/main/webapp/xdat-templates/macros/TurbineMacros.vm +++ b/src/main/webapp/xdat-templates/macros/TurbineMacros.vm @@ -1,11 +1,10 @@ -##Copyright 2005 Harvard University / Howard Hughes Medical Institute (HHMI) All Rights Reserved -## -## Default Macro file for cnda4 +#* @vtlvariable name="turbineUtils" type="org.nrg.xdat.turbine.utils.TurbineUtils" *# +#* @vtlvariable name="user" type="org.nrg.xft.security.UserI" *# +#* @vtlvariable name="tipText" type="java.util.List" *# +##Copyright 2016 Harvard University / Howard Hughes Medical Institute (HHMI) All Rights Reserved ## -## Put your Application macros in this file. +## Default macro file for XNAT ## -## patch test -#* @vtlvariable name="tipText" type="java.util.List" *# #macro(insertPipelineNotification) <br/> @@ -1640,7 +1639,7 @@ $!turbineUtils.escapeJS($s) #if($turbineUtils.toBoolean($siteConfig.getProperty("UI.debug-extension-points","false")))document.write("<div class='extension_js'>/templates/screens/$subFolder</div>")#end #foreach($screenProps in $turbineUtils.getTemplates($subFolder)) #set($templateFileName=$screenProps.getProperty("path")) - #if($turbineUtils.isGuest($user)) + #if($user.isGuest()) #if($turbineUtils.toBoolean($screenProps.getProperty("allowGuest","false"))) #parse("/screens/$templateFileName") #end @@ -1659,7 +1658,7 @@ $!turbineUtils.escapeJS($s) #if($turbineUtils.toBoolean($siteConfig.getProperty("UI.debug-extension-points","false")))document.write("<div class='extension_js'>/templates/screens/$dataType/$subFolder</div>")#end #foreach($screenProps in $turbineUtils.getTemplates($dataType,$subFolder)) #set($templateFileName=$screenProps.getProperty("path")) - #if($turbineUtils.isGuest($user)) + #if($user.isGuest()) #if($turbineUtils.toBoolean($screenProps.getProperty("allowGuest","false"))) #parse("/screens/$templateFileName") #end @@ -1678,7 +1677,7 @@ $!turbineUtils.escapeJS($s) #if($turbineUtils.toBoolean($siteConfig.getProperty("UI.debug-extension-points","false")))<div class="extension">/templates/screens/$subFolder</div>#end #foreach($screenProps in $turbineUtils.getTemplates($subFolder)) #set($templateFileName=$screenProps.getProperty("path")) - #if($turbineUtils.isGuest($user)) + #if($user.isGuest()) #if($turbineUtils.toBoolean($screenProps.getProperty("allowGuest","false"))) #parse("/screens/$templateFileName") #end @@ -1697,7 +1696,7 @@ $!turbineUtils.escapeJS($s) #if($turbineUtils.toBoolean($siteConfig.getProperty("UI.debug-extension-points","false")))<div class="extension">/templates/screens/$dataType/$subFolder</div>#end #foreach($screenProps in $turbineUtils.getTemplates($dataType,$subFolder)) #set($templateFileName=$screenProps.getProperty("path")) - #if($turbineUtils.isGuest($user)) + #if($user.isGuest()) #if($turbineUtils.toBoolean($screenProps.getProperty("allowGuest","false"))) #parse("/screens/$templateFileName") #end @@ -1715,7 +1714,7 @@ $!turbineUtils.escapeJS($s) #set($hasCustomScreens = false) #foreach($screenProps in $turbineUtils.getTemplates($dataType,$subFolder)) #set($templateFileName=$screenProps.getProperty("path")) - #if($turbineUtils.isGuest($user)) + #if($user.isGuest()) #if($turbineUtils.toBoolean($screenProps.getProperty("allowGuest","false"))) #set($hasCustomScreens = true) #end diff --git a/src/main/webapp/xdat-templates/navigations/NoMenuTop.vm b/src/main/webapp/xdat-templates/navigations/NoMenuTop.vm index 448e58b4960ed3b76b4a2b5329ad0cc8ffd1aaff..dd963c7d4982fa6939606dd67b9edef64eb14d7e 100644 --- a/src/main/webapp/xdat-templates/navigations/NoMenuTop.vm +++ b/src/main/webapp/xdat-templates/navigations/NoMenuTop.vm @@ -1,3 +1,4 @@ +#* @vtlvariable name="siteConfig" type="org.nrg.xdat.preferences.SiteConfigPreferences" *# #* @vtlvariable name="data" type="org.apache.turbine.util.RunData" *# #* @vtlvariable name="turbineUtils" type="org.nrg.xdat.turbine.utils.TurbineUtils" *# #* @vtlvariable name="page" type="org.apache.turbine.util.template.HtmlPageAttributes" *# @@ -5,6 +6,7 @@ #* @vtlvariable name="user" type="org.nrg.xft.security.UserI" *# #* @vtlvariable name="ui" type="org.apache.turbine.services.pull.util.UIManager" *# #* @vtlvariable name="link" type="org.apache.turbine.services.pull.tools.TemplateLink" *# +<!-- BEGIN NoMenuTop.vm --> $page.setBgColor($ui.bgcolor) <div id="user_bar" class="no_menu"> @@ -12,13 +14,18 @@ $page.setBgColor($ui.bgcolor) <span id="last_login">Last login: $turbineUtils.formatDateTime($last_login)</span> #end #if($user) - #set($username = $user.getUsername()) - #if($turbineUtils.isGuest($user)) + #if(!$siteConfig.requireLogin && $user.isGuest()) <span id="user_info">Logged in as: <span style="color:red;">Guest</span> <b>|</b> <a href="$link.setPage("Login.vm")">Login</a> <b>|</b> <a href="$link.setPage("Register.vm")">Register</a></span> - #elseif($username) - ## use default timout value from web.xml as the starting text in the "timeLeft" element - <span id="user_info">Logged in as: <a href="$link.setPage("XDATScreen_UpdateUser.vm")">$!username</a> <b>|</b> <a href="$link.setAction("LogoutUser")">Logout</a></span> - #end + #else + #set($username = $user.getUsername()) + #if($username) + ## use default timout value from web.xml as the starting text in the "timeLeft" element + <span id="user_info">Logged in as: <a href="$link.setPage("XDATScreen_UpdateUser.vm")">$!username</a> <b>|</b> <a href="$link.setAction("LogoutUser")">Logout</a></span> + <script> + window.loggedIn = true; + </script> + #end + #end #end <div class="clear"></div> </div><!-- /user_bar --> @@ -30,3 +37,4 @@ $page.setBgColor($ui.bgcolor) #parse("/screens/Logo.vm") </a> </div></div> +<!-- END NoMenuTop.vm --> diff --git a/src/main/webapp/xdat-templates/navigations/NoninteractiveTop.vm b/src/main/webapp/xdat-templates/navigations/NoninteractiveTop.vm index 944527d4b2e5f04fd0946783c1943659e7e79aa8..32ba1e26e50f929389c044d0b936f3a93f89945d 100644 --- a/src/main/webapp/xdat-templates/navigations/NoninteractiveTop.vm +++ b/src/main/webapp/xdat-templates/navigations/NoninteractiveTop.vm @@ -1,4 +1,5 @@ #* @vtlvariable name="data" type="org.apache.turbine.util.RunData" *# +#* @vtlvariable name="siteConfig" type="org.nrg.xdat.preferences.SiteConfigPreferences" *# #* @vtlvariable name="turbineUtils" type="org.nrg.xdat.turbine.utils.TurbineUtils" *# #* @vtlvariable name="page" type="org.apache.turbine.util.template.HtmlPageAttributes" *# #* @vtlvariable name="last_login" type="java.util.Date" *# @@ -13,15 +14,17 @@ $page.setBgColor($ui.bgcolor) <span id="last_login">Last login: $turbineUtils.formatDateTime($last_login)</span> #end #if($user) - #set($username = $user.getUsername()) - #if($turbineUtils.isGuest($user)) + #if(!$siteConfig.requireLogin && $user.isGuest()) <span id="user_info">Logged in as: <span style="color:red;">Guest</span> - #elseif($username) - ## use default timout value from web.xml as the starting text in the "timeLeft" element - <span id="user_info">Logged in as: <i>$!username</i> <b>|</b> <a href="$link.setAction("LogoutUser")">Logout</a></span> - <script> - window.loggedIn = true; - </script> + #else + #set($username = $user.getUsername()) + #if($username) + ## use default timout value from web.xml as the starting text in the "timeLeft" element + <span id="user_info">Logged in as: <i>$!username</i> <b>|</b> <a href="$link.setAction("LogoutUser")">Logout</a></span> + <script> + window.loggedIn = true; + </script> + #end #end #end <div class="clear"></div> diff --git a/src/main/webapp/xnat-templates/navigations/DefaultTop.vm b/src/main/webapp/xnat-templates/navigations/DefaultTop.vm index 33a30d782ecf756c89d9f145eaca9cc1e42fde96..f5adc98afaa50ca9e62ed888867739e6e861595a 100644 --- a/src/main/webapp/xnat-templates/navigations/DefaultTop.vm +++ b/src/main/webapp/xnat-templates/navigations/DefaultTop.vm @@ -1,3 +1,4 @@ +#* @vtlvariable name="user" type="org.nrg.xft.security.UserI" *# #* @vtlvariable name="timeLeft" type="java.lang.String" *# <!-- START: xnat-templates/navigations/DefaultTop.vm --> #if($popup) @@ -27,21 +28,24 @@ #if($last_login) <span id="last_login">Last login: $turbineUtils.formatDateTime($last_login)</span> #end - #if($turbineUtils.isGuest($user)) + #if($!user != "" && $user.isGuest()) <span id="user_info">Logged in as: <span style="color:red;">Guest</span> <b>|</b> <a href="$link.setPage("Login.vm")">Login</a> <b>|</b> <a href="$link.setPage("Register.vm")">Register</a></span> <script type="text/javascript"> Cookies.set('guest','true',{path:'/'}); </script> - #elseif($user.getUsername()) - ## use default timeout value from web.xml as the starting text in the "#timeLeft" element - <span id="user_info">Logged in as: <a href="$link.setPage("XDATScreen_UpdateUser.vm")">$!user.getUsername()</a> <b>|</b><span class="tip_icon" style="margin-right:3px;left:2px;top:3px;"> - <span class="tip shadowed" style="top:20px;z-index:10000;white-space:normal;left:-150px;width:300px;background-color:#ffc;">Your XNAT session will auto-logout after a certain period of inactivity. You can reset that timer without reloading the page by clicking "renew."</span> - </span> - ## some kind of default text needs to be there so stuff doesn't shift around before the timer functions kick in - Auto-logout in: <b id="timeLeft">-:--:--</b> - <a id="timeLeftRenew" href="javascript:" onClick="XNAT.app.timeout.handleOk()">renew</a> <b>|</b> <a id="logout_user" href="$link.setAction("LogoutUser")">Logout</a></span> - <script type="text/javascript"> - Cookies.set('guest','false',{path:'/'}); - </script> + #else + #set($username = $user.getUsername()) + #if($username) + ## use default timeout value from web.xml as the starting text in the "#timeLeft" element + <span id="user_info">Logged in as: <a href="$link.setPage("XDATScreen_UpdateUser.vm")">$!user.getUsername()</a> <b>|</b><span class="tip_icon" style="margin-right:3px;left:2px;top:3px;"> + <span class="tip shadowed" style="top:20px;z-index:10000;white-space:normal;left:-150px;width:300px;background-color:#ffc;">Your XNAT session will auto-logout after a certain period of inactivity. You can reset that timer without reloading the page by clicking "renew."</span> + </span> + ## some kind of default text needs to be there so stuff doesn't shift around before the timer functions kick in + Auto-logout in: <b id="timeLeft">-:--:--</b> - <a id="timeLeftRenew" href="javascript:" onClick="XNAT.app.timeout.handleOk()">renew</a> <b>|</b> <a id="logout_user" href="$link.setAction("LogoutUser")">Logout</a></span> + <script type="text/javascript"> + Cookies.set('guest','false',{path:'/'}); + </script> + #end #end <div class="clear"></div> </div> @@ -65,6 +69,20 @@ }) </script> +#if ($siteConfig.pathErrorWarning != "") + <div id="warning_bar" style="display:none;"> + <span class="close"><img src="$content.getURI('images/close.gif')"></span> + <span> + XNAT System Path Verification Failure: Contact your system administrator + <span class="tip_text">(<i>what does this mean?</i>) + <span class="tip shadowed"> + $siteConfig.pathErrorWarning + </span> + </span> + </span> + </div> +#end + #if ($sessionCount > 1 || $sessionIpCount > 1 ) ##If you want fewer warnings, you can eliminate $sessionCount > 1 so it will not display a warning for multiple sessions on the same IP, or increase it to $sessionCount > X where X is the maximum number of sessions you can have on the same IP before you get a warning. <div id="warning_bar" style="display:none;"> @@ -91,20 +109,6 @@ </div> #end -#if ($siteConfig.pathErrorWarning != "") - <div id="warning_bar" style="display:none;"> - <span class="close"><img src="$content.getURI('images/close.gif')"></span> - <span> - XNAT System Path Verification Failure: Contact your system administrator - <span class="tip_text">(<i>what does this mean?</i>) - <span class="tip shadowed"> - $siteConfig.pathErrorWarning - </span> - </span> - </span> - </div> -#end - <div id="main_nav"> <div class="inner"> diff --git a/src/main/webapp/xnat-templates/screens/XDATScreen_MyXNAT.vm b/src/main/webapp/xnat-templates/screens/XDATScreen_MyXNAT.vm index de26211d6b925ddd133caedf2950d7e908b99736..6f61defa994873e6accbe5ea5cd662c7a9332801 100644 --- a/src/main/webapp/xnat-templates/screens/XDATScreen_MyXNAT.vm +++ b/src/main/webapp/xnat-templates/screens/XDATScreen_MyXNAT.vm @@ -1,10 +1,11 @@ +#* @vtlvariable name="user" type="org.nrg.xft.security.UserI" *# ##Copyright 2005 Harvard University / Howard Hughes Medical Institute (HHMI) All Rights Reserved $page.setTitle("My XNAT") #if ($data.message) <DIV class="error">$data.message</DIV><br> #end -#if(!$turbineUtils.isGuest($user)) +#if(!$user.isGuest()) #parse("screens/XDATScreen_change_email.vm") <br /><br /> #parse("screens/XDATScreen_password.vm") diff --git a/src/main/webapp/xnat-templates/screens/XDATScreen_UpdateUser.vm b/src/main/webapp/xnat-templates/screens/XDATScreen_UpdateUser.vm index 5695593525abb2d1f9a6120f469acefe0420e79e..c726e0266c4970964fe2d4bf08c20ba0b971b8dd 100644 --- a/src/main/webapp/xnat-templates/screens/XDATScreen_UpdateUser.vm +++ b/src/main/webapp/xnat-templates/screens/XDATScreen_UpdateUser.vm @@ -1,3 +1,4 @@ +#* @vtlvariable name="user" type="org.nrg.xft.security.UserI" *# ##Copyright 2005 Harvard University / Howard Hughes Medical Institute (HHMI) All Rights Reserved #if ($expired || $forgot) $!data.getTemplateInfo().setLayoutTemplate("Noninteractive.vm") @@ -7,7 +8,7 @@ $page.setTitle("My XNAT") <DIV class="error">$data.message</DIV><br> #end -#if(!$turbineUtils.isGuest($user)) +#if(!$user.isGuest()) #if (!$expired && !$forgot) #parse("screens/XDATScreen_change_email.vm") <br /><br /> diff --git a/src/main/webapp/xnat-templates/screens/topBar/New/Default.vm b/src/main/webapp/xnat-templates/screens/topBar/New/Default.vm index a8f4f6e089f9d4028ba7b8ced2a40efd8d787427..576074f3d5f167ce7063ca63200deec63b278502 100644 --- a/src/main/webapp/xnat-templates/screens/topBar/New/Default.vm +++ b/src/main/webapp/xnat-templates/screens/topBar/New/Default.vm @@ -5,9 +5,9 @@ #* @vtlvariable name="displayManager" type="org.nrg.xdat.display.DisplayManager" *# #* @vtlvariable name="project" type="org.nrg.xdat.om.XnatProjectdata" *# <!-- Sequence: 10 --> - #if($siteConfig.getUiAllowNonAdminProjectCreation() || $data.getSession().getAttribute("userHelper").canCreate("xnat:subjectData/project")) + #if ($turbineUtils.isSiteAdmin($user) || $siteConfig.getUiAllowNonAdminProjectCreation() || $data.getSession().getAttribute("userHelper").canCreate("xnat:subjectData/project")) <li><a href="$link.setPage("XDATScreen_add_xnat_projectData.vm")">$displayManager.getSingularDisplayNameForProject()</a></li> - #end + #end <!-- --> #if ($data.getSession().getAttribute("userHelper").canCreate("xnat:subjectData")) #if($project) diff --git a/src/main/webapp/xnat-templates/screens/xnat_projectData/xnat_projectData_summary_management.vm b/src/main/webapp/xnat-templates/screens/xnat_projectData/xnat_projectData_summary_management.vm index 8fd56e1fe413e6e88538da160280ddcc268136b2..9fbd5cf16fd16d767b535b6d58e12c7dfa831b96 100644 --- a/src/main/webapp/xnat-templates/screens/xnat_projectData/xnat_projectData_summary_management.vm +++ b/src/main/webapp/xnat-templates/screens/xnat_projectData/xnat_projectData_summary_management.vm @@ -17,7 +17,7 @@ <TABLE> <TR> <TD COLSPAN="3"><h4 id="add_invite_user_header" style="margin-bottom:0px">Add/Invite User</h4> - Enter the email address of the user to add. + Enter the username or email address of the user to add. </TD> </TR> <TR> @@ -31,11 +31,11 @@ <TD COLSPAN="3"> </TD> </TR> #if($showUserList) - <TR> + <TR id="popup_all_users_button_container1"> <TD COLSPAN="3"><h4 id="user_list_header" style="margin-bottom:0px">Add Users from List</h4> </TD> </TR> - <TR> + <TR id="popup_all_users_button_container2"> <TD COLSPAN="3" NOWRAP> <input type="button" id="popup_all_users_button" disabled="true" value="Show List" ONCLICK="window.userManager.popupAllUsersBox();"/> </TD>