diff --git a/build.gradle b/build.gradle index cba2a3457fa7d0d0c90a98145807d29ab5a8857e..8eecde42f116e13e4b7365c5ef0284ef3ab2cb96 100644 --- a/build.gradle +++ b/build.gradle @@ -385,9 +385,10 @@ dependencies { compile "org.apache.httpcomponents:httpcore-nio:4.4.4" compile "org.codehaus.groovy:groovy-all:${vGroovy}" - compile "org.python:jython-standalone:${vJython}" + compile "org.python:jython:${vJython}" compile "net.sourceforge.saxon:saxon:${vSaxon}" + compile "xalan:xalan:2.7.2" compile "nl.bitwalker:UserAgentUtils:1.2.4" compile "com.twmacinta:fast-md5:2.7.1" @@ -423,7 +424,6 @@ dependencies { runtime "net.imagej:ij:1.50e" runtime "net.bull.javamelody:javamelody-core:1.58.0" runtime "org.javassist:javassist:3.20.0-GA" - runtime "xalan:xalan:2.7.2" providedCompile "javax.servlet:javax.servlet-api:${vServletApi}" diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 972604aef5c43767c8547fdca27ec9a5e8214015..740384b0ef641f50fa8d9cfe30b23130fa2ce6c6 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Sat May 28 14:49:32 CDT 2016 +#Thu Jul 07 14:39:27 CDT 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.13-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-2.13-all.zip diff --git a/src/main/java/org/nrg/xapi/rest/dicomscp/DicomSCPApi.java b/src/main/java/org/nrg/xapi/rest/dicomscp/DicomSCPApi.java index b4e5c40ec99efb64e71b018bc5f2bb7da022b0b0..e4e51c0d725ddb83255534cba3c57330dce5186d 100644 --- a/src/main/java/org/nrg/xapi/rest/dicomscp/DicomSCPApi.java +++ b/src/main/java/org/nrg/xapi/rest/dicomscp/DicomSCPApi.java @@ -6,7 +6,7 @@ import org.nrg.dcm.preferences.DicomSCPInstance; import org.nrg.framework.annotations.XapiRestController; import org.nrg.framework.exceptions.NrgServiceException; import org.nrg.xapi.rest.NotFoundException; -import org.nrg.xdat.rest.AbstractXnatRestApi; +import org.nrg.xdat.rest.AbstractXapiRestController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -20,7 +20,7 @@ import java.util.List; @Api(description = "XNAT DICOM SCP management API") @XapiRestController @RequestMapping(value = "/dicomscp") -public class DicomSCPApi extends AbstractXnatRestApi { +public class DicomSCPApi extends AbstractXapiRestController { private static final Logger _log = LoggerFactory.getLogger(DicomSCPApi.class); @ApiOperation(value = "Get list of all configured DICOM SCP receiver definitions.", notes = "The primary DICOM SCP retrieval function returns a list of all DICOM SCP receivers defined for the current system.", response = DicomSCPInstance.class, responseContainer = "List") diff --git a/src/main/java/org/nrg/xapi/rest/notifications/NotificationsApi.java b/src/main/java/org/nrg/xapi/rest/notifications/NotificationsApi.java index db69a9e3566c4526dfe1228fc84acee976cc9d68..ebb5c42a9e22c2bbc2a7227fb4d4ed7f5ead0ecc 100644 --- a/src/main/java/org/nrg/xapi/rest/notifications/NotificationsApi.java +++ b/src/main/java/org/nrg/xapi/rest/notifications/NotificationsApi.java @@ -9,7 +9,7 @@ import org.nrg.notify.services.NotificationService; import org.nrg.prefs.exceptions.InvalidPreferenceName; import org.nrg.xapi.exceptions.InitializationException; import org.nrg.xdat.preferences.NotificationsPreferences; -import org.nrg.xdat.rest.AbstractXnatRestApi; +import org.nrg.xdat.rest.AbstractXapiRestController; import org.nrg.xnat.services.XnatAppInfo; import org.nrg.xnat.utils.XnatHttpUtils; import org.slf4j.Logger; @@ -29,7 +29,7 @@ import java.util.*; @Api(description = "XNAT Notifications management API") @XapiRestController @RequestMapping(value = "/notifications") -public class NotificationsApi extends AbstractXnatRestApi { +public class NotificationsApi extends AbstractXapiRestController { public static final String POST_PROPERTIES_NOTES = "Sets the mail service host, port, username, password, and protocol. You can set " + "extra properties on the mail sender (e.g. for configuring SSL or TLS transport) by " diff --git a/src/main/java/org/nrg/xapi/rest/settings/SiteConfigApi.java b/src/main/java/org/nrg/xapi/rest/settings/SiteConfigApi.java index c9172788f223c1f510df6e36b16063924711c46f..8efe9d55314e6afe2027f7b5f5eb6778c5035a22 100644 --- a/src/main/java/org/nrg/xapi/rest/settings/SiteConfigApi.java +++ b/src/main/java/org/nrg/xapi/rest/settings/SiteConfigApi.java @@ -7,7 +7,7 @@ import org.nrg.framework.annotations.XapiRestController; import org.nrg.prefs.exceptions.InvalidPreferenceName; import org.nrg.xapi.exceptions.InitializationException; import org.nrg.xdat.preferences.SiteConfigPreferences; -import org.nrg.xdat.rest.AbstractXnatRestApi; +import org.nrg.xdat.rest.AbstractXapiRestController; import org.nrg.xnat.services.XnatAppInfo; import org.nrg.xnat.turbine.utils.ArcSpecManager; import org.nrg.xnat.utils.XnatHttpUtils; @@ -32,7 +32,7 @@ import java.util.Properties; @Api(description = "Site Configuration Management API") @XapiRestController @RequestMapping(value = "/siteConfig") -public class SiteConfigApi extends AbstractXnatRestApi { +public class SiteConfigApi extends AbstractXapiRestController { @ApiOperation(value = "Returns a map of application build properties.", notes = "This includes the implementation version, Git commit hash, and build number and number.", response = Properties.class) @ApiResponses({@ApiResponse(code = 200, message = "Application build properties successfully retrieved."), @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), @ApiResponse(code = 500, message = "Unexpected error")}) @RequestMapping(value = "buildInfo", produces = {MediaType.APPLICATION_JSON_VALUE}, method = {RequestMethod.GET}) diff --git a/src/main/java/org/nrg/xapi/rest/users/UsersApi.java b/src/main/java/org/nrg/xapi/rest/users/UsersApi.java index e59a3e6513906fe184b960bc241dd0246a6c452e..dca118723dd34a2b6b3cadeaeccd3a6b51d6d261 100644 --- a/src/main/java/org/nrg/xapi/rest/users/UsersApi.java +++ b/src/main/java/org/nrg/xapi/rest/users/UsersApi.java @@ -7,7 +7,7 @@ import org.nrg.xapi.model.users.User; import org.nrg.xapi.rest.NotFoundException; import org.nrg.xdat.XDAT; import org.nrg.xdat.preferences.SiteConfigPreferences; -import org.nrg.xdat.rest.AbstractXnatRestApi; +import org.nrg.xdat.rest.AbstractXapiRestController; import org.nrg.xdat.security.UserGroupI; import org.nrg.xdat.security.helpers.Groups; import org.nrg.xdat.security.helpers.Users; @@ -32,7 +32,7 @@ import java.util.*; @Api(description = "User Management API") @XapiRestController @RequestMapping(value = "/users") -public class UsersApi extends AbstractXnatRestApi { +public class UsersApi extends AbstractXapiRestController { private static final Logger _log = LoggerFactory.getLogger(UsersApi.class); @ApiOperation(value = "Get list of users.", notes = "The primary users function returns a list of all users of the XNAT system.", response = User.class, responseContainer = "List") 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 321ef8a28f2cd2d9b2aa2f4562c3046c2ac9a77a..ceb1700c66a2a3537bb1f281fb60d0c4608aef67 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,7 +32,6 @@ 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; @@ -50,385 +49,368 @@ import org.springframework.util.StringUtils; import org.xml.sax.SAXException; import java.io.File; -import java.io.IOException; import java.io.Reader; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.Map; public class SavedSearchResource extends ItemResource { - XdatStoredSearch xss = null; - String sID=null; - boolean loadedFromFile=false; - - public SavedSearchResource(Context context, Request request, - Response response) { - super(context, request, response); - - sID= (String)getParameter(request,"SEARCH_ID"); - if(sID!=null){ - this.getVariants().add(new Variant(MediaType.TEXT_XML)); - }else{ - response.setStatus(Status.CLIENT_ERROR_GONE); - } - } - - - /** - * Returns a file containing search xmls which was stored on the file system. This provides a way to standardize search xmls outside of the database, for easy sharing across installations. - * @return - */ - private synchronized static File getFileSystemSearch(String name){ - if(name.indexOf("..")==-1){ - final File file=new File(new File(XFT.GetConfDir()).getParentFile().getParentFile(),"resources/searches/" + name); - if(file.exists()){ - return file; - } - } - return null; - } - - @Override - public Representation represent(Variant variant) { - MediaType mt = overrideVariant(variant); - - if(xss==null && sID!=null){ - if(sID.startsWith("@")){ - try { - String dv = this.getQueryVariable("dv"); - if(dv==null){ - dv="listing"; - } - DisplaySearch ds = new DisplaySearch(); - ds.setUser(user); - ds.setDisplay(dv); - ds.setRootElement(sID.substring(1)); - xss=ds.convertToStoredSearch(sID); - xss.setId(sID); - } catch (XFTInitException e) { - logger.error("",e); - } catch (ElementNotFoundException e) { - logger.error("",e); - } - }else{ - xss= XdatStoredSearch.getXdatStoredSearchsById(sID, user, true); - } - } - - if(xss != null) { - if(!xss.hasAllowedUser(user.getLogin()) || !Permissions.canQuery(user, xss.getRootElementName())){ + private XdatStoredSearch xss = null; + private String sID = null; + private boolean loadedFromFile = false; + + public SavedSearchResource(Context context, Request request, + Response response) { + super(context, request, response); + + sID = (String) getParameter(request, "SEARCH_ID"); + if (sID != null) { + this.getVariants().add(new Variant(MediaType.TEXT_XML)); + } else { + response.setStatus(Status.CLIENT_ERROR_GONE); + } + } + + /** + * Returns a file containing search xmls which was stored on the file system. This provides a way to standardize search xmls outside of the database, for easy sharing across installations. + * + * @return The search XMLs stored on the file system. + */ + private synchronized static File getFileSystemSearch(String name) { + if (!name.contains("..")) { + final File file = new File(new File(XFT.GetConfDir()).getParentFile().getParentFile(), "resources/searches/" + name); + if (file.exists()) { + return file; + } + } + return null; + } + + @Override + public Representation represent(Variant variant) { + MediaType mt = overrideVariant(variant); + + if (xss == null && sID != null) { + if (sID.startsWith("@")) { + try { + String dv = this.getQueryVariable("dv"); + if (dv == null) { + dv = "listing"; + } + DisplaySearch ds = new DisplaySearch(); + ds.setUser(user); + ds.setDisplay(dv); + ds.setRootElement(sID.substring(1)); + xss = ds.convertToStoredSearch(sID); + xss.setId(sID); + } catch (XFTInitException | ElementNotFoundException e) { + logger.error("", e); + } + } else { + xss = XdatStoredSearch.getXdatStoredSearchsById(sID, user, true); + } + } + + if (xss != null) { + if (!xss.hasAllowedUser(user.getLogin()) && !Permissions.canQuery(user, xss.getRootElementName())) { getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); return null; } } else { - //allow loading of saved searches from xml stored on hte file system - File search_xml=getFileSystemSearch(sID); - - if(mt.equals(MediaType.TEXT_XML) && (filepath ==null || !filepath.startsWith("results")) && !this.hasQueryVariable("project")){ - return new FileRepresentation(search_xml, mt); - }else{ - try { - SAXReader reader = new SAXReader(user); - XFTItem item = reader.parse(search_xml); - xss = new XdatStoredSearch(item); - - loadedFromFile=true; - - if(this.getQueryVariable("project")!=null){ - final XdatCriteriaSet cs= new XdatCriteriaSet((UserI)user); - cs.setMethod("OR"); - - for(final String p: StringUtils.commaDelimitedListToSet(this.getQueryVariable("project"))){ - XdatCriteria c=new XdatCriteria((UserI)user); - c.setSchemaField(xss.getRootElementName()+"/project"); - c.setComparisonType("="); - c.setValue(p); - cs.setCriteria(c); - - c=new XdatCriteria((UserI)user); - c.setSchemaField(xss.getRootElementName()+"/sharing/share/project"); - c.setComparisonType("="); - c.setValue(p); - cs.setCriteria(c); - } - - xss.setSearchWhere(cs); - } - } catch (Exception e) { - logger.error("",e); - getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); - return null; - } - } - } - - if(xss!=null){ - if(filepath !=null && filepath.startsWith("results")){ + //allow loading of saved searches from xml stored on hte file system + final File searchXml = getFileSystemSearch(sID); + + if (searchXml != null) { + if (mt.equals(MediaType.TEXT_XML) && (filepath == null || !filepath.startsWith("results")) && !this.hasQueryVariable("project")) { + return new FileRepresentation(searchXml, mt); + } else { + try { + SAXReader reader = new SAXReader(user); + XFTItem item = reader.parse(searchXml); + xss = new XdatStoredSearch(item); + + loadedFromFile = true; + + if (this.getQueryVariable("project") != null) { + final XdatCriteriaSet cs = new XdatCriteriaSet(user); + cs.setMethod("OR"); + + for (final String p : StringUtils.commaDelimitedListToSet(this.getQueryVariable("project"))) { + XdatCriteria c = new XdatCriteria(user); + c.setSchemaField(xss.getRootElementName() + "/project"); + c.setComparisonType("="); + c.setValue(p); + cs.setCriteria(c); + + c = new XdatCriteria(user); + c.setSchemaField(xss.getRootElementName() + "/sharing/share/project"); + c.setComparisonType("="); + c.setValue(p); + cs.setCriteria(c); + } + + xss.setSearchWhere(cs); + } + } catch (Exception e) { + logger.error("", e); + getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); + return null; + } + } + } + } + + if (xss != null) { + if (filepath != null && filepath.startsWith("results")) { if ((mt.equals(SecureResource.TEXT_CSV) || mt.equals(MediaType.APPLICATION_EXCEL)) && - !filepath.endsWith(".csv")){ + !filepath.endsWith(".csv")) { this.setContentDisposition(filepath + ".csv"); } - try { - DisplaySearch ds=xss.getDisplaySearch(user); - String sortBy = this.getQueryVariable("sortBy"); - String sortOrder = this.getQueryVariable("sortOrder"); - if (sortBy != null){ - ds.setSortBy(sortBy); - if(sortOrder != null) - { - ds.setSortOrder(sortOrder); - } - } - - MaterializedViewI mv=null; - - if(xss.getId()!=null && !xss.getId().equals("")){ - mv = MaterializedView.getViewBySearchID(xss.getId(), user,getQueryVariable(MaterializedView.CACHING_HANDLER,MaterializedView.DEFAULT_MATERIALIZED_VIEW_SERVICE_CODE)); - } - - if(mv!=null && (xss.getId().startsWith("@") || this.isQueryVariableTrue("refresh"))){ - mv.delete(); - mv=null; - } - - LinkedHashMap<String,Map<String,String>> cp=SearchResource.setColumnProperties(ds,user,this); - - XFTTable table=null; - if(mv!=null){ - if (mt.equals(SecureResource.APPLICATION_XLIST)){ - table=(XFTTable)ds.execute(new RESTHTMLPresenter(TurbineUtils.GetRelativePath(ServletCall.getRequest(this.getRequest())),this.getCurrentURI(),user,sortBy),user.getLogin()); - }else if(this.isQueryVariableTrue("guiStyle")){ - table=(XFTTable)ds.execute(new CSVPresenter(),user.getLogin()); - }else{ - table=mv.getData(null, null, null); + try { + DisplaySearch ds = xss.getDisplaySearch(user); + String sortBy = this.getQueryVariable("sortBy"); + String sortOrder = this.getQueryVariable("sortOrder"); + if (sortBy != null) { + ds.setSortBy(sortBy); + if (sortOrder != null) { + ds.setSortOrder(sortOrder); } - }else{ + } + + MaterializedViewI mv = null; + + if (xss.getId() != null && !xss.getId().equals("")) { + mv = MaterializedView.getViewBySearchID(xss.getId(), user, getQueryVariable(MaterializedView.CACHING_HANDLER, MaterializedView.DEFAULT_MATERIALIZED_VIEW_SERVICE_CODE)); + } + + if (mv != null && (xss.getId().startsWith("@") || this.isQueryVariableTrue("refresh"))) { + mv.delete(); + mv = null; + } + + LinkedHashMap<String, Map<String, String>> cp = SearchResource.setColumnProperties(ds, user, this); + + final XFTTable table; + if (mv != null) { + if (mt.equals(SecureResource.APPLICATION_XLIST)) { + table = (XFTTable) ds.execute(new RESTHTMLPresenter(TurbineUtils.GetRelativePath(ServletCall.getRequest(this.getRequest())), this.getCurrentURI(), user, sortBy), user.getLogin()); + } else if (this.isQueryVariableTrue("guiStyle")) { + table = (XFTTable) ds.execute(new CSVPresenter(), user.getLogin()); + } else { + table = mv.getData(null, null, null); + } + } else { ds.setPagingOn(false); - if (mt.equals(SecureResource.APPLICATION_XLIST)){ - table=(XFTTable)ds.execute(new RESTHTMLPresenter(TurbineUtils.GetRelativePath(ServletCall.getRequest(this.getRequest())),this.getCurrentURI(),user,sortBy),user.getLogin()); - }else if(this.isQueryVariableTrue("guiStyle")){ - table=(XFTTable)ds.execute(new CSVPresenter(),user.getLogin()); - }else{ - table=(XFTTable)ds.execute(null,user.getLogin()); + if (mt.equals(SecureResource.APPLICATION_XLIST)) { + table = (XFTTable) ds.execute(new RESTHTMLPresenter(TurbineUtils.GetRelativePath(ServletCall.getRequest(this.getRequest())), this.getCurrentURI(), user, sortBy), user.getLogin()); + } else if (this.isQueryVariableTrue("guiStyle")) { + table = (XFTTable) ds.execute(new CSVPresenter(), user.getLogin()); + } else { + table = (XFTTable) ds.execute(null, user.getLogin()); } } - Hashtable<String,Object> tableParams=new Hashtable<String,Object>(); - tableParams.put("totalRecords", table.getNumRows()); - - return this.representTable(table, mt, tableParams,cp); - } catch (Exception e) { - logger.error("",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } - }else{ - if (mt.equals(MediaType.TEXT_XML)){ - ItemXMLRepresentation rep= new ItemXMLRepresentation(xss.getItem(),MediaType.TEXT_XML); - if(sID.startsWith("@") || loadedFromFile){ - rep.setAllowDBAccess(false); - } - - return rep; - } - } - } - - return null; - - } - - @Override - public boolean allowDelete() { - return true; - } - - @Override - public boolean allowPut() { - return true; - } - - @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); - - boolean isNew=false; - - if(search.getId()==null || !search.getId().equals(sID)){ - search.setId(sID); - isNew=true; - }else{ - XFTItem xss= search.getCurrentDBVersion(false); - if(xss==null){ - isNew=true; - }else if(this.isQueryVariableTrue("saveAs")){ - while(xss!=null){ - search.setId(search.getId()+"_1"); - xss= search.getCurrentDBVersion(false); - } - isNew=true; - } - } - if (isNew && search.getTag() != null) { - CriteriaCollection cc = new CriteriaCollection("AND"); - cc.addClause("xdat:stored_search/tag", search.getTag()); - cc.addClause("xdat:stored_search/brief-description", search.getBriefDescription()); - ItemCollection result = ItemSearch.GetItems(cc, user, false); - if (result.size() > 0) { - isNew = false; - search.setId(result.getFirst().getStringProperty("ID")); - } - } - - if(!Permissions.canQuery(user, search.getRootElementName())){ - getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); - return; - } - - final boolean isPrimary = (search.getTag() != null && (search.getId().equals(search.getTag() + "_" + search.getRootElementName()))) || - (org.apache.commons.lang3.StringUtils.isNotBlank(search.getBriefDescription()) && search.getBriefDescription().equals(DisplayManager.GetInstance().getPluralDisplayNameForElement(search.getRootElementName()))); - - if(isNew && isPrimary){ - if(!Permissions.can(user,"xnat:projectData/ID", search.getTag(), SecurityManager.DELETE)){ - isNew=false; - } - } - - if(this.isQueryVariableTrue("saveAs")){ - while(search.getAllowedGroups_groupid().size()>0){ - search.removeAllowedGroups_groupid(0); - } - - while(search.getAllowedUser().size()>0){ - search.removeAllowedUser(0); - } - } - - boolean found=false; - for(XdatStoredSearchAllowedUser au : search.getAllowedUser()){ - if(au.getLogin().equals(user.getLogin())){ - found=true; - } - } - - for(XdatStoredSearchGroupid ag : search.getAllowedGroups_groupid()){ - if(Groups.isMember(user,ag.getGroupid())){ - found=true; - } - } - - if(!found && !isNew){ - if(search.getTag()!=null && !search.getTag().equals("")){ - if(!Permissions.canEdit(user,"xnat:projectData/ID", search.getTag())){ - this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); - return; - }else{ - XdatStoredSearchAllowedUser au = new XdatStoredSearchAllowedUser((UserI)user); - au.setLogin(user.getLogin()); - search.setAllowedUser(au); - } - }else{ - this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); - return; - } - } - - if(isNew && !found){ - XdatStoredSearchAllowedUser au = new XdatStoredSearchAllowedUser((UserI)user); - au.setLogin(user.getLogin()); - search.setAllowedUser(au); - } - - try { - SaveItemHelper.unauthorizedSave(search,user, false, true,this.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN, (isNew)?"Creating new stored search":"Modified existing stored search")); - } catch (Exception e) { - logger.error("",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } - - } catch (IOException e) { - logger.error("",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } catch (SAXException e) { - logger.error("",e); - this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); - } catch (ElementNotFoundException e) { - logger.error("",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } catch (Exception e) { - logger.error("",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } - } - - - - @Override - public void handleDelete() { - if(sID!=null){ - try { - XdatStoredSearch search = XdatStoredSearch.getXdatStoredSearchsById(sID, user, false); - - if(search!=null){ - XdatStoredSearchAllowedUser mine=null; - XdatStoredSearchGroupid group=null; - - for(XdatStoredSearchAllowedUser au : search.getAllowedUser()){ - if(au.getLogin().equals(user.getLogin())){ - mine=au; - break; - } - } - - for(XdatStoredSearchGroupid ag : search.getAllowedGroups_groupid()){ - if(Groups.isMember(user,ag.getGroupid())){ - group=ag; - break; - } - } - - if(mine!=null){ - if(search.getAllowedUser().size()>1 || search.getAllowedGroups_groupid().size()>0){ - SaveItemHelper.authorizedDelete(mine.getItem(), user,this.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN,"Removed user from stored search")); - }else{ - SaveItemHelper.authorizedDelete(search.getItem(), user,this.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN,"Removed stored search")); - } - }else if(group!=null){ - if(search.getAllowedUser().size()>0 || search.getAllowedGroups_groupid().size()>1){ - SaveItemHelper.authorizedDelete(group.getItem(), user,this.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN,"Removed group from stored search")); - }else{ - SaveItemHelper.authorizedDelete(search.getItem(), user,this.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN,"Removed stored search")); - } - }else if(Roles.isSiteAdmin(user)){ - SaveItemHelper.authorizedDelete(search.getItem(), user,this.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN,"Removed stored search")); - }else{ - this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); - return; - } - } - } catch (IOException e) { - logger.error("",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } catch (SAXException e) { - logger.error("",e); - this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); - } catch (ElementNotFoundException e) { - logger.error("",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } catch (Exception e) { - logger.error("",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } - } - } + Hashtable<String, Object> tableParams = new Hashtable<>(); + tableParams.put("totalRecords", table.getNumRows()); + + return this.representTable(table, mt, tableParams, cp); + } catch (Exception e) { + logger.error("", e); + this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); + } + } else { + if (mt.equals(MediaType.TEXT_XML)) { + ItemXMLRepresentation rep = new ItemXMLRepresentation(xss.getItem(), MediaType.TEXT_XML); + if (sID.startsWith("@") || loadedFromFile) { + rep.setAllowDBAccess(false); + } + + return rep; + } + } + } + + return null; + + } + + @Override + public boolean allowDelete() { + return true; + } + + @Override + public boolean allowPut() { + return true; + } + + @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); + + boolean isNew = false; + + if (search.getId() == null || !search.getId().equals(sID)) { + search.setId(sID); + isNew = true; + } else { + XFTItem xss = search.getCurrentDBVersion(false); + if (xss == null) { + isNew = true; + } else if (this.isQueryVariableTrue("saveAs")) { + while (xss != null) { + search.setId(search.getId() + "_1"); + xss = search.getCurrentDBVersion(false); + } + isNew = true; + } + } + if (isNew && search.getTag() != null) { + CriteriaCollection cc = new CriteriaCollection("AND"); + cc.addClause("xdat:stored_search/tag", search.getTag()); + cc.addClause("xdat:stored_search/brief-description", search.getBriefDescription()); + ItemCollection result = ItemSearch.GetItems(cc, user, false); + if (result.size() > 0) { + isNew = false; + search.setId(result.getFirst().getStringProperty("ID")); + } + } + + if (!Permissions.canQuery(user, search.getRootElementName())) { + getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); + return; + } + + final boolean isPrimary = (search.getTag() != null && (search.getId().equals(search.getTag() + "_" + search.getRootElementName()))) || + (org.apache.commons.lang3.StringUtils.isNotBlank(search.getBriefDescription()) && search.getBriefDescription().equals(DisplayManager.GetInstance().getPluralDisplayNameForElement(search.getRootElementName()))); + + if (isNew && isPrimary) { + if (!Permissions.can(user, "xnat:projectData/ID", search.getTag(), SecurityManager.DELETE)) { + isNew = false; + } + } + + if (this.isQueryVariableTrue("saveAs")) { + while (search.getAllowedGroups_groupid().size() > 0) { + search.removeAllowedGroups_groupid(0); + } + + while (search.getAllowedUser().size() > 0) { + search.removeAllowedUser(0); + } + } + + boolean found = false; + for (XdatStoredSearchAllowedUser au : search.getAllowedUser()) { + if (au.getLogin().equals(user.getLogin())) { + found = true; + } + } + + for (XdatStoredSearchGroupid ag : search.getAllowedGroups_groupid()) { + if (Groups.isMember(user, ag.getGroupid())) { + found = true; + } + } + + if (!found && !isNew) { + if (search.getTag() != null && !search.getTag().equals("")) { + if (!Permissions.canEdit(user, "xnat:projectData/ID", search.getTag())) { + this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); + return; + } else { + XdatStoredSearchAllowedUser au = new XdatStoredSearchAllowedUser(user); + au.setLogin(user.getLogin()); + search.setAllowedUser(au); + } + } else { + this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); + return; + } + } + + if (isNew && !found) { + XdatStoredSearchAllowedUser au = new XdatStoredSearchAllowedUser(user); + au.setLogin(user.getLogin()); + search.setAllowedUser(au); + } + + try { + SaveItemHelper.unauthorizedSave(search, user, false, true, this.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN, (isNew) ? "Creating new stored search" : "Modified existing stored search")); + } catch (Exception e) { + logger.error("", e); + this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); + } + + } 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 { + XdatStoredSearch search = XdatStoredSearch.getXdatStoredSearchsById(sID, user, false); + + if (search != null) { + XdatStoredSearchAllowedUser mine = null; + XdatStoredSearchGroupid group = null; + + for (XdatStoredSearchAllowedUser au : search.getAllowedUser()) { + if (au.getLogin().equals(user.getLogin())) { + mine = au; + break; + } + } + + for (XdatStoredSearchGroupid ag : search.getAllowedGroups_groupid()) { + if (Groups.isMember(user, ag.getGroupid())) { + group = ag; + break; + } + } + + if (mine != null) { + if (search.getAllowedUser().size() > 1 || search.getAllowedGroups_groupid().size() > 0) { + SaveItemHelper.authorizedDelete(mine.getItem(), user, this.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN, "Removed user from stored search")); + } else { + SaveItemHelper.authorizedDelete(search.getItem(), user, this.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN, "Removed stored search")); + } + } else if (group != null) { + if (search.getAllowedUser().size() > 0 || search.getAllowedGroups_groupid().size() > 1) { + SaveItemHelper.authorizedDelete(group.getItem(), user, this.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN, "Removed group from stored search")); + } else { + SaveItemHelper.authorizedDelete(search.getItem(), user, this.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN, "Removed stored search")); + } + } else if (Roles.isSiteAdmin(user)) { + SaveItemHelper.authorizedDelete(search.getItem(), user, this.newEventInstance(EventUtils.CATEGORY.SIDE_ADMIN, "Removed stored search")); + } else { + this.getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); + } + } + } 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); + } + } + } } 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 ec3d1116b0fdbb28be085d9666766c19b6ba7d08..722a41cc4a95d8ee308d6aa571dc837865db48b7 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 @@ -10,25 +10,15 @@ */ package org.nrg.xnat.restlet.resources.search; -import java.io.IOException; -import java.io.Reader; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - +import com.noelios.restlet.ext.servlet.ServletCall; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.nrg.xdat.collections.DisplayFieldCollection.DisplayFieldNotFoundException; import org.nrg.xdat.display.DisplayFieldReferenceI; import org.nrg.xdat.display.HTMLLink; import org.nrg.xdat.display.HTMLLinkProperty; import org.nrg.xdat.display.SQLQueryField; -import org.nrg.xdat.exceptions.IllegalAccessException; import org.nrg.xdat.om.XdatCriteriaSet; import org.nrg.xdat.search.DisplaySearch; import org.nrg.xdat.security.XdatStoredSearch; @@ -39,9 +29,7 @@ import org.nrg.xft.XFTItem; import org.nrg.xft.XFTTable; import org.nrg.xft.db.MaterializedView; import org.nrg.xft.db.MaterializedViewI; -import org.nrg.xft.exception.DBPoolException; import org.nrg.xft.exception.ElementNotFoundException; -import org.nrg.xft.exception.FieldNotFoundException; import org.nrg.xft.exception.XFTInitException; import org.nrg.xft.schema.Wrappers.XMLWrapper.SAXReader; import org.nrg.xft.security.UserI; @@ -55,450 +43,438 @@ 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 org.xml.sax.SAXException; import org.xml.sax.SAXParseException; -import com.noelios.restlet.ext.servlet.ServletCall; +import java.io.Reader; +import java.util.*; public class SearchResource extends SecureResource { - static org.apache.log4j.Logger logger = Logger.getLogger(SearchResource.class); - XFTTable table= null; - Long rows=null; - String tableName=null; - - String rootElementName=null; - - Hashtable<String,Object> tableParams=new Hashtable<String,Object>(); - Map<String,Map<String,String>> cp=new LinkedHashMap<String,Map<String,String>>(); - - public SearchResource(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)); - } - - @Override - public boolean allowGet() { - return false; - } - - @Override - public boolean allowPost() { - return true; - } - - @Override - public void handlePost() { - try { - String cacheRequest = this.getQueryVariable("cache"); - boolean cache = false; - if (cacheRequest!=null && cacheRequest.equalsIgnoreCase("true")){ - cache =true; - } - - XFTItem item=null; - Representation entity = this.getRequest().getEntity(); - if(entity!=null && entity.getMediaType()!=null && entity.getMediaType().getName().equals(MediaType.MULTIPART_FORM_DATA.getName())){ - try { - org.apache.commons.fileupload.DefaultFileItemFactory factory = new org.apache.commons.fileupload.DefaultFileItemFactory(); - org.restlet.ext.fileupload.RestletFileUpload upload = new org.restlet.ext.fileupload.RestletFileUpload(factory); - - List<FileItem> items = upload.parseRequest(this.getRequest()); + private static final Logger logger = LoggerFactory.getLogger(SearchResource.class); + private XFTTable table = null; + private Long rows = null; + private String tableName = null; + + private String rootElementName = null; + + private final Hashtable<String, Object> tableParams = new Hashtable<>(); + private final Map<String, Map<String, String>> cp = new LinkedHashMap<>(); + + public SearchResource(Context context, Request request, Response response) { + super(context, request, response); + getVariants().add(new Variant(MediaType.APPLICATION_JSON)); + getVariants().add(new Variant(MediaType.TEXT_HTML)); + getVariants().add(new Variant(MediaType.TEXT_XML)); + } + + @Override + public boolean allowGet() { + return false; + } + + @Override + public boolean allowPost() { + return true; + } + + @Override + public void handlePost() { + try { + String cacheRequest = getQueryVariable("cache"); + boolean cache = false; + if (cacheRequest != null && cacheRequest.equalsIgnoreCase("true")) { + cache = true; + } + + XFTItem item = null; + Representation entity = getRequest().getEntity(); + 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(); + org.restlet.ext.fileupload.RestletFileUpload upload = new org.restlet.ext.fileupload.RestletFileUpload(factory); + + List<FileItem> items = upload.parseRequest(getRequest()); for (final FileItem fi : items) { - if(fi.getName().endsWith(".xml")){ - SAXReader reader = new SAXReader(user); - try { - item = reader.parse(fi.getInputStream()); - - if(!reader.assertValid()){ - throw reader.getErrors().get(0); - } - if (XFT.VERBOSE) - System.out.println("Loaded XML Item:" + item.getProperName()); - - if(item!=null){ - completeDocument=true; - } - } catch (SAXParseException e) { - logger.error("",e); - this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY,e.getMessage()); - throw e; - } catch (IOException e) { - logger.error("",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } catch (Exception e) { - logger.error("",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } - } - } - } catch (FileUploadException e) { + if (fi.getName().endsWith(".xml")) { + SAXReader reader = new SAXReader(user); + try { + item = reader.parse(fi.getInputStream()); + + if (!reader.assertValid()) { + throw reader.getErrors().get(0); + } + if (XFT.VERBOSE) { + System.out.println("Loaded XML Item:" + item.getProperName()); + } + + if (item != null) { + completeDocument = true; + } + } catch (SAXParseException e) { + logger.error("", e); + getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY, e.getMessage()); + throw e; + } catch (Exception e) { + logger.error("", e); + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); + } + } + } + } catch (FileUploadException e) { logger.error("", e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } - }else{ - if(entity!=null){ - Reader sax=entity.getReader(); - try { - - SAXReader reader = new SAXReader(user); - item = reader.parse(sax); - - if(!reader.assertValid()){ - throw reader.getErrors().get(0); - } - if (XFT.VERBOSE) - System.out.println("Loaded XML Item:" + item.getProperName()); - - if(item!=null){ - completeDocument=true; - } - - } catch (SAXParseException e) { - logger.error("",e); - this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY,e.getMessage()); - throw e; - } catch (IOException e) { - logger.error("",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } catch (Exception e) { - logger.error("",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } - } - } - - if(item == null || !item.instanceOf("xdat:stored_search")){ - this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); - return; - } - - XdatStoredSearch search = new XdatStoredSearch(item); - - // If a user has been manually added to a secret search, it is allowed (the criteria cannot be modified, - // which is checked in the canQueryByAllowedUser() method) - boolean allowed = canQueryByAllowedUser(search); - - // If the user is not explicitly allowed to perform a search... - if(!allowed) { - // See if the user can *implicitly* perform the search. - if (!Permissions.canQuery(user,search.getRootElementName())) { - getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); - return; + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); + } + } else { + if (entity != null) { + Reader sax = entity.getReader(); + try { + + SAXReader reader = new SAXReader(user); + item = reader.parse(sax); + + if (!reader.assertValid()) { + throw reader.getErrors().get(0); + } + if (XFT.VERBOSE) { + System.out.println("Loaded XML Item:" + item.getProperName()); + } + + if (item != null) { + completeDocument = true; + } + + } catch (SAXParseException e) { + logger.error("", e); + getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY, e.getMessage()); + throw e; + } catch (Exception e) { + logger.error("", e); + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } - } - - rootElementName=search.getRootElementName(); - - DisplaySearch ds=search.getDisplaySearch(user); - - String sortBy = this.getQueryVariable("sortBy"); - String sortOrder = this.getQueryVariable("sortOrder"); - if (sortBy != null){ - ds.setSortBy(sortBy); + } + } + + if (item == null || !item.instanceOf("xdat:stored_search")) { + getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); + return; + } + + XdatStoredSearch search = new XdatStoredSearch(item); + + // If a user has been manually added to a secret search, it is allowed (the criteria cannot be modified, + // which is checked in the canQueryByAllowedUser() method) + boolean allowed = canQueryByAllowedUser(search); + + // If the user is not explicitly allowed to perform a search... + if (!allowed) { + // See if the user can *implicitly* perform the search. + if (!Permissions.canQuery(user, search.getRootElementName())) { + getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN); + return; + } + } + + rootElementName = search.getRootElementName(); + + DisplaySearch ds = search.getDisplaySearch(user); + + String sortBy = getQueryVariable("sortBy"); + String sortOrder = getQueryVariable("sortOrder"); + if (sortBy != null) { + ds.setSortBy(sortBy); if (sortOrder != null) { - ds.setSortOrder(sortOrder); - } - } - - MaterializedViewI mv=null; - - if(search.getId()!=null && !search.getId().equals("")){ - mv = MaterializedView.getViewBySearchID(search.getId(), user,getQueryVariable(MaterializedView.CACHING_HANDLER,MaterializedView.DEFAULT_MATERIALIZED_VIEW_SERVICE_CODE)); - } - - if(mv!=null && (search.getId().startsWith("@") || this.isQueryVariableTrue("refresh"))){ - mv.delete(); - mv=null; - } - - cp=setColumnProperties(ds,user,this); - - if (!cache){ - if(mv!=null){ - table=mv.getData(null, null, null); - }else{ - ds.setPagingOn(false); - MediaType mt = this.getRequestedMediaType(); - if (mt!=null && mt.equals(SecureResource.APPLICATION_XLIST)){ - table=(XFTTable)ds.execute(new RESTHTMLPresenter(TurbineUtils.GetRelativePath(ServletCall.getRequest(this.getRequest())),null,user,sortBy),user.getLogin()); - }else{ - table=(XFTTable)ds.execute(null,user.getLogin()); - } - //table=(XFTTable)ds.execute(null,user.getLogin()); - - } - }else{ - if(mv!=null){ - if(search.getId()!=null && !search.getId().equals("") && mv.getLast_access()!=null) - tableParams.put("last_access", mv.getLast_access()); - table=mv.getData(null, null, 0); - tableName=mv.getTable_name(); - rows=mv.getSize(); - }else{ - ds.setPagingOn(false); - ds.addKeyColumn(true); - - String query = ds.getSQLQuery(null); - query = StringUtils.replace(query, "'", "*'*"); - query = StringUtils.replace(query,"*'*","''"); - - String codeToUse = getQueryVariable(MaterializedView.CACHING_HANDLER,MaterializedView.DEFAULT_MATERIALIZED_VIEW_SERVICE_CODE); - mv = MaterializedView.createView(user,codeToUse); - if(search.getId()!=null && !search.getId().equals("")) - mv.setSearch_id(search.getId()); - mv.setSearch_sql(query); - mv.setSearch_xml(item.writeToFlatString(0)); - - MaterializedView.save(mv,codeToUse); - - if(search.getId()!=null && !search.getId().equals("") && mv.getLast_access()!=null) - tableParams.put("last_access", mv.getLast_access()); - - tableName=mv.getTable_name(); - - int limit=0; - if(this.getQueryVariable("limit")!=null) - limit=Integer.valueOf(this.getQueryVariable("limit")); - table=mv.getData(null, null, limit); - rows=mv.getSize(); - } - } - - this.returnDefaultRepresentation(); - } catch (IOException e) { - logger.error("Failed POST",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } catch (SAXException e) { - logger.error("Failed POST",e); - this.getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); - } catch (ElementNotFoundException e) { - logger.error("Failed POST",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } catch (XFTInitException e) { - logger.error("Failed POST",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } catch (FieldNotFoundException e) { - logger.error("Failed POST",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } catch (DBPoolException e) { - logger.error("Failed POST",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } catch (SQLException e) { - logger.error("Failed POST",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } catch (IllegalAccessException e) { - logger.error("Failed POST",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } catch (Exception e) { - logger.error("Failed POST",e); - this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); - } - } + ds.setSortOrder(sortOrder); + } + } + + MaterializedViewI mv = null; + + if (search.getId() != null && !search.getId().equals("")) { + mv = MaterializedView.getViewBySearchID(search.getId(), user, getQueryVariable(MaterializedView.CACHING_HANDLER, MaterializedView.DEFAULT_MATERIALIZED_VIEW_SERVICE_CODE)); + } + + if (mv != null && (search.getId().startsWith("@") || isQueryVariableTrue("refresh"))) { + mv.delete(); + mv = null; + } + + cp.clear(); + cp.putAll(setColumnProperties(ds, user, this)); + + if (!cache) { + if (mv != null) { + table = mv.getData(null, null, null); + } else { + ds.setPagingOn(false); + MediaType mt = getRequestedMediaType(); + if (mt != null && mt.equals(SecureResource.APPLICATION_XLIST)) { + table = (XFTTable) ds.execute(new RESTHTMLPresenter(TurbineUtils.GetRelativePath(ServletCall.getRequest(getRequest())), null, user, sortBy), user.getLogin()); + } else { + table = (XFTTable) ds.execute(null, user.getLogin()); + } + //table=(XFTTable)ds.execute(null,user.getLogin()); + + } + } else { + if (mv != null) { + if (search.getId() != null && !search.getId().equals("") && mv.getLast_access() != null) { + tableParams.put("last_access", mv.getLast_access()); + } + table = mv.getData(null, null, 0); + tableName = mv.getTable_name(); + rows = mv.getSize(); + } else { + ds.setPagingOn(false); + ds.addKeyColumn(true); + + String query = ds.getSQLQuery(null); + query = StringUtils.replace(query, "'", "*'*"); + query = StringUtils.replace(query, "*'*", "''"); + + String codeToUse = getQueryVariable(MaterializedView.CACHING_HANDLER, MaterializedView.DEFAULT_MATERIALIZED_VIEW_SERVICE_CODE); + mv = MaterializedView.createView(user, codeToUse); + if (search.getId() != null && !search.getId().equals("")) { + mv.setSearch_id(search.getId()); + } + mv.setSearch_sql(query); + mv.setSearch_xml(item.writeToFlatString(0)); + + MaterializedView.save(mv, codeToUse); + + if (search.getId() != null && !search.getId().equals("") && mv.getLast_access() != null) { + tableParams.put("last_access", mv.getLast_access()); + } + + tableName = mv.getTable_name(); + + int limit = 0; + if (getQueryVariable("limit") != null) { + limit = Integer.valueOf(getQueryVariable("limit")); + } + table = mv.getData(null, null, limit); + rows = mv.getSize(); + } + } + + returnDefaultRepresentation(); + } catch (SAXException e) { + logger.error("Failed POST", e); + getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); + } catch (Exception e) { + logger.error("Failed POST", e); + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); + } + } @Override - public Representation represent(Variant variant) { - if(tableName!=null){ - tableParams.put("ID", tableName); - } - - if(rows!=null){ - tableParams.put("totalRecords", rows); - }else{ - tableParams.put("totalRecords", table.getNumRows()); - } - - if(rootElementName!=null){ - tableParams.put("rootElementName", rootElementName); - } - - MediaType mt = overrideVariant(variant); - - return this.representTable(table, mt, tableParams,cp); - } - - public static LinkedHashMap<String,Map<String,String>> setColumnProperties(DisplaySearch search,UserI user, SecureResource sr){ - LinkedHashMap<String,Map<String,String>> cp=new LinkedHashMap<String,Map<String,String>>(); - try { - List<DisplayFieldReferenceI> fields = search.getAllFields(""); - - //int fieldCount = visibleFields.size() + search.getInClauses().size(); + public Representation represent(Variant variant) { + if (tableName != null) { + tableParams.put("ID", tableName); + } + + if (rows != null) { + tableParams.put("totalRecords", rows); + } else { + tableParams.put("totalRecords", table.getNumRows()); + } + + if (rootElementName != null) { + tableParams.put("rootElementName", rootElementName); + } + + MediaType mt = overrideVariant(variant); + + return representTable(table, mt, tableParams, cp); + } + + @SuppressWarnings("ConstantConditions") + public static LinkedHashMap<String, Map<String, String>> setColumnProperties(DisplaySearch search, UserI user, SecureResource sr) { + LinkedHashMap<String, Map<String, String>> cp = new LinkedHashMap<>(); + try { + List<DisplayFieldReferenceI> fields = search.getAllFields(""); + + //int fieldCount = visibleFields.size() + search.getInClauses().size(); if (search.getInClauses().size() > 0) { for (int i = 0; i < search.getInClauses().size(); i++) { - cp.put("search_field"+i,new Hashtable<String,String>()); - cp.get("search_field"+i).put("header", ""); - } - } + cp.put("search_field" + i, new Hashtable<String, String>()); + cp.get("search_field" + i).put("header", ""); + } + } - //POPULATE HEADERS + //POPULATE HEADERS for (DisplayFieldReferenceI dfr : fields) { - try { + try { String id; - if(dfr.getValue()!=null && !dfr.getValue().equals("")){ - if(dfr.getValue().equals("{XDAT_USER_ID}")){ - dfr.setValue(user.getID()); - } - } + if (dfr.getValue() != null && !dfr.getValue().equals("")) { + if (dfr.getValue().equals("{XDAT_USER_ID}")) { + dfr.setValue(user.getID()); + } + } if (dfr.getElementName().equalsIgnoreCase(search.getRootElement().getFullXMLName())) { - id = dfr.getRowID().toLowerCase(); - }else{ - id = dfr.getElementSQLName().toLowerCase() + "_" + dfr.getRowID().toLowerCase(); - } - cp.put(id,new Hashtable<String,String>()); - cp.get(id).put("element_name", dfr.getElementName()); - try { - String temp_id=dfr.getDisplayField().getId(); - if(dfr.getValue()!=null) - temp_id+="="+dfr.getValue(); - cp.get(id).put("id", temp_id); - } catch (DisplayFieldNotFoundException e2) { - logger.error("",e2); - } - cp.get(id).put("xPATH", dfr.getElementName() + "." + dfr.getSortBy()); - + id = dfr.getRowID().toLowerCase(); + } else { + id = dfr.getElementSQLName().toLowerCase() + "_" + dfr.getRowID().toLowerCase(); + } + cp.put(id, new Hashtable<String, String>()); + cp.get(id).put("element_name", dfr.getElementName()); + try { + String temp_id = dfr.getDisplayField().getId(); + if (dfr.getValue() != null) { + temp_id += "=" + dfr.getValue(); + } + cp.get(id).put("id", temp_id); + } catch (DisplayFieldNotFoundException e2) { + logger.error("", e2); + } + cp.get(id).put("xPATH", dfr.getElementName() + "." + dfr.getSortBy()); + if (dfr.getHeader().equalsIgnoreCase("")) { - cp.get(id).put("header", " "); - }else{ - cp.get(id).put("header", dfr.getHeader()); - } - - String t=dfr.getType(); - if(t==null){ - try { - if(dfr.getDisplayField()!=null){ - t=dfr.getDisplayField().getDataType(); - } - } catch (DisplayFieldNotFoundException e) { - logger.error("",e); - } - } - if(t!=null){ - cp.get(id).put("type", t); - } - - try { - if(!dfr.isVisible()){ - cp.get(id).put("visible","false"); - } - } catch (DisplayFieldNotFoundException e1) { - logger.error("",e1); - } + cp.get(id).put("header", " "); + } else { + cp.get(id).put("header", dfr.getHeader()); + } + + String t = dfr.getType(); + if (t == null) { + try { + if (dfr.getDisplayField() != null) { + t = dfr.getDisplayField().getDataType(); + } + } catch (DisplayFieldNotFoundException e) { + logger.error("", e); + } + } + if (t != null) { + cp.get(id).put("type", t); + } + + try { + if (!dfr.isVisible()) { + cp.get(id).put("visible", "false"); + } + } catch (DisplayFieldNotFoundException e1) { + logger.error("", e1); + } if (dfr.getHTMLLink() != null && sr.getQueryVariable("format") != null && sr.getQueryVariable("format").equalsIgnoreCase("json")) { - cp.get(id).put("clickable", "true"); - HTMLLink link = dfr.getHTMLLink(); - + cp.get(id).put("clickable", "true"); + HTMLLink link = dfr.getHTMLLink(); + StringBuilder linkProps = new StringBuilder("["); - int propCounter=0; - for(HTMLLinkProperty prop: link.getProperties()){ - if(propCounter++>0)linkProps.append(","); - linkProps.append("{"); - linkProps.append("\"name\":\""); - linkProps.append(prop.getName()).append("\""); - linkProps.append(",\"value\":\""); - String v =prop.getValue(); - v = StringUtils.replace(v,"@WEBAPP",TurbineUtils.GetRelativePath(ServletCall.getRequest(sr.getRequest())) + "/"); - - linkProps.append(v).append("\""); + int propCounter = 0; + for (HTMLLinkProperty prop : link.getProperties()) { + if (propCounter++ > 0) { + linkProps.append(","); + } + linkProps.append("{"); + linkProps.append("\"name\":\""); + linkProps.append(prop.getName()).append("\""); + linkProps.append(",\"value\":\""); + String v = prop.getValue(); + v = StringUtils.replace(v, "@WEBAPP", TurbineUtils.GetRelativePath(ServletCall.getRequest(sr.getRequest())) + "/"); + + linkProps.append(v).append("\""); if (prop.getInsertedValues().size() > 0) { - linkProps.append(",\"inserts\":["); - int valueCounter=0; + linkProps.append(",\"inserts\":["); + int valueCounter = 0; for (Map.Entry<String, String> entry : prop.getInsertedValues().entrySet()) { - if(valueCounter++>0)linkProps.append(","); - linkProps.append("{\"name\":\""); - linkProps.append(entry.getKey()).append("\""); - linkProps.append(",\"value\":\""); - - String insert_value = entry.getValue(); - if (insert_value.startsWith("@WHERE")){ + if (valueCounter++ > 0) { + linkProps.append(","); + } + linkProps.append("{\"name\":\""); + linkProps.append(entry.getKey()).append("\""); + linkProps.append(",\"value\":\""); + + String insert_value = entry.getValue(); + if (insert_value.startsWith("@WHERE")) { try { - if (dfr.getDisplayField() instanceof SQLQueryField){ - Object insertValue = dfr.getValue(); + if (dfr.getDisplayField() instanceof SQLQueryField) { + Object insertValue = dfr.getValue(); if (insertValue == null) { - insertValue = "NULL"; - }else{ + insertValue = "NULL"; + } else { if (insertValue.toString().contains(",")) { - insert_value = insert_value.substring(6); - try { - Integer i = Integer.parseInt(insert_value); - ArrayList<String> al = XftStringUtils.CommaDelimitedStringToArrayList(insertValue.toString()); - insertValue =al.get(i); - } catch (Throwable e) { - logger.error("",e); - } - } - } + insert_value = insert_value.substring(6); + //noinspection Duplicates + try { + Integer i = Integer.parseInt(insert_value); + ArrayList<String> al = XftStringUtils.CommaDelimitedStringToArrayList(insertValue.toString()); + insertValue = al.get(i); + } catch (Throwable e) { + logger.error("", e); + } + } + } linkProps.append("@").append(insertValue); - } - } catch (DisplayFieldNotFoundException e) { - logger.error("",e); - } - }else{ + } + } catch (DisplayFieldNotFoundException e) { + logger.error("", e); + } + } else { if (!dfr.getElementName().equalsIgnoreCase(search.getRootElement().getFullXMLName())) { - insert_value = dfr.getElementSQLName().toLowerCase() + "_" + insert_value.toLowerCase(); - }else{ - insert_value=insert_value.toLowerCase(); - } - if(cp.get(insert_value)==null){ - cp.put(insert_value,new Hashtable<String,String>()); - + insert_value = dfr.getElementSQLName().toLowerCase() + "_" + insert_value.toLowerCase(); + } else { + insert_value = insert_value.toLowerCase(); + } + if (cp.get(insert_value) == null) { + cp.put(insert_value, new Hashtable<String, String>()); + if (!dfr.getElementName().equalsIgnoreCase(search.getRootElement().getFullXMLName())) { - cp.get(insert_value).put("xPATH", dfr.getElementName() + "." + insert_value); - }else{ - cp.get(insert_value).put("xPATH", insert_value); + cp.get(insert_value).put("xPATH", dfr.getElementName() + "." + insert_value); + } else { + cp.get(insert_value).put("xPATH", insert_value); } - } - - linkProps.append(insert_value); + } + + linkProps.append(insert_value); } - linkProps.append("\"}"); - } - linkProps.append("]"); - } - linkProps.append("}"); - } - linkProps.append("]"); - - cp.get(id).put("linkProps", linkProps.toString()); - } - + linkProps.append("\"}"); + } + linkProps.append("]"); + } + linkProps.append("}"); + } + linkProps.append("]"); + + cp.get(id).put("linkProps", linkProps.toString()); + } + if (dfr.isImage()) { - cp.get(id).put("imgRoot", TurbineUtils.GetRelativePath(ServletCall.getRequest(sr.getRequest())) + "/"); - } - } catch (XFTInitException | ElementNotFoundException e) { - logger.error("",e); - } + cp.get(id).put("imgRoot", TurbineUtils.GetRelativePath(ServletCall.getRequest(sr.getRequest())) + "/"); + } + } catch (XFTInitException | ElementNotFoundException e) { + logger.error("", e); + } + } - } - - cp.put("quarantine_status",new Hashtable<String,String>()); - } catch (ElementNotFoundException | XFTInitException e) { - logger.error("",e); - } + cp.put("quarantine_status", new Hashtable<String, String>()); + } catch (ElementNotFoundException | XFTInitException e) { + logger.error("", e); + } - return cp; - } + return cp; + } private boolean canQueryByAllowedUser(final XdatStoredSearch search) { - boolean allowed=false; - if(StringUtils.isNotBlank(search.getId())) - { + boolean allowed = false; + if (StringUtils.isNotBlank(search.getId())) { //need to check against unmodified stored search final org.nrg.xdat.om.XdatStoredSearch stored = XdatStoredSearch.getXdatStoredSearchsById(search.getId(), user, true); //if the user was added to the search - if(stored != null && stored.hasAllowedUser(user.getUsername())){ + if (stored != null && stored.hasAllowedUser(user.getUsername())) { //confirm it has a WHERE clause and hasn't been modified - if(XdatCriteriaSet.compareCriteriaSets(stored.getSearchWhere(), search.getSearchWhere())){ - allowed=true; + if (XdatCriteriaSet.compareCriteriaSets(stored.getSearchWhere(), search.getSearchWhere())) { + allowed = true; } } }