From 76d96715f5222d70ee06c2a68a13228e1f27c2fe Mon Sep 17 00:00:00 2001 From: Will Ezell Date: Wed, 27 Dec 2017 12:00:34 -0500 Subject: [PATCH] Issue 13192 edit mode cleanup (#13193) * #13164 untested work * #13164 removes multitreefactory from hibernate, includes treefactory * #13164 removes tree from inode and category hibernate * #13164 removing old code * core#13192 edit mode parsing * #13192 edit mode parsing * #13192 contenttool * #13194 some untested fixes * #13194 use map.getOrDefault methods * #13194 loadObjectResults * #13194 jenkins feedback fixes * #13194 fixes the red * #13192 Container+Content Resource * #13192 adding widget support * #13192 adding widget support * #13192 container pulling * Add lang variables and update edit contentlet save and cancel functions to report back to ng * #13192 multitree updates * #13192 removing templatecontainers import * #13192 removing templatecontainers from hibernate * #13192 allow multitree to be imported * #13192 fixes import * #13192 copying velocity work to new folder * Update ContentSelector dojo widget to make it work with ng * #13192 kinda running * #13192 look ma, no red * Fix ContentSelector select event * Fix edit contentlet requires fields * #13192 live mode working * #13192 slow and steady * #13192 live mode * #13192 live mode working * #13192 preview mode working exclaimation point * #13192 readding the integration tests * #13192 ContainerResourceWorking * Merge remote-tracking branch 'remotes/origin/master' into issue-13192-edit-mode-cleanup # Conflicts: # dotCMS/src/main/java/com/dotmarketing/util/TaskLocatorUtil.java * #13192 CloseDB aspect fixed * #13192 unable to save pages * #13192 white space cleanup --- .../ajax/RemotePublishAjaxActionTest.java | 16 +- .../velocity/VelocityMacroCacheTest.java | 4 +- .../velocity/VelocityUtilTest.java | 4 +- .../velocity}/viewtools/BrowserAPITest.java | 2 +- .../viewtools/LanguageWebAPITest.java | 2 +- .../viewtools/content/ContentToolTest.java | 2 +- .../viewtools/navigation/NavToolTest.java | 21 +- .../factories/MultiTreeFactoryTest.java | 161 +++ .../com/dotmarketing/filters/FiltersTest.java | 12 +- .../business/ContentletAPITest.java | 25 +- .../business/ContentletCheckInTest.java | 49 + .../folders/business/FolderAPITest.java | 6 +- .../runtime/parser/node/SimpleNodeTest.java | 2 +- .../dotcms/aspects/aspectj/CloseDBAspect.java | 45 + .../CloseDBMethodInterceptor.java | 47 + .../java/com/dotcms/business/CloseDB.java | 20 + .../business/ESContentletAPIImpl.java | 111 +- .../business/ContentTypeCache2Impl.java | 1 + .../contenttype/business/FieldAPIImpl.java | 53 +- .../business/FieldFactoryImpl.java | 10 +- .../component/VelocityFieldFormRenderer.java | 2 +- ...ltFrontEndLoginRequiredWebInterceptor.java | 5 +- .../publisher/util/DependencyManager.java | 2 +- .../dotcms/rendering/velocity/Constants.java | 5 + .../velocity/directive/ContentletDetail.java | 34 +- .../velocity/directive/DotDirective.java | 27 +- .../velocity/directive/DotParse.java | 30 +- .../velocity/directive/FixBreaks.java | 4 +- .../velocity/directive/ParseContainer.java | 20 +- .../velocity/directive/RenderParams.java | 15 +- .../MethodExceptionEventHandlerImpl.java | 8 +- .../events/NullSetEventHandlerImpl.java | 2 +- .../velocity/services/ContainerLoader.java | 261 ++++ .../velocity/services/ContentTypeLoader.java | 303 ++++ .../velocity/services/ContentletLoader.java | 851 ++++++++++++ .../velocity/services/DotLoader.java | 80 ++ .../velocity/services/DotResourceCache.java | 220 +++ .../velocity/services/DotResourceLoader.java | 158 +++ .../velocity/services/FieldLoader.java | 99 ++ .../velocity/services/PageContextBuilder.java | 294 ++++ .../velocity/services/PageLoader.java | 219 +++ .../velocity/services/SiteLoader.java | 108 ++ .../velocity/services/StringifyObject.java | 104 ++ .../velocity/services/TemplateLoader.java | 102 ++ .../velocity/services/VTLLoader.java | 145 ++ .../services/VelocityPrettyWriter.java | 69 + .../velocity/services/VelocityType.java | 37 + .../velocity/servlet/VelocityLiveServlet.java | 391 ++++++ .../servlet/VelocityPreviewServlet.java | 359 +++++ .../velocity/util/VelocityProfiler.java | 28 + .../rendering/velocity/util/VelocityUtil.java | 607 ++++++++ .../velocity}/viewtools/BrowserAPI.java | 2 +- .../velocity}/viewtools/CASTool.java | 2 +- .../velocity}/viewtools/CMSUsersWebAPI.java | 2 +- .../velocity}/viewtools/CategoriesWebAPI.java | 2 +- .../velocity}/viewtools/CommentsWebAPI.java | 2 +- .../velocity}/viewtools/ContainerWebAPI.java | 2 +- .../velocity}/viewtools/ContentsWebAPI.java | 20 +- .../velocity}/viewtools/CryptWebAPI.java | 2 +- .../velocity}/viewtools/DateViewWebAPI.java | 5 +- .../viewtools/DotCMSDocumentationAPI.java | 2 +- .../viewtools/DotCMSMacroWebAPI.java | 3 +- .../velocity}/viewtools/DotLoggerTool.java | 2 +- .../velocity}/viewtools/DotRenderTool.java | 2 +- .../velocity}/viewtools/DotTemplateTool.java | 7 +- .../velocity}/viewtools/ESContentTool.java | 63 +- .../velocity}/viewtools/FileTool.java | 3 +- .../velocity}/viewtools/FolderWebAPI.java | 2 +- .../viewtools/GlobalVariableWebAPI.java | 3 +- .../velocity}/viewtools/GlossaryWebAPI.java | 3 +- .../velocity}/viewtools/JSONTool.java | 3 +- .../viewtools/LangBackendWebAPI.java | 3 +- .../velocity}/viewtools/LanguageWebAPI.java | 3 +- .../velocity}/viewtools/MailerTool.java | 3 +- .../velocity}/viewtools/MarkdownTool.java | 11 +- .../velocity}/viewtools/MessagesTools.java | 19 +- .../velocity}/viewtools/PersonaTool.java | 7 +- .../velocity}/viewtools/PluginWebAPI.java | 6 +- .../velocity}/viewtools/RequestWrapper.java | 3 +- .../viewtools/SQLResultsViewTool.java | 3 +- .../velocity}/viewtools/StringsWebApi.java | 3 +- .../velocity}/viewtools/StructuresWebAPI.java | 3 +- .../viewtools/SubmitContentWebAPI.java | 3 +- .../velocity}/viewtools/TagsWebAPI.java | 2 +- .../velocity}/viewtools/UserAgentTool.java | 3 +- .../viewtools/UserCommentsWebAPI.java | 3 +- .../velocity/viewtools/VelocityWebUtil.java | 151 ++ .../rendering/velocity}/viewtools/WebAPI.java | 21 +- .../velocity}/viewtools/WebsiteWebAPI.java | 2 +- .../velocity}/viewtools/WikiTool.java | 3 +- .../velocity}/viewtools/WorkflowTool.java | 2 +- .../velocity}/viewtools/XmlTool.java | 10 +- .../velocity}/viewtools/XsltTool.java | 6 +- .../velocity}/viewtools/XssWebAPI.java | 2 +- .../viewtools/bean/XSLTranformationDoc.java | 2 +- .../velocity}/viewtools/bean/XmlToolDoc.java | 6 +- .../cache/XSLTransformationCache.java | 4 +- .../viewtools/cache/XmlToolCache.java | 5 +- .../viewtools/content/BinaryMap.java | 2 +- .../viewtools/content/CheckboxMap.java | 2 +- .../viewtools/content/ContentMap.java | 31 +- .../viewtools/content/ContentTool.java | 26 +- .../viewtools/content/FileAssetMap.java | 3 +- .../viewtools/content/MultiSelectMap.java | 2 +- .../content/PaginatedContentList.java | 3 +- .../velocity}/viewtools/content/RadioMap.java | 3 +- .../viewtools/content/SelectMap.java | 2 +- .../velocity}/viewtools/content/TagList.java | 2 +- .../viewtools/content/util/ContentUtils.java | 6 +- .../viewtools/navigation/NavResult.java | 374 +++++ .../navigation/NavResultHydrated.java | 183 +++ .../viewtools/navigation/NavTool.java | 301 ++++ .../viewtools/navigation/NavToolCache.java | 2 +- .../navigation/NavToolCacheImpl.java | 2 +- .../velocity}/viewtools/util/ClassUtils.java | 2 +- .../viewtools/util/ConversionUtils.java | 2 +- .../java/com/dotcms/rest/ContentResource.java | 2 +- .../api/v1/container/ContainerResource.java | 403 +++++- .../v1/container/ContainerResourceHelper.java | 14 + .../content/ContentRelationshipsHelper.java | 2 +- .../rest/api/v1/page/ContainerView.java | 2 +- .../rest/api/v1/page/ContentletMixIn.java | 2 +- .../dotcms/rest/api/v1/page/JsonMapper.java | 2 +- .../com/dotcms/rest/api/v1/page/PageForm.java | 2 +- .../dotcms/rest/api/v1/page/PageResource.java | 47 +- .../rest/api/v1/page/PageResourceHelper.java | 66 +- .../com/dotcms/rest/api/v1/page/PageView.java | 2 +- .../rest/api/v1/page/PermissionableMixIn.java | 2 +- .../ESContentResourcePortlet.java | 22 +- .../java/com/dotcms/spring/web/DotView.java | 7 +- .../translate/GoogleTranslationService.java | 2 +- .../com/dotcms/webdav/FileContentService.java | 35 + .../webdav/FileSystemResourceFactory.java | 264 ++++ .../dotcms/webdav/FsDirectoryResource.java | 263 ++++ .../com/dotcms/webdav/FsFileResource.java | 133 ++ .../dotcms/webdav/FsMemoryLockManager.java | 141 ++ .../java/com/dotcms/webdav/FsResource.java | 162 +++ .../webdav/SimpleFileContentService.java | 49 + .../java/com/dotmarketing/beans/Inode.java | 14 +- .../com/dotmarketing/beans/MultiTree.java | 181 ++- .../beans/TemplateContainers.java | 32 - .../business/BaseWebAssetAPI.java | 16 +- .../dotmarketing/business/CacheLocator.java | 23 +- .../business/IdentifierFactoryImpl.java | 8 +- .../business/PermissionBitFactoryImpl.java | 4 +- .../cache/provider/redis/RedisProvider.java | 2 +- .../dotmarketing/business/web/HostWebAPI.java | 2 + .../business/web/HostWebAPIImpl.java | 32 +- .../business/web/LanguageWebAPIImpl.java | 4 +- .../cache/LegacyContentTypeCacheImpl.java | 2 + .../cms/comment/action/CommentsAction.java | 2 +- .../cms/urlmap/filters/URLMapFilter.java | 9 +- .../db/test/DataSourcesForTesting.java | 2 +- .../factories/DBTreeTransformer.java | 52 + .../dotmarketing/factories/EmailFactory.java | 5 +- .../dotmarketing/factories/MultiTreeAPI.java | 84 ++ .../factories/MultiTreeFactory.java | 1005 ++++---------- .../factories/PublishFactory.java | 31 +- .../dotmarketing/factories/TreeFactory.java | 715 +++++----- .../factories/WebAssetFactory.java | 23 +- .../com/dotmarketing/filters/CMSFilter.java | 64 +- .../com/dotmarketing/filters/CMSUrlUtil.java | 28 +- .../filters/ThreadNameFilter.java | 4 +- .../filters/TimeMachineFilter.java | 8 +- .../struts/DotCustomLoginPostAction.java | 8 +- .../portlets/browser/ajax/BrowserAjax.java | 5 +- .../portlets/calendar/ajax/CalendarAjax.java | 4 +- .../portlets/categories/model/Category.java | 22 +- .../action/ViewCMSMaintenanceAction.java | 424 +----- .../ajax/CMSMaintenanceAjax.java | 361 +---- .../action/EditContainerAction.java | 40 +- .../containers/business/ContainerAPI.java | 29 +- .../containers/business/ContainerAPIImpl.java | 77 +- .../business/ContainerFactoryImpl.java | 10 +- .../factories/ContainerFactory.java | 10 +- .../action/OrderContentletAction.java | 158 --- .../contentlet/ajax/ContentletAjax.java | 7 +- .../business/ContentletFactory.java | 6 + .../business/web/ContentletWebAPIImpl.java | 4 +- .../director/action/DirectorAction.java | 12 +- .../folders/business/FolderFactoryImpl.java | 10 +- .../portlets/form/business/FormAPIImpl.java | 13 +- .../bussiness/HostVariableAPIImpl.java | 15 +- .../business/HTMLPageAssetAPIImpl.java | 30 +- .../action/PreviewHTMLPageAction.java | 8 +- .../portlets/links/action/EditLinkAction.java | 20 +- .../links/business/MenuLinkFactoryImpl.java | 2 + .../portlets/links/factories/LinkFactory.java | 2 + .../portlets/rules/business/RulesEngine.java | 74 + .../VisitorOperatingSystemConditionlet.java | 4 +- .../structure/action/EditFieldAction.java | 25 +- .../structure/action/EditStructureAction.java | 22 +- .../templates/action/EditTemplateAction.java | 35 +- .../action/PublishTemplatesAction.java | 13 +- .../templates/business/TemplateAPI.java | 2 +- .../templates/business/TemplateAPIImpl.java | 10 +- .../templates/business/TemplateFactory.java | 13 +- .../business/TemplateFactoryImpl.java | 61 +- .../quartz/job/ServerHeartbeatJob.java | 17 +- .../quartz/job/UpdateRatingThread.java | 26 +- .../services/ContainerServices.java | 339 ----- .../services/ContentletMapServices.java | 524 ------- .../services/ContentletServices.java | 593 -------- .../dotmarketing/services/FieldServices.java | 104 -- .../dotmarketing/services/HostServices.java | 120 -- .../dotmarketing/services/PageServices.java | 421 ------ .../services/StructureServices.java | 189 --- .../services/TemplateServices.java | 122 -- .../servlets/BinaryExporterServlet.java | 31 +- .../servlets/ImportExportXMLServlet.java | 518 ------- .../dotmarketing/servlets/InitServlet.java | 2 +- .../dotmarketing/servlets/ShortyServlet.java | 17 +- .../servlets/SpeedyAssetServlet.java | 10 +- ...8CreateTagStorageFieldOnHostStructure.java | 7 +- .../runonce/Task04315UpdateMultiTreePK.java | 127 ++ .../dotmarketing/util/ConvertToPOJOUtil.java | 268 ++++ .../dotmarketing/util/ImportExportUtil.java | 112 +- .../java/com/dotmarketing/util/Logger.java | 6 +- .../java/com/dotmarketing/util/PageMode.java | 83 ++ .../util/PageRequestModeUtil.java | 34 +- .../dotmarketing/util/TaskLocatorUtil.java | 1 + .../com/dotmarketing/util/UtilMethods.java | 90 +- .../dotmarketing/util/VelocityProfiler.java | 22 +- .../com/dotmarketing/util/VelocityUtil.java | 612 +-------- .../java/com/dotmarketing/util/WebKeys.java | 5 + .../velocity/ClientVelocityServlet.java | 96 -- .../velocity/DotResourceCache.java | 199 --- .../velocity/DotResourceLoader.java | 590 -------- .../velocity/VelocityServlet.java | 1219 ----------------- .../viewtools/VelocityWebUtil.java | 154 --- .../viewtools/navigation/NavResult.java | 372 ----- .../viewtools/navigation/NavTool.java | 264 ---- .../dotmarketing/webdav/DotWebdavHelper.java | 18 +- .../portal/struts/PortalRequestProcessor.java | 5 +- .../java/org/apache/velocity/Template.java | 8 +- .../velocity/runtime/VelocimacroFactory.java | 3 +- .../runtime/resource/ContentResource.java | 4 +- .../velocity/runtime/resource/Resource.java | 4 +- .../runtime/resource/ResourceManagerImpl.java | 3 +- .../velocity/tools/generic/SortTool.java | 2 +- .../com/dotmarketing/beans/DotCMSId.hbm.xml | 13 - .../com/dotmarketing/beans/DotCMSSeq.hbm.xml | 13 - .../runtime/defaults/directive.properties | 8 +- dotCMS/src/main/resources/system.properties | 107 +- dotCMS/src/main/webapp/META-INF/context.xml | 2 +- .../WEB-INF/messages/Language.properties | 2 + dotCMS/src/main/webapp/WEB-INF/toolbox.xml | 86 +- .../static/preview_mode/content_controls.vtl | 2 +- dotCMS/src/main/webapp/WEB-INF/web.xml | 18 +- .../js/dotcms/dijit/form/ContentSelector.js | 19 +- .../js/dotcms/dijit/form/ContentSelector.jsp | 61 +- .../dijit/form/ContentSelectorContent.jsp | 61 + .../dijit/form/ContentSelectorNoDialog.jsp | 3 + .../webapp/html/ng-contentlet-selector.html | 111 ++ .../cmsmaintenance/view_cms_maintenance.jsp | 2 +- .../portlet/ext/common/page_preview_popup.jsp | 2 +- .../ext/contentlet/edit_contentlet.jsp | 2 +- .../ext/contentlet/edit_contentlet_js_inc.jsp | 33 +- .../GoogleTranslationServiceTest.java | 4 +- 259 files changed, 10002 insertions(+), 9951 deletions(-) rename dotCMS/src/integration-test/java/com/dotcms/{ => rendering}/velocity/VelocityMacroCacheTest.java (95%) rename dotCMS/src/integration-test/java/com/dotcms/{ => rendering}/velocity/VelocityUtilTest.java (95%) rename dotCMS/src/integration-test/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/BrowserAPITest.java (98%) rename dotCMS/src/integration-test/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/LanguageWebAPITest.java (99%) rename dotCMS/src/integration-test/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/content/ContentToolTest.java (98%) rename dotCMS/src/integration-test/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/navigation/NavToolTest.java (90%) create mode 100644 dotCMS/src/integration-test/java/com/dotmarketing/factories/MultiTreeFactoryTest.java create mode 100644 dotCMS/src/integration-test/java/com/dotmarketing/portlets/contentlet/business/ContentletCheckInTest.java create mode 100644 dotCMS/src/main/java/com/dotcms/aspects/aspectj/CloseDBAspect.java create mode 100644 dotCMS/src/main/java/com/dotcms/aspects/interceptors/CloseDBMethodInterceptor.java create mode 100644 dotCMS/src/main/java/com/dotcms/business/CloseDB.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/Constants.java rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering}/velocity/directive/ContentletDetail.java (61%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering}/velocity/directive/DotDirective.java (89%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering}/velocity/directive/DotParse.java (83%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering}/velocity/directive/FixBreaks.java (95%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering}/velocity/directive/ParseContainer.java (58%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering}/velocity/directive/RenderParams.java (77%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering}/velocity/events/MethodExceptionEventHandlerImpl.java (96%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering}/velocity/events/NullSetEventHandlerImpl.java (82%) create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/ContainerLoader.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/ContentTypeLoader.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/ContentletLoader.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/DotLoader.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/DotResourceCache.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/DotResourceLoader.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/FieldLoader.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/PageContextBuilder.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/PageLoader.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/SiteLoader.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/StringifyObject.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/TemplateLoader.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/VTLLoader.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/VelocityPrettyWriter.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/services/VelocityType.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/servlet/VelocityLiveServlet.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/servlet/VelocityPreviewServlet.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/util/VelocityProfiler.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/util/VelocityUtil.java rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/BrowserAPI.java (99%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/CASTool.java (96%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/CMSUsersWebAPI.java (96%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/CategoriesWebAPI.java (97%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/CommentsWebAPI.java (97%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/ContainerWebAPI.java (93%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/ContentsWebAPI.java (97%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/CryptWebAPI.java (90%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/DateViewWebAPI.java (89%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/DotCMSDocumentationAPI.java (87%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/DotCMSMacroWebAPI.java (99%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/DotLoggerTool.java (97%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/DotRenderTool.java (79%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/DotTemplateTool.java (97%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/ESContentTool.java (66%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/FileTool.java (97%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/FolderWebAPI.java (95%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/GlobalVariableWebAPI.java (97%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/GlossaryWebAPI.java (99%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/JSONTool.java (99%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/LangBackendWebAPI.java (91%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/LanguageWebAPI.java (96%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/MailerTool.java (98%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/MarkdownTool.java (93%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/MessagesTools.java (86%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/PersonaTool.java (94%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/PluginWebAPI.java (97%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/RequestWrapper.java (99%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/SQLResultsViewTool.java (99%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/StringsWebApi.java (94%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/StructuresWebAPI.java (99%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/SubmitContentWebAPI.java (98%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/TagsWebAPI.java (94%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/UserAgentTool.java (97%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/UserCommentsWebAPI.java (92%) create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/VelocityWebUtil.java rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/WebAPI.java (95%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/WebsiteWebAPI.java (98%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/WikiTool.java (99%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/WorkflowTool.java (99%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/XmlTool.java (94%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/XsltTool.java (97%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/XssWebAPI.java (96%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/bean/XSLTranformationDoc.java (92%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/bean/XmlToolDoc.java (85%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/cache/XSLTransformationCache.java (93%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/cache/XmlToolCache.java (92%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/content/BinaryMap.java (99%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/content/CheckboxMap.java (96%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/content/ContentMap.java (94%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/content/ContentTool.java (96%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/content/FileAssetMap.java (97%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/content/MultiSelectMap.java (96%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/content/PaginatedContentList.java (95%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/content/RadioMap.java (96%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/content/SelectMap.java (96%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/content/TagList.java (94%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/content/util/ContentUtils.java (99%) create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavResult.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavResultHydrated.java create mode 100644 dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavTool.java rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/navigation/NavToolCache.java (89%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/navigation/NavToolCacheImpl.java (98%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/util/ClassUtils.java (96%) rename dotCMS/src/main/java/com/{dotmarketing => dotcms/rendering/velocity}/viewtools/util/ConversionUtils.java (96%) create mode 100644 dotCMS/src/main/java/com/dotcms/rest/api/v1/container/ContainerResourceHelper.java create mode 100644 dotCMS/src/main/java/com/dotcms/webdav/FileContentService.java create mode 100644 dotCMS/src/main/java/com/dotcms/webdav/FileSystemResourceFactory.java create mode 100644 dotCMS/src/main/java/com/dotcms/webdav/FsDirectoryResource.java create mode 100644 dotCMS/src/main/java/com/dotcms/webdav/FsFileResource.java create mode 100644 dotCMS/src/main/java/com/dotcms/webdav/FsMemoryLockManager.java create mode 100644 dotCMS/src/main/java/com/dotcms/webdav/FsResource.java create mode 100644 dotCMS/src/main/java/com/dotcms/webdav/SimpleFileContentService.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/beans/TemplateContainers.java create mode 100644 dotCMS/src/main/java/com/dotmarketing/factories/DBTreeTransformer.java create mode 100644 dotCMS/src/main/java/com/dotmarketing/factories/MultiTreeAPI.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/action/OrderContentletAction.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/services/ContainerServices.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/services/ContentletMapServices.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/services/ContentletServices.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/services/FieldServices.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/services/HostServices.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/services/PageServices.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/services/StructureServices.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/services/TemplateServices.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/servlets/ImportExportXMLServlet.java create mode 100644 dotCMS/src/main/java/com/dotmarketing/startup/runonce/Task04315UpdateMultiTreePK.java create mode 100644 dotCMS/src/main/java/com/dotmarketing/util/ConvertToPOJOUtil.java create mode 100644 dotCMS/src/main/java/com/dotmarketing/util/PageMode.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/velocity/ClientVelocityServlet.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/velocity/DotResourceCache.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/velocity/DotResourceLoader.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/velocity/VelocityServlet.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/viewtools/VelocityWebUtil.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/viewtools/navigation/NavResult.java delete mode 100644 dotCMS/src/main/java/com/dotmarketing/viewtools/navigation/NavTool.java create mode 100644 dotCMS/src/main/webapp/html/js/dotcms/dijit/form/ContentSelectorContent.jsp create mode 100644 dotCMS/src/main/webapp/html/js/dotcms/dijit/form/ContentSelectorNoDialog.jsp create mode 100644 dotCMS/src/main/webapp/html/ng-contentlet-selector.html diff --git a/dotCMS/src/functional-test/java/com/dotcms/publisher/ajax/RemotePublishAjaxActionTest.java b/dotCMS/src/functional-test/java/com/dotcms/publisher/ajax/RemotePublishAjaxActionTest.java index 5a30f71052c2..926ad5c1cfb8 100644 --- a/dotCMS/src/functional-test/java/com/dotcms/publisher/ajax/RemotePublishAjaxActionTest.java +++ b/dotCMS/src/functional-test/java/com/dotcms/publisher/ajax/RemotePublishAjaxActionTest.java @@ -388,7 +388,7 @@ public void push_archived_issue5086 () throws Exception { Identifier containerIdentifier = APILocator.getIdentifierAPI().find(containerId); Identifier contenletIdentifier = APILocator.getIdentifierAPI().find(contentlet); MultiTree multiTree = MultiTreeFactory.getMultiTree(htmlPageIdentifier, containerIdentifier,contenletIdentifier); - int contentletCount = MultiTreeFactory.getMultiTree(workinghtmlPageAsset.getInode()).size(); + int contentletCount = MultiTreeFactory.getMultiTrees(workinghtmlPageAsset.getIdentifier()).size(); if (!InodeUtils.isSet(multiTree.getParent1()) && !InodeUtils.isSet(multiTree.getParent2()) && !InodeUtils.isSet(multiTree.getChild())) { MultiTree mTree = new MultiTree(htmlPageIdentifier.getInode(), containerIdentifier.getInode(), @@ -400,7 +400,7 @@ public void push_archived_issue5086 () throws Exception { * Relating content to archived page */ multiTree = MultiTreeFactory.getMultiTree(htmlPageIdentifier, containerIdentifier,contenletIdentifier); - contentletCount = MultiTreeFactory.getMultiTree(workinghtmlPageAsset.getInode()).size(); + contentletCount = MultiTreeFactory.getMultiTrees(workinghtmlPageAsset.getIdentifier()).size(); if (!InodeUtils.isSet(multiTree.getParent1()) && !InodeUtils.isSet(multiTree.getParent2()) && !InodeUtils.isSet(multiTree.getChild())) { MultiTree mTree = new MultiTree(htmlPageIdentifier.getInode(), containerIdentifier.getInode(), @@ -544,8 +544,8 @@ public void push_archived_issue5086 () throws Exception { } - Assert.assertEquals(0,MultiTreeFactory.getMultiTree(workinghtmlPageAsset.getInode()).size()); - Assert.assertEquals(0,MultiTreeFactory.getMultiTreeByChild(contentlet.getIdentifier()).size()); + Assert.assertEquals(0,MultiTreeFactory.getMultiTrees(workinghtmlPageAsset.getInode()).size()); + Assert.assertEquals(0,MultiTreeFactory.getMultiTreesByChild(contentlet.getIdentifier()).size()); folder = APILocator.getFolderAPI().findFolderByPath(folderPath, host, systemUser, false); assertTrue(!UtilMethods.isSet(folder.getInode())); @@ -708,7 +708,7 @@ public void push_container_issue5189 () throws Exception { Identifier containerIdentifier = APILocator.getIdentifierAPI().find(containerId); Identifier contenletIdentifier1 = APILocator.getIdentifierAPI().find(contentlet1); MultiTree multiTree = MultiTreeFactory.getMultiTree(htmlPageIdentifier, containerIdentifier,contenletIdentifier1); - int contentletCount = MultiTreeFactory.getMultiTree(htmlPageIdentifier).size(); + int contentletCount = MultiTreeFactory.getMultiTrees(htmlPageIdentifier).size(); if (!InodeUtils.isSet(multiTree.getParent1()) && !InodeUtils.isSet(multiTree.getParent2()) && !InodeUtils.isSet(multiTree.getChild())) { MultiTree mTree = new MultiTree(htmlPageIdentifier.getInode(), containerIdentifier.getInode(), @@ -718,7 +718,7 @@ public void push_container_issue5189 () throws Exception { Identifier contenletIdentifier2 = APILocator.getIdentifierAPI().find(contentlet2); multiTree = MultiTreeFactory.getMultiTree(htmlPageIdentifier, containerIdentifier,contenletIdentifier2); - contentletCount = MultiTreeFactory.getMultiTree(htmlPageIdentifier).size(); + contentletCount = MultiTreeFactory.getMultiTrees(htmlPageIdentifier).size(); if (!InodeUtils.isSet(multiTree.getParent1()) && !InodeUtils.isSet(multiTree.getParent2()) && !InodeUtils.isSet(multiTree.getChild())) { MultiTree mTree = new MultiTree(htmlPageIdentifier.getInode(), containerIdentifier.getInode(), @@ -728,7 +728,7 @@ public void push_container_issue5189 () throws Exception { Identifier contenletIdentifier3 = APILocator.getIdentifierAPI().find(contentlet3); multiTree = MultiTreeFactory.getMultiTree(htmlPageIdentifier, containerIdentifier,contenletIdentifier3); - contentletCount = MultiTreeFactory.getMultiTree(htmlPageIdentifier).size(); + contentletCount = MultiTreeFactory.getMultiTrees(htmlPageIdentifier).size(); if (!InodeUtils.isSet(multiTree.getParent1()) && !InodeUtils.isSet(multiTree.getParent2()) && !InodeUtils.isSet(multiTree.getChild())) { MultiTree mTree = new MultiTree(htmlPageIdentifier.getInode(), containerIdentifier.getInode(), @@ -741,7 +741,7 @@ public void push_container_issue5189 () throws Exception { * Validations */ assertTrue(workinghtmlPageAsset.isLive()); - contentletCount = MultiTreeFactory.getMultiTree(htmlPageIdentifier).size(); + contentletCount = MultiTreeFactory.getMultiTrees(htmlPageIdentifier).size(); assertTrue(contentletCount == 3); /* diff --git a/dotCMS/src/integration-test/java/com/dotcms/velocity/VelocityMacroCacheTest.java b/dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/VelocityMacroCacheTest.java similarity index 95% rename from dotCMS/src/integration-test/java/com/dotcms/velocity/VelocityMacroCacheTest.java rename to dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/VelocityMacroCacheTest.java index 5c24d397c3d9..cbbcb2eab6f3 100644 --- a/dotCMS/src/integration-test/java/com/dotcms/velocity/VelocityMacroCacheTest.java +++ b/dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/VelocityMacroCacheTest.java @@ -1,4 +1,4 @@ -package com.dotcms.velocity; +package com.dotcms.rendering.velocity; import org.apache.velocity.context.Context; import org.junit.BeforeClass; @@ -9,7 +9,7 @@ import static org.junit.Assert.*; import com.dotcms.util.IntegrationTestInitService; import com.dotmarketing.business.CacheLocator; -import com.dotmarketing.util.VelocityUtil; +import com.dotcms.rendering.velocity.util.VelocityUtil; /** * VelocityUtilTest diff --git a/dotCMS/src/integration-test/java/com/dotcms/velocity/VelocityUtilTest.java b/dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/VelocityUtilTest.java similarity index 95% rename from dotCMS/src/integration-test/java/com/dotcms/velocity/VelocityUtilTest.java rename to dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/VelocityUtilTest.java index ab9aa1b13c9f..3c9e49cc01bd 100644 --- a/dotCMS/src/integration-test/java/com/dotcms/velocity/VelocityUtilTest.java +++ b/dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/VelocityUtilTest.java @@ -1,8 +1,8 @@ -package com.dotcms.velocity; +package com.dotcms.rendering.velocity; import com.dotcms.util.IntegrationTestInitService; import com.dotmarketing.util.Config; -import com.dotmarketing.util.VelocityUtil; +import com.dotcms.rendering.velocity.util.VelocityUtil; import org.junit.Assert; import org.junit.BeforeClass; diff --git a/dotCMS/src/integration-test/java/com/dotmarketing/viewtools/BrowserAPITest.java b/dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/viewtools/BrowserAPITest.java similarity index 98% rename from dotCMS/src/integration-test/java/com/dotmarketing/viewtools/BrowserAPITest.java rename to dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/viewtools/BrowserAPITest.java index a239526bb310..33b90d7ac913 100644 --- a/dotCMS/src/integration-test/java/com/dotmarketing/viewtools/BrowserAPITest.java +++ b/dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/viewtools/BrowserAPITest.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import com.dotcms.IntegrationTestBase; import com.dotcms.contenttype.exception.NotFoundInDbException; diff --git a/dotCMS/src/integration-test/java/com/dotmarketing/viewtools/LanguageWebAPITest.java b/dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/viewtools/LanguageWebAPITest.java similarity index 99% rename from dotCMS/src/integration-test/java/com/dotmarketing/viewtools/LanguageWebAPITest.java rename to dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/viewtools/LanguageWebAPITest.java index 58951218c79a..993fd14e1dac 100644 --- a/dotCMS/src/integration-test/java/com/dotmarketing/viewtools/LanguageWebAPITest.java +++ b/dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/viewtools/LanguageWebAPITest.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import static com.dotcms.contenttype.model.type.KeyValueContentType.MULTILINGUABLE_FALLBACK_KEY; import static org.junit.Assert.assertEquals; diff --git a/dotCMS/src/integration-test/java/com/dotmarketing/viewtools/content/ContentToolTest.java b/dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/viewtools/content/ContentToolTest.java similarity index 98% rename from dotCMS/src/integration-test/java/com/dotmarketing/viewtools/content/ContentToolTest.java rename to dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/viewtools/content/ContentToolTest.java index 30996a7bfb8f..da26a29bd677 100644 --- a/dotCMS/src/integration-test/java/com/dotmarketing/viewtools/content/ContentToolTest.java +++ b/dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/viewtools/content/ContentToolTest.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools.content; +package com.dotcms.rendering.velocity.viewtools.content; import com.dotcms.IntegrationTestBase; import com.dotcms.contenttype.model.type.ContentType; diff --git a/dotCMS/src/integration-test/java/com/dotmarketing/viewtools/navigation/NavToolTest.java b/dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/viewtools/navigation/NavToolTest.java similarity index 90% rename from dotCMS/src/integration-test/java/com/dotmarketing/viewtools/navigation/NavToolTest.java rename to dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/viewtools/navigation/NavToolTest.java index 493948e593ce..f719492e5a79 100644 --- a/dotCMS/src/integration-test/java/com/dotmarketing/viewtools/navigation/NavToolTest.java +++ b/dotCMS/src/integration-test/java/com/dotcms/rendering/velocity/viewtools/navigation/NavToolTest.java @@ -1,6 +1,7 @@ -package com.dotmarketing.viewtools.navigation; +package com.dotcms.rendering.velocity.viewtools.navigation; import com.dotcms.IntegrationTestBase; +import com.dotcms.rendering.velocity.viewtools.LanguageWebAPI; import com.dotcms.util.IntegrationTestInitService; import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; @@ -10,7 +11,7 @@ import com.dotmarketing.portlets.folders.model.Folder; import com.dotmarketing.portlets.htmlpageasset.model.IHTMLPage; import com.dotmarketing.util.Config; -import com.dotmarketing.viewtools.LanguageWebAPI; + import com.liferay.portal.model.User; import org.junit.AfterClass; @@ -65,14 +66,14 @@ public void testAboutUsDefaultPageToLanguageTrue() throws Exception { // https:/ //Using Identifier to get the path. Identifier aboutUsIdentifier=APILocator.getIdentifierAPI().find(aboutUsFolder); - NavResult navResult = NavTool.getNav(demoHost, aboutUsIdentifier.getPath(), 1, user); + NavResult navResult = new NavTool().getNav(demoHost, aboutUsIdentifier.getPath(), 1, user); assertNotNull(navResult); //We are expecting 3 children result for English Language. int englishResultChildren = navResult.getChildren().size(); assertEquals(englishResultChildren, 3); - navResult = NavTool.getNav(demoHost, aboutUsIdentifier.getPath(), 2, user); + navResult = new NavTool().getNav(demoHost, aboutUsIdentifier.getPath(), 2, user); assertNotNull(navResult); int spanishResultChildren = navResult.getChildren().size(); @@ -86,7 +87,7 @@ public void testAboutUsDefaultPageToLanguageTrue() throws Exception { // https:/ createSpanishPagesCopy(user, liveHTMLPages, contentletsCreated); - navResult = NavTool.getNav(demoHost, aboutUsIdentifier.getPath(), 2, user); + navResult = new NavTool().getNav(demoHost, aboutUsIdentifier.getPath(), 2, user); assertNotNull(navResult); //Now We are expecting more children result for Spanish Language than English Language. @@ -98,7 +99,7 @@ public void testAboutUsDefaultPageToLanguageTrue() throws Exception { // https:/ APILocator.getContentletAPI().delete(contentletsCreated, user, false); //We should back to 2 in Spanish Nav. - navResult = NavTool.getNav(demoHost, aboutUsIdentifier.getPath(), 2, user); + navResult = new NavTool().getNav(demoHost, aboutUsIdentifier.getPath(), 2, user); assertNotNull(navResult); //Now We are expecting original amount children result for Spanish Language. @@ -125,14 +126,14 @@ public void testAboutUsDefaultPageToLanguageFalse() throws Exception { // https: //Using Identifier to get the path. Identifier aboutUsIdentifier=APILocator.getIdentifierAPI().find(aboutUsFolder); - NavResult navResult = NavTool.getNav(demoHost, aboutUsIdentifier.getPath(), 1, user); + NavResult navResult = new NavTool().getNav(demoHost, aboutUsIdentifier.getPath(), 1, user); assertNotNull(navResult); //We are expecting 3 children result for English Language. int englishResultChildren = navResult.getChildren().size(); assertEquals(englishResultChildren, 3); - navResult = NavTool.getNav(demoHost, aboutUsIdentifier.getPath(), 2, user); + navResult = new NavTool().getNav(demoHost, aboutUsIdentifier.getPath(), 2, user); assertNotNull(navResult); int spanishResultChildren = navResult.getChildren().size(); @@ -146,7 +147,7 @@ public void testAboutUsDefaultPageToLanguageFalse() throws Exception { // https: createSpanishPagesCopy(user, liveHTMLPages, contentletsCreated); - navResult = NavTool.getNav(demoHost, aboutUsIdentifier.getPath(), 2, user); + navResult = new NavTool().getNav(demoHost, aboutUsIdentifier.getPath(), 2, user); assertNotNull(navResult); //Now We are expecting same children result for Spanish Language and English Language. @@ -158,7 +159,7 @@ public void testAboutUsDefaultPageToLanguageFalse() throws Exception { // https: APILocator.getContentletAPI().delete(contentletsCreated, user, false); //We should back to 2 in Spanish Nav. - navResult = NavTool.getNav(demoHost, aboutUsIdentifier.getPath(), 2, user); + navResult = new NavTool().getNav(demoHost, aboutUsIdentifier.getPath(), 2, user); assertNotNull(navResult); //Now We are expecting original amount children result for Spanish Language. diff --git a/dotCMS/src/integration-test/java/com/dotmarketing/factories/MultiTreeFactoryTest.java b/dotCMS/src/integration-test/java/com/dotmarketing/factories/MultiTreeFactoryTest.java new file mode 100644 index 000000000000..bee41f0769c2 --- /dev/null +++ b/dotCMS/src/integration-test/java/com/dotmarketing/factories/MultiTreeFactoryTest.java @@ -0,0 +1,161 @@ +package com.dotmarketing.factories; + +import static org.junit.Assert.assertTrue; + +import com.dotcms.IntegrationTestBase; +import com.dotcms.util.IntegrationTestInitService; + +import com.dotmarketing.beans.MultiTree; +import com.dotmarketing.startup.runonce.Task04315UpdateMultiTreePK; +import com.dotmarketing.util.Logger; + +import java.util.List; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class MultiTreeFactoryTest extends IntegrationTestBase { + + + private static final String CONTAINER = "CONTAINER"; + private static final String PAGE = "PAGE"; + private static final String CONTENTLET = "CONTENTLET"; + private static final String RELATION_TYPE = "RELATION_TYPE"; + + final static int runs =2; + final static int contentlets =5; + @BeforeClass + public static void initData() throws Exception { + IntegrationTestInitService.getInstance().init(); + // testUpgradeTask(); + buildInitalData(); + } + + public static void testUpgradeTask() throws Exception { + Task04315UpdateMultiTreePK task = Task04315UpdateMultiTreePK.class.newInstance(); + task.executeUpgrade(); + } + + + public static void buildInitalData() throws Exception { + for(int i=0;i all = MultiTreeFactory.getAllMultiTrees(); + + List list = MultiTreeFactory.getMultiTrees(PAGE); + + deleteInitialData(); + assertTrue("multiTree deletes", MultiTreeFactory.getAllMultiTrees().size() < all.size() ); + assertTrue("multiTree deletes", MultiTreeFactory.getAllMultiTrees().size() == all.size() - list.size() ); + } + + + @Test + public void testReorder() throws Exception { + deleteInitialData(); + buildInitalData() ; + MultiTree tree = MultiTreeFactory.getMultiTree(PAGE, CONTAINER+0, CONTENTLET +0, RELATION_TYPE+0); + assertTrue("multiTree reorders", tree.getTreeOrder()==0 ); + MultiTreeFactory.saveMultiTree(tree.setTreeOrder(7)); + tree = MultiTreeFactory.getMultiTree(PAGE, CONTAINER+ 0, CONTENTLET + 0, RELATION_TYPE+0); + assertTrue("multiTree reorders", tree.getTreeOrder()==4 ); + MultiTreeFactory.saveMultiTree(tree.setTreeOrder(2)); + List list = MultiTreeFactory.getMultiTrees(PAGE, CONTAINER+0, RELATION_TYPE+0); + assertTrue("multiTree reorders", list.get(2).equals(tree)); + + } + + @Test + public void findByChild() throws Exception { + deleteInitialData(); + buildInitalData() ; + + List list = MultiTreeFactory.getMultiTreesByChild(CONTENTLET + "0"); + + assertTrue("getByChild returns all results", list.size() == runs ); + + + + } + + + + @AfterClass + public static void deleteInitialData() throws Exception { + + List list = MultiTreeFactory.getMultiTrees(PAGE); + + for(MultiTree tree : list) { + MultiTreeFactory.deleteMultiTree(tree); + } + + } + + + + + + @Test + public void testSaveMultiTree() throws Exception { + MultiTree mt = new MultiTree() + .setContainer(CONTAINER) + .setHtmlPage(PAGE) + .setContentlet("NEW_ONE") + .setTreeOrder(0) + .setRelationType(RELATION_TYPE + 0); + + MultiTreeFactory.saveMultiTree(mt); + + MultiTree mt2 = MultiTreeFactory.getMultiTree(mt.getHtmlPage(), mt.getContainer(), mt.getContentlet(), mt.getRelationType()); + assertTrue("multiTree save and get equals", mt.equals(mt2)); + + + + + + + + + } + + + + + + + + + + + @Test + public void testGetMultiTreeIdentifierIdentifierIdentifierString() throws Exception { + + + + + } + + @Test + public void testGetMultiTreeInode() throws Exception { + + } + +} diff --git a/dotCMS/src/integration-test/java/com/dotmarketing/filters/FiltersTest.java b/dotCMS/src/integration-test/java/com/dotmarketing/filters/FiltersTest.java index 480979f1a89f..a5880b6e7c7f 100644 --- a/dotCMS/src/integration-test/java/com/dotmarketing/filters/FiltersTest.java +++ b/dotCMS/src/integration-test/java/com/dotmarketing/filters/FiltersTest.java @@ -6,8 +6,10 @@ import com.dotcms.LicenseTestUtil; import com.dotcms.contenttype.model.type.ContentType; import com.dotcms.contenttype.transform.contenttype.StructureTransformer; +import com.dotcms.rendering.velocity.servlet.VelocityLiveServlet; import com.dotcms.util.FiltersUtil; import com.dotcms.util.IntegrationTestInitService; + import com.dotmarketing.beans.Host; import com.dotmarketing.business.APILocator; import com.dotmarketing.exception.DotDataException; @@ -17,9 +19,7 @@ import com.dotmarketing.servlets.SpeedyAssetServlet; import com.dotmarketing.util.Config; import com.dotmarketing.util.Logger; -import com.dotmarketing.velocity.ClientVelocityServlet; -import com.dotmarketing.velocity.VelocityServlet; -import com.liferay.portal.model.User; + import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; @@ -30,6 +30,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; + import javax.servlet.FilterChain; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; @@ -44,6 +45,7 @@ import javax.servlet.http.HttpServletResponseWrapper; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionContext; + import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; @@ -51,6 +53,8 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; +import com.liferay.portal.model.User; + public class FiltersTest { private static ContentletAPI contentletAPI; @@ -372,7 +376,7 @@ public void include(ServletRequest arg0, ServletResponse arg1) public void forward(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException { - VelocityServlet servlet = new ClientVelocityServlet(); + VelocityLiveServlet servlet = new VelocityLiveServlet(); servlet.init(null); servlet.service(arg0, arg1); } diff --git a/dotCMS/src/integration-test/java/com/dotmarketing/portlets/contentlet/business/ContentletAPITest.java b/dotCMS/src/integration-test/java/com/dotmarketing/portlets/contentlet/business/ContentletAPITest.java index a1dfbaf81faa..afea311dee68 100644 --- a/dotCMS/src/integration-test/java/com/dotmarketing/portlets/contentlet/business/ContentletAPITest.java +++ b/dotCMS/src/integration-test/java/com/dotmarketing/portlets/contentlet/business/ContentletAPITest.java @@ -72,7 +72,7 @@ import com.dotmarketing.util.Logger; import com.dotmarketing.util.UUIDGenerator; import com.dotmarketing.util.UtilMethods; -import com.dotmarketing.util.VelocityUtil; +import com.dotcms.rendering.velocity.util.VelocityUtil; import com.dotmarketing.util.WebKeys; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -668,7 +668,7 @@ public void publishRelatedHtmlPages () throws DotDataException, DotSecurityExcep //Get the contentlet Identifier to gather the related pages Identifier identifier = APILocator.getIdentifierAPI().find( contentlet ); //Get the identifier's number of the related pages - List multiTrees = MultiTreeFactory.getMultiTreeByChild( identifier.getId() ); + List multiTrees = MultiTreeFactory.getMultiTreesByChild( identifier.getId() ); for ( MultiTree multitree : multiTrees ) { //Get the Identifiers of the related pages Identifier htmlPageIdentifier = APILocator.getIdentifierAPI().find( multitree.getParent1() ); @@ -994,7 +994,7 @@ public void findPageContentlets () throws DotDataException, DotSecurityException Identifier identifier = APILocator.getIdentifierAPI().find( contentlet ); //Search for related html pages and containers - List multiTrees = MultiTreeFactory.getMultiTreeByChild( identifier.getId() ); + List multiTrees = MultiTreeFactory.getMultiTreesByChild( identifier.getId() ); if ( multiTrees != null && !multiTrees.isEmpty() ) { for ( MultiTree multiTree : multiTrees ) { @@ -2043,8 +2043,11 @@ public void testPubExpDatesFromIdentifier() throws Exception { Identifier ident=APILocator.getIdentifierAPI().find(c1); assertNotNull(ident.getSysPublishDate()); assertNotNull(ident.getSysExpireDate()); - assertTrue(compareDates(d1, ident.getSysPublishDate())); - assertTrue(compareDates(d2, ident.getSysExpireDate())); + + assertTrue(d1 + .equals(ident.getSysPublishDate())); + assertTrue(d2.equals(ident.getSysExpireDate())); + // if we save another language version for the same identifier // then the identifier should be updated with those dates d3&d4 @@ -2061,13 +2064,17 @@ public void testPubExpDatesFromIdentifier() throws Exception { Identifier ident2=APILocator.getIdentifierAPI().find(c2); assertNotNull(ident2.getSysPublishDate()); assertNotNull(ident2.getSysExpireDate()); - assertTrue(compareDates(d3, ident2.getSysPublishDate())); - assertTrue(compareDates(d4, ident2.getSysExpireDate())); + + assertTrue(d3 + .equals(ident2.getSysPublishDate())); + assertTrue(d4 + .equals(ident2.getSysExpireDate())); // the other contentlet should have the same dates if we read it again Contentlet c11=APILocator.getContentletAPI().find(c1.getInode(), user, false); - assertTrue(compareDates(d3, c11.getDateProperty(fieldPubDate.getVelocityVarName()))); - assertTrue(compareDates(d4, c11.getDateProperty(fieldExpDate.getVelocityVarName()))); + assertTrue(d3.equals(c11.getDateProperty(fieldPubDate.getVelocityVarName()))); + assertTrue(d4.equals(c11.getDateProperty(fieldExpDate.getVelocityVarName()))); + Thread.sleep(2000); // wait a bit for the index diff --git a/dotCMS/src/integration-test/java/com/dotmarketing/portlets/contentlet/business/ContentletCheckInTest.java b/dotCMS/src/integration-test/java/com/dotmarketing/portlets/contentlet/business/ContentletCheckInTest.java new file mode 100644 index 000000000000..eb5eeadddb29 --- /dev/null +++ b/dotCMS/src/integration-test/java/com/dotmarketing/portlets/contentlet/business/ContentletCheckInTest.java @@ -0,0 +1,49 @@ +package com.dotmarketing.portlets.contentlet.business; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.dotcms.contenttype.test.ContentTypeAPIImplTest; +import com.dotcms.util.IntegrationTestInitService; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.portlets.ContentletBaseTest; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.structure.model.Structure; + +/** + * Created by Jonathan Gamba. + * Date: 3/20/12 + * Time: 12:12 PM + */ +public class ContentletCheckInTest extends ContentletBaseTest { + + + + @BeforeClass + public static void prepare () throws Exception{ + + ContentletBaseTest.prepare(); + + } + + @Test + public void checkinContent () throws DotDataException, DotSecurityException { + + + + + + + + + + + + + } + + + +} \ No newline at end of file diff --git a/dotCMS/src/integration-test/java/com/dotmarketing/portlets/folders/business/FolderAPITest.java b/dotCMS/src/integration-test/java/com/dotmarketing/portlets/folders/business/FolderAPITest.java index 716667e2c669..745bdcc0fc06 100644 --- a/dotCMS/src/integration-test/java/com/dotmarketing/portlets/folders/business/FolderAPITest.java +++ b/dotCMS/src/integration-test/java/com/dotmarketing/portlets/folders/business/FolderAPITest.java @@ -348,7 +348,7 @@ public void move() throws Exception { pages = htmlPageAssetAPI.getLiveHTMLPages(newftest3,user, false); Assert.assertTrue(pages.size() == 1 && pages.get(0).getTitle().equals(page2Str)); - final List mt= MultiTreeFactory.getMultiTree(pages.get(0).getIdentifier()); + final List mt= MultiTreeFactory.getMultiTrees(pages.get(0).getIdentifier()); Assert.assertTrue(mt.size() ==1 && mt.get(0).getParent2().equals(container.getIdentifier()) && mt.get(0).getChild().equals(contentAsset2.getIdentifier()) ); } @@ -592,7 +592,7 @@ public void copy() throws Exception { .getPageByPath(newftest1.getPath()+page1Str, host, langId, false); Assert.assertTrue(page != null && page.getTitle().contains(pageStr)); - List mt= MultiTreeFactory.getMultiTree(page.getIdentifier()); + List mt= MultiTreeFactory.getMultiTrees(page.getIdentifier()); Assert.assertTrue(mt.size() ==1 && mt.get(0).getParent2().equals(container.getIdentifier()) && mt.get(0).getChild().equals(contentAsset2.getIdentifier()) ); Thread.sleep(3000); List files = fileAssetAPI @@ -626,7 +626,7 @@ public void copy() throws Exception { .getPageByPath(newftest3.getPath()+pageStr3, host, langId, false); Assert.assertTrue(page != null && page.getTitle().contains(pageStr3)); - mt= MultiTreeFactory.getMultiTree(page.getIdentifier()); + mt= MultiTreeFactory.getMultiTrees(page.getIdentifier()); Assert.assertTrue(mt.size() ==1 && mt.get(0).getParent2().equals(container.getIdentifier()) && mt.get(0).getChild().equals(contentAsset7.getIdentifier()) ); } diff --git a/dotCMS/src/integration-test/java/org/apache/velocity/runtime/parser/node/SimpleNodeTest.java b/dotCMS/src/integration-test/java/org/apache/velocity/runtime/parser/node/SimpleNodeTest.java index b7363c69a3ce..1c93b444c473 100644 --- a/dotCMS/src/integration-test/java/org/apache/velocity/runtime/parser/node/SimpleNodeTest.java +++ b/dotCMS/src/integration-test/java/org/apache/velocity/runtime/parser/node/SimpleNodeTest.java @@ -3,7 +3,7 @@ import com.dotcms.util.IntegrationTestInitService; import com.dotmarketing.business.CacheLocator; import com.dotmarketing.util.Config; -import com.dotmarketing.util.VelocityUtil; +import com.dotcms.rendering.velocity.util.VelocityUtil; import org.apache.velocity.app.VelocityEngine; import org.junit.BeforeClass; diff --git a/dotCMS/src/main/java/com/dotcms/aspects/aspectj/CloseDBAspect.java b/dotCMS/src/main/java/com/dotcms/aspects/aspectj/CloseDBAspect.java new file mode 100644 index 000000000000..f0ca426f70e2 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/aspects/aspectj/CloseDBAspect.java @@ -0,0 +1,45 @@ +package com.dotcms.aspects.aspectj; + +import com.dotcms.aspects.MethodInterceptor; +import com.dotcms.aspects.interceptors.CloseDBMethodInterceptor; +import com.dotcms.business.CloseDB; + +import com.google.common.annotations.VisibleForTesting; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; + +/** + * This aspect handles the @{@link CloseDB} with AspectJ + * @author jsanca + */ +@Aspect +public class CloseDBAspect { + + private final MethodInterceptor interceptor; + + public CloseDBAspect() { + this(CloseDBMethodInterceptor.INSTANCE); + } + + @VisibleForTesting + public CloseDBAspect(final MethodInterceptor interceptor) { + this.interceptor = interceptor; + } + + /** + * Aspect implementation for the {@link CloseDB} annotation + * + * @param point Joint point + * @return The result of call + * @throws Throwable If something goes wrong inside + */ + @Around("execution(* *(..))" + + " && @annotation(com.dotcms.business.CloseDB)") + public Object invoke(final ProceedingJoinPoint point) throws Throwable { + + return + this.interceptor.invoke + (new AspectJDelegateMethodInvocation(point)); + } // invoke. +} // E:O:F:LogTimeAspect. \ No newline at end of file diff --git a/dotCMS/src/main/java/com/dotcms/aspects/interceptors/CloseDBMethodInterceptor.java b/dotCMS/src/main/java/com/dotcms/aspects/interceptors/CloseDBMethodInterceptor.java new file mode 100644 index 000000000000..d46c8af68c7f --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/aspects/interceptors/CloseDBMethodInterceptor.java @@ -0,0 +1,47 @@ +package com.dotcms.aspects.interceptors; + +import static com.dotcms.util.AnnotationUtils.getMethodAnnotation; + +import com.dotcms.aspects.DelegateMethodInvocation; +import com.dotcms.aspects.MethodInterceptor; +import com.dotcms.business.CloseDB; + + +import com.dotmarketing.db.DbConnectionFactory; + +/** + * Method handler for the {@link CloseDB} annotation aspect + * @author jsanca + */ +public class CloseDBMethodInterceptor implements MethodInterceptor { + + /** + * + */ + private static final long serialVersionUID = 1L; + public static final CloseDBMethodInterceptor INSTANCE = new CloseDBMethodInterceptor(); + + + @Override + public Object invoke(final DelegateMethodInvocation delegate) throws Throwable { + + + final CloseDB closeDB = + getMethodAnnotation(delegate.getMethod(), CloseDB.class); + Object methodReturn = null; + + try { + methodReturn = delegate.proceed(); + } finally { + try { + DbConnectionFactory.closeAndCommit(); + } finally { + DbConnectionFactory.closeSilently(); + } + + + } + + return methodReturn; + } // invoke. +} // E:O:F:LogTimeMethodInterceptor. \ No newline at end of file diff --git a/dotCMS/src/main/java/com/dotcms/business/CloseDB.java b/dotCMS/src/main/java/com/dotcms/business/CloseDB.java new file mode 100644 index 000000000000..003d113388fa --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/business/CloseDB.java @@ -0,0 +1,20 @@ +package com.dotcms.business; + +import java.lang.annotation.*; + +/** + * A method annotated with CloseDB annotation will close resources in the current thread if needed, such as database connections... + * @author jsanca + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface CloseDB { + + /** + * By default in true, set to false if you do not want to close the connection hold on the current thread + * @return boolean + */ + boolean connection() default true; + +} // E:O:F:LogTime \ No newline at end of file diff --git a/dotCMS/src/main/java/com/dotcms/content/elasticsearch/business/ESContentletAPIImpl.java b/dotCMS/src/main/java/com/dotcms/content/elasticsearch/business/ESContentletAPIImpl.java index 1d82662525dd..4a6492d47b41 100644 --- a/dotCMS/src/main/java/com/dotcms/content/elasticsearch/business/ESContentletAPIImpl.java +++ b/dotCMS/src/main/java/com/dotcms/content/elasticsearch/business/ESContentletAPIImpl.java @@ -1,35 +1,5 @@ package com.dotcms.content.elasticsearch.business; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.Serializable; -import java.nio.file.Files; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.elasticsearch.action.search.SearchPhaseExecutionException; -import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.search.SearchHit; -import org.elasticsearch.search.SearchHits; -import org.springframework.beans.BeanUtils; - import com.dotcms.api.system.event.ContentletSystemEventUtil; import com.dotcms.business.CloseDBIfOpened; import com.dotcms.business.WrapInTransaction; @@ -43,6 +13,8 @@ import com.dotcms.notifications.bean.NotificationLevel; import com.dotcms.publisher.business.DotPublisherException; import com.dotcms.publisher.business.PublisherAPI; +import com.dotcms.rendering.velocity.services.ContentletLoader; +import com.dotcms.rendering.velocity.services.PageLoader; import com.dotcms.repackage.com.google.common.base.Preconditions; import com.dotcms.repackage.com.google.common.collect.Lists; import com.dotcms.repackage.com.google.common.collect.Maps; @@ -55,6 +27,7 @@ import com.dotcms.services.VanityUrlServices; import com.dotcms.system.event.local.type.content.CommitListenerEvent; import com.dotcms.util.CollectionsUtils; + import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.MultiTree; @@ -64,7 +37,6 @@ import com.dotmarketing.business.CacheLocator; import com.dotmarketing.business.DotCacheAdministrator; import com.dotmarketing.business.DotStateException; -import com.dotmarketing.business.DotValidationException; import com.dotmarketing.business.FactoryLocator; import com.dotmarketing.business.PermissionAPI; import com.dotmarketing.business.RelationshipAPI; @@ -103,7 +75,6 @@ import com.dotmarketing.portlets.contentlet.business.DotReindexStateException; import com.dotmarketing.portlets.contentlet.business.HostAPI; import com.dotmarketing.portlets.contentlet.model.Contentlet; - import com.dotmarketing.portlets.contentlet.model.ContentletVersionInfo; import com.dotmarketing.portlets.fileassets.business.FileAsset; import com.dotmarketing.portlets.fileassets.business.FileAssetAPI; @@ -128,8 +99,6 @@ import com.dotmarketing.portlets.workflows.model.WorkflowHistory; import com.dotmarketing.portlets.workflows.model.WorkflowProcessor; import com.dotmarketing.portlets.workflows.model.WorkflowTask; -import com.dotmarketing.services.ContentletServices; -import com.dotmarketing.services.PageServices; import com.dotmarketing.tag.business.TagAPI; import com.dotmarketing.tag.model.Tag; import com.dotmarketing.util.ActivityLogger; @@ -139,6 +108,7 @@ import com.dotmarketing.util.DateUtil; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; import com.dotmarketing.util.PaginatedArrayList; import com.dotmarketing.util.RegEX; import com.dotmarketing.util.RegExMatch; @@ -146,6 +116,37 @@ import com.dotmarketing.util.UUIDGenerator; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.Serializable; +import java.nio.file.Files; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.elasticsearch.action.search.SearchPhaseExecutionException; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.search.SearchHit; +import org.elasticsearch.search.SearchHits; +import org.springframework.beans.BeanUtils; + import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.liferay.portal.NoSuchUserException; @@ -311,11 +312,12 @@ public Contentlet findContentletByIdentifier(String identifier, boolean live, lo @Override public List findContentletsByIdentifiers(String[] identifiers, boolean live, long languageId, User user, boolean respectFrontendRoles)throws DotDataException, DotSecurityException, DotContentletStateException { List l = new ArrayList(); - Long languageIdLong = languageId <= 0?null:new Long(languageId); + for(String identifier : identifiers){ - Contentlet con = findContentletByIdentifier(identifier.trim(), live, languageIdLong, user, respectFrontendRoles); + Contentlet con = findContentletByIdentifier(identifier.trim(), live, languageId, user, respectFrontendRoles); l.add(con); } + return l; } @@ -605,8 +607,8 @@ public void run () { if (!isNew) { // writes the contentlet to a live directory under velocity folder - ContentletServices.invalidateAll(contentlet); + new ContentletLoader().invalidate(contentlet); CacheLocator.getContentletCache().remove(contentlet.getInode()); // Need to refresh the live pages that reference this piece of @@ -821,7 +823,7 @@ public void publishRelatedHtmlPages(final Contentlet contentlet) throws DotState //Get the contentlet Identifier to gather the related pages final Identifier identifier = APILocator.getIdentifierAPI().find(contentlet); //Get the identifier's number of the related pages - final List multitrees = (List) MultiTreeFactory.getMultiTreeByChild(identifier.getId()); + final List multitrees = (List) MultiTreeFactory.getMultiTreesByChild(identifier.getId()); for(MultiTree multitree : multitrees) { @@ -839,7 +841,8 @@ public void publishRelatedHtmlPages(final Contentlet contentlet) throws DotState if(null != page && page.isLive()){ //Rebuild the pages' files - PageServices.invalidateAll(page); + new PageLoader().invalidate(page); + } } catch(Exception e) { final String htmlPageIdentifierId = null != htmlPageIdentifier ? htmlPageIdentifier.getId() : null; @@ -1009,7 +1012,7 @@ public List> getContentletReferences(Contentlet contentlet, Identifier id = APILocator.getIdentifierAPI().find(contentlet); if (!InodeUtils.isSet(id.getId())) return results; - List trees = MultiTreeFactory.getMultiTreeByChild(id.getId()); + List trees = MultiTreeFactory.getMultiTreesByChild(id.getId()); for (MultiTree tree : trees) { IHTMLPage page = loadPageByIdentifier(tree.getParent1(), false, contentlet.getLanguageId(), APILocator.getUserAPI().getSystemUser(), false); Container container = (Container) APILocator.getVersionableAPI().findWorkingVersion(tree.getParent2(), APILocator.getUserAPI().getSystemUser(), false); @@ -1114,7 +1117,7 @@ public void addLinkToContentlet(Contentlet contentlet, String linkInode, String Link link = (Link) InodeFactory.getInode(linkInode, Link.class); Identifier identifier = APILocator.getIdentifierAPI().find(link); relationshipAPI.addRelationship(contentlet.getInode(),identifier.getInode(), relationName); - ContentletServices.invalidateWorking(contentlet); + new ContentletLoader().invalidate(contentlet); } } @@ -1541,13 +1544,13 @@ private boolean destroyContentlets(List contentlets, User user, bool contentletsVersion.addAll(findAllVersions(APILocator.getIdentifierAPI().find(con.getIdentifier()), user, respectFrontendRoles)); // Remove page contents (if the content is a Content Page) - List mts = MultiTreeFactory.getMultiTreeByChild(con.getIdentifier()); + List mts = MultiTreeFactory.getMultiTreesByChild(con.getIdentifier()); for (MultiTree mt : mts) { Identifier pageIdent = APILocator.getIdentifierAPI().find(mt.getParent1()); if (pageIdent != null && UtilMethods.isSet(pageIdent.getInode())) { IHTMLPage page = loadPageByIdentifier(pageIdent.getId(), false, con.getLanguageId(), user, false); if (page != null && UtilMethods.isSet(page.getIdentifier())) - PageServices.invalidateAll(page); + new PageLoader().invalidate(page); } MultiTreeFactory.deleteMultiTree(mt); } @@ -1954,8 +1957,8 @@ public void archive(Contentlet contentlet, User user,boolean respectFrontendRole CacheLocator.getNavToolCache().removeNav(ident.getHostId(), folder.getInode()); } } + new ContentletLoader().invalidate(contentlet); - ContentletServices.invalidateAll(contentlet); publishRelatedHtmlPages(contentlet); contentletSystemEventUtil.pushArchiveEvent(contentlet); }else{ @@ -2234,7 +2237,7 @@ private void unpublish(Contentlet contentlet, User user) throws DotDataException CacheLocator.getNavToolCache().removeNav(ident.getHostId(), folder.getInode()); } } - ContentletServices.invalidateLive(contentlet); + new ContentletLoader().invalidate(contentlet, PageMode.LIVE); publishRelatedHtmlPages(contentlet); @@ -2324,7 +2327,7 @@ public void unarchive(Contentlet contentlet, User user, boolean respectFrontendR && !liveContentlet.getInode().equalsIgnoreCase(workingContentlet.getInode())) indexAPI.addContentToIndex(liveContentlet); - ContentletServices.invalidateAll(contentlet); + new ContentletLoader().invalidate(contentlet); publishRelatedHtmlPages(contentlet); contentletSystemEventUtil.pushUnArchiveEvent(contentlet); @@ -3448,7 +3451,8 @@ else if (oldFile.exists()) { publishAssociated(contentlet, isNewContent, createNewVersion); } else { if (!isNewContent) { - ContentletServices.invalidateWorking(contentlet); + new ContentletLoader().invalidate(contentlet); + } indexAPI.addContentToIndex(contentlet); @@ -3496,19 +3500,10 @@ else if (oldFile.exists()) { DotCacheAdministrator cache = CacheLocator.getCacheAdministrator(); Host host = APILocator.getHostAPI().find(contIdent.getHostId(), user, respectFrontendRoles); - ContentletServices.invalidateLive(contentlet); - ContentletServices.invalidateWorking(contentlet); + new ContentletLoader().invalidate(contentlet); - String velocityResourcePath = "working/" + contentlet.getIdentifier() + "_" + contentlet.getLanguageId() + "." + Config.getStringProperty("VELOCITY_CONTENT_EXTENSION","content"); - if(CacheLocator.getVeloctyResourceCache().isMiss(velocityResourcePath)) - CacheLocator.getVeloctyResourceCache().remove(velocityResourcePath); - if (isLive) { - velocityResourcePath = "live/" + contentlet.getIdentifier() + "_" + contentlet.getLanguageId() + "." + Config.getStringProperty("VELOCITY_CONTENT_EXTENSION","content"); - if(CacheLocator.getVeloctyResourceCache().isMiss(velocityResourcePath)) - CacheLocator.getVeloctyResourceCache().remove(velocityResourcePath); - } } catch (Exception e) { if(createNewVersion && workingContentlet!= null && UtilMethods.isSet(workingContentlet.getInode())){ @@ -3739,7 +3734,7 @@ public void restoreVersion(Contentlet contentlet, User user,boolean respectFront Contentlet currentWorkingCon = findContentletByIdentifier(contentlet.getIdentifier(), false, contentlet.getLanguageId(), user, respectFrontendRoles); APILocator.getVersionableAPI().setWorking(contentlet); // Updating lucene index - ContentletServices.invalidateWorking(contentlet); + new ContentletLoader().invalidate(contentlet); // Updating lucene index indexAPI.addContentToIndex(currentWorkingCon); indexAPI.addContentToIndex(contentlet); diff --git a/dotCMS/src/main/java/com/dotcms/contenttype/business/ContentTypeCache2Impl.java b/dotCMS/src/main/java/com/dotcms/contenttype/business/ContentTypeCache2Impl.java index ca9fe88c071e..74ada59ef008 100644 --- a/dotCMS/src/main/java/com/dotcms/contenttype/business/ContentTypeCache2Impl.java +++ b/dotCMS/src/main/java/com/dotcms/contenttype/business/ContentTypeCache2Impl.java @@ -87,6 +87,7 @@ public String getPrimaryGroup() { @Override public void remove(ContentType type) { + cache.remove( type.id(),primaryGroup); cache.remove( type.variable(),primaryGroup); clearURLMasterPattern(); diff --git a/dotCMS/src/main/java/com/dotcms/contenttype/business/FieldAPIImpl.java b/dotCMS/src/main/java/com/dotcms/contenttype/business/FieldAPIImpl.java index 0bee1ad7b6f2..c51195adc985 100644 --- a/dotCMS/src/main/java/com/dotcms/contenttype/business/FieldAPIImpl.java +++ b/dotCMS/src/main/java/com/dotcms/contenttype/business/FieldAPIImpl.java @@ -4,28 +4,59 @@ import com.dotcms.business.WrapInTransaction; import com.dotcms.content.business.DotMappingException; import com.dotcms.contenttype.exception.NotFoundInDbException; -import com.dotcms.contenttype.model.field.*; +import com.dotcms.contenttype.model.field.BinaryField; +import com.dotcms.contenttype.model.field.CategoryField; +import com.dotcms.contenttype.model.field.CheckboxField; +import com.dotcms.contenttype.model.field.ConstantField; +import com.dotcms.contenttype.model.field.CustomField; +import com.dotcms.contenttype.model.field.DateField; +import com.dotcms.contenttype.model.field.DateTimeField; +import com.dotcms.contenttype.model.field.Field; +import com.dotcms.contenttype.model.field.FieldVariable; +import com.dotcms.contenttype.model.field.FileField; +import com.dotcms.contenttype.model.field.HiddenField; +import com.dotcms.contenttype.model.field.HostFolderField; +import com.dotcms.contenttype.model.field.ImageField; +import com.dotcms.contenttype.model.field.ImmutableFieldVariable; +import com.dotcms.contenttype.model.field.KeyValueField; +import com.dotcms.contenttype.model.field.LineDividerField; +import com.dotcms.contenttype.model.field.MultiSelectField; +import com.dotcms.contenttype.model.field.PermissionTabField; +import com.dotcms.contenttype.model.field.RadioField; +import com.dotcms.contenttype.model.field.RelationshipsTabField; +import com.dotcms.contenttype.model.field.SelectField; +import com.dotcms.contenttype.model.field.TabDividerField; +import com.dotcms.contenttype.model.field.TagField; +import com.dotcms.contenttype.model.field.TextAreaField; +import com.dotcms.contenttype.model.field.TimeField; +import com.dotcms.contenttype.model.field.WysiwygField; import com.dotcms.contenttype.model.type.ContentType; import com.dotcms.contenttype.transform.contenttype.StructureTransformer; import com.dotcms.contenttype.transform.field.LegacyFieldTransformer; +import com.dotcms.rendering.velocity.services.ContentTypeLoader; +import com.dotcms.rendering.velocity.services.ContentletLoader; import com.dotcms.repackage.com.google.common.annotations.VisibleForTesting; import com.dotcms.repackage.com.google.common.collect.ImmutableList; import com.dotcms.repackage.org.apache.commons.lang.StringUtils; -import com.dotmarketing.business.*; + +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.CacheLocator; +import com.dotmarketing.business.DotStateException; +import com.dotmarketing.business.PermissionAPI; +import com.dotmarketing.business.PermissionLevel; +import com.dotmarketing.business.UserAPI; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.contentlet.business.ContentletAPI; import com.dotmarketing.portlets.structure.model.Structure; import com.dotmarketing.quartz.job.DeleteFieldJobHelper; -import com.dotmarketing.services.ContentletMapServices; -import com.dotmarketing.services.ContentletServices; -import com.dotmarketing.services.StructureServices; import com.dotmarketing.util.ActivityLogger; import com.dotmarketing.util.UtilMethods; -import com.liferay.portal.model.User; import java.util.List; +import com.liferay.portal.model.User; + public class FieldAPIImpl implements FieldAPI { @@ -94,15 +125,14 @@ public Field save(final Field field, final User user) throws DotDataException, D Structure structure = new StructureTransformer(type).asStructure(); CacheLocator.getContentTypeCache().remove(structure); - StructureServices.removeStructureFile(structure); + new ContentTypeLoader().invalidate(structure); if(oldField!=null){ if(oldField.indexed() != field.indexed()){ contentletAPI.refresh(structure); } else if (field instanceof ConstantField) { if(!StringUtils.equals(oldField.values(), field.values()) ){ - ContentletServices.removeContentletFile(structure); - ContentletMapServices.removeContentletMapFile(structure); + new ContentletLoader().invalidate(structure); contentletAPI.refresh(structure); } } @@ -187,7 +217,7 @@ public void delete(final Field field, final User user) throws DotDataException, contentTypeAPI.updateModDate(type); CacheLocator.getContentTypeCache().remove(structure); - StructureServices.removeStructureFile(structure); + //Refreshing permissions if (field instanceof HostFolderField) { @@ -203,8 +233,7 @@ public void delete(final Field field, final User user) throws DotDataException, contentletAPI.reindex(structure); } // remove the file from the cache - ContentletServices.removeContentletFile(structure); - ContentletMapServices.removeContentletMapFile(structure); + new ContentletLoader().invalidate(structure); } diff --git a/dotCMS/src/main/java/com/dotcms/contenttype/business/FieldFactoryImpl.java b/dotCMS/src/main/java/com/dotcms/contenttype/business/FieldFactoryImpl.java index 2f47fb09a424..f20ea0b5e232 100644 --- a/dotCMS/src/main/java/com/dotcms/contenttype/business/FieldFactoryImpl.java +++ b/dotCMS/src/main/java/com/dotcms/contenttype/business/FieldFactoryImpl.java @@ -557,12 +557,12 @@ public String suggestVelocityVar(final String tryVar, List takenFields) t break; } } - if (var != null) - return var; + if (!UtilMethods.isSet(var)) { + throw new DotDataValidationException("Unable to suggest a variable name. Got to:" + var, + "field.validation.variable.already.taken"); + } } - throw new DotDataValidationException("Unable to suggest a variable name. Got to:" + var, - "field.validation.variable.already.taken"); - + return var; } public void moveSortOrderForward(String contentTypeId, int from, int to) throws DotDataException { diff --git a/dotCMS/src/main/java/com/dotcms/contenttype/model/component/VelocityFieldFormRenderer.java b/dotCMS/src/main/java/com/dotcms/contenttype/model/component/VelocityFieldFormRenderer.java index d90fa976b58c..5a6b4b33e623 100644 --- a/dotCMS/src/main/java/com/dotcms/contenttype/model/component/VelocityFieldFormRenderer.java +++ b/dotCMS/src/main/java/com/dotcms/contenttype/model/component/VelocityFieldFormRenderer.java @@ -2,7 +2,7 @@ import org.apache.velocity.context.Context; -import com.dotmarketing.util.VelocityUtil; +import com.dotcms.rendering.velocity.util.VelocityUtil; public class VelocityFieldFormRenderer implements FieldFormRenderer{ diff --git a/dotCMS/src/main/java/com/dotcms/filters/interceptor/dotcms/DefaultFrontEndLoginRequiredWebInterceptor.java b/dotCMS/src/main/java/com/dotcms/filters/interceptor/dotcms/DefaultFrontEndLoginRequiredWebInterceptor.java index c94d0bea361f..607016a522bd 100644 --- a/dotCMS/src/main/java/com/dotcms/filters/interceptor/dotcms/DefaultFrontEndLoginRequiredWebInterceptor.java +++ b/dotCMS/src/main/java/com/dotcms/filters/interceptor/dotcms/DefaultFrontEndLoginRequiredWebInterceptor.java @@ -6,6 +6,7 @@ import com.dotcms.repackage.org.apache.struts.action.ActionMessage; import com.dotcms.repackage.org.apache.struts.action.ActionMessages; import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; import com.dotmarketing.util.WebKeys; import javax.servlet.http.HttpServletRequest; @@ -27,9 +28,7 @@ public Result intercept(final HttpServletRequest request, Result result = Result.NEXT; if (null != session) { - final boolean isAdminMode = (session.getAttribute - (com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null); - + final boolean isAdminMode = PageMode.get(request).isAdmin; // if we are not logged in and you are not admin mode. go to login page if (session.getAttribute(WebKeys.CMS_USER) == null diff --git a/dotCMS/src/main/java/com/dotcms/publisher/util/DependencyManager.java b/dotCMS/src/main/java/com/dotcms/publisher/util/DependencyManager.java index 2978c1a20dc0..e7289ad4a98a 100644 --- a/dotCMS/src/main/java/com/dotcms/publisher/util/DependencyManager.java +++ b/dotCMS/src/main/java/com/dotcms/publisher/util/DependencyManager.java @@ -686,7 +686,7 @@ private void setHTMLPagesDependencies(Set idsToWork) { structuresSet.add(containerStructure.getStructureId()); } - List treeList = MultiTreeFactory.getMultiTree(workingPage,container); + List treeList = MultiTreeFactory.getMultiTrees(workingPage,container); for (MultiTree mt : treeList) { String contentIdentifier = mt.getChild(); diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/Constants.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/Constants.java new file mode 100644 index 000000000000..0ed200219793 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/Constants.java @@ -0,0 +1,5 @@ +package com.dotcms.rendering.velocity; + +public final class Constants { + public static final String VELOCITY_CONTEXT = "velocityContext"; +} diff --git a/dotCMS/src/main/java/com/dotmarketing/velocity/directive/ContentletDetail.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/directive/ContentletDetail.java similarity index 61% rename from dotCMS/src/main/java/com/dotmarketing/velocity/directive/ContentletDetail.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/directive/ContentletDetail.java index 1e667d60665b..793d3da5c405 100644 --- a/dotCMS/src/main/java/com/dotmarketing/velocity/directive/ContentletDetail.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/directive/ContentletDetail.java @@ -1,7 +1,11 @@ -package com.dotmarketing.velocity.directive; +package com.dotcms.rendering.velocity.directive; import com.dotcms.contenttype.model.type.BaseContentType; import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.rendering.velocity.directive.DotDirective; +import com.dotcms.rendering.velocity.directive.RenderParams; +import com.dotcms.rendering.velocity.services.VelocityType; + import com.dotmarketing.business.APILocator; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.contentlet.model.ContentletVersionInfo; @@ -10,6 +14,7 @@ import org.apache.velocity.context.Context; import org.apache.velocity.exception.ResourceNotFoundException; +import java.io.File; import java.io.Writer; public class ContentletDetail extends DotDirective { @@ -17,7 +22,7 @@ public class ContentletDetail extends DotDirective { private static final long serialVersionUID = 1L; - final static String EXTENSION = Config.getStringProperty("VELOCITY_CONTENT_EXTENSION", "content"); + final static String EXTENSION = VelocityType.CONTENT.fileExtension; @Override @@ -28,19 +33,19 @@ public String getName() { @Override - String resolveTemplatePath(final Context context, final Writer writer, final RenderParams params, final String argument) { + String resolveTemplatePath(final Context context, final Writer writer, final RenderParams params, final String[] arguments) { ContentletVersionInfo cv; - + final String argument = arguments[0]; try { cv = APILocator.getVersionableAPI().getContentletVersionInfo(argument, params.language.getId()); if (cv == null) { long defaultLang = APILocator.getLanguageAPI().getDefaultLanguage().getId(); if (defaultLang != params.language.getId()) { cv = APILocator.getVersionableAPI().getContentletVersionInfo(argument, defaultLang); - String inode = (params.live) ? cv.getLiveInode() : cv.getWorkingInode(); - Contentlet test = APILocator.getContentletAPI().find(inode, params.user, !params.editMode); - ContentType type = APILocator.getContentTypeAPI(params.user).find(test.getContentTypeId()); + String inode = (params.mode.showLive) ? cv.getLiveInode() : cv.getWorkingInode(); + Contentlet test = APILocator.getContentletAPI().find(inode, params.user, params.mode.respectAnonPerms); + ContentType type = APILocator.getContentTypeAPI(APILocator.systemUser()).find(test.getContentTypeId()); if(type.baseType() == BaseContentType.CONTENT && !Config.getBooleanProperty("DEFAULT_CONTENT_TO_DEFAULT_LANGUAGE", false)){ throw new ResourceNotFoundException("cannnot find contentlet id " + argument + " lang:" + params.language); } @@ -53,21 +58,10 @@ else if(type.baseType() == BaseContentType.WIDGET && !Config.getBooleanProperty throw new ResourceNotFoundException("cannnot find contentlet id " + argument + " lang:" + params.language); } - // _show_working_ context variable is used on Container Services. If the time machine date is after the Publish - // date of the Contentlet (identifier data) we need to show the working. If not we only show the live. - // - // #if($UtilMethods.isSet($_ident.sysPublishDate) && $_tmdate.after($_ident.sysPublishDate)) - // #set($_show_working_=true) - // - boolean showWorking = false; - if (context.get("_show_working_") != null && (boolean)context.get("_show_working_")) { - showWorking = true; - } - return (params.live && !showWorking) - ? "/live/" + argument + "_" + cv.getLang() + "." + EXTENSION - : "/working/" + argument + "_" + cv.getLang() + "." + EXTENSION; + + return File.separator + params.mode.name() + File.separator + argument + "_" + cv.getLang() + "." + EXTENSION; } } diff --git a/dotCMS/src/main/java/com/dotmarketing/velocity/directive/DotDirective.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/directive/DotDirective.java similarity index 89% rename from dotCMS/src/main/java/com/dotmarketing/velocity/directive/DotDirective.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/directive/DotDirective.java index ad3b6e1d683c..ff8af22012c2 100644 --- a/dotCMS/src/main/java/com/dotmarketing/velocity/directive/DotDirective.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/directive/DotDirective.java @@ -1,4 +1,4 @@ -package com.dotmarketing.velocity.directive; +package com.dotcms.rendering.velocity.directive; import java.io.IOException; import java.io.Writer; @@ -18,9 +18,11 @@ import org.apache.velocity.runtime.parser.node.Node; import org.apache.velocity.runtime.parser.node.SimpleNode; +import com.dotcms.rendering.velocity.directive.RenderParams; +import com.dotcms.rendering.velocity.util.VelocityUtil; + import com.dotmarketing.util.Logger; -import com.dotmarketing.util.VelocityUtil; -import com.dotmarketing.viewtools.VelocityWebUtil; + abstract class DotDirective extends InputBase { @@ -36,7 +38,7 @@ public final int getType() { } - abstract String resolveTemplatePath(Context context, Writer writer, RenderParams params, String argument); + abstract String resolveTemplatePath(Context context, Writer writer, RenderParams params, String[] arguments); final Template loadTemplate(InternalContextAdapter context, String templatePath){ @@ -70,13 +72,24 @@ final public boolean render(InternalContextAdapter context, Writer writer, Node throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { HttpServletRequest request = (HttpServletRequest) context.get("request"); - Object value = node.jjtGetChild(0).value(context); - String argument = value == null ? null : value.toString(); + int args = node.jjtGetNumChildren(); + String[] arguments = new String[args]; + + for(int i=0;i1 && UtilMethods.isSet(arguments[1])) ? arguments[1] : MultiTree.LEGACY_RELATION_TYPE; + + return "/" +params.mode.name() + "/" + id + "/" + uid + "." + VelocityType.CONTAINER.fileExtension ; + + } } diff --git a/dotCMS/src/main/java/com/dotmarketing/velocity/directive/RenderParams.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/directive/RenderParams.java similarity index 77% rename from dotCMS/src/main/java/com/dotmarketing/velocity/directive/RenderParams.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/directive/RenderParams.java index b645202510e3..8d8142d71c9c 100644 --- a/dotCMS/src/main/java/com/dotmarketing/velocity/directive/RenderParams.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/directive/RenderParams.java @@ -1,20 +1,21 @@ -package com.dotmarketing.velocity.directive; +package com.dotcms.rendering.velocity.directive; import javax.servlet.http.HttpServletRequest; +import com.dotcms.rendering.velocity.directive.RenderParams; + import com.dotmarketing.beans.Host; import com.dotmarketing.business.web.WebAPILocator; import com.dotmarketing.portlets.languagesmanager.model.Language; -import com.dotmarketing.util.PageRequestModeUtil; +import com.dotmarketing.util.PageMode; import com.liferay.portal.model.User; public class RenderParams { public static final String RENDER_PARAMS_ATTRIBUTE = "com.dotcms.directive.renderparams"; - final boolean live; final User user; final Language language; final Host currentHost; - final boolean editMode; + final PageMode mode; public RenderParams(HttpServletRequest request) { @@ -24,17 +25,15 @@ public RenderParams(HttpServletRequest request) { RenderParams(HttpServletRequest request, RenderParams params) { if (params != null) { - this.live = params.live; this.user = params.user; this.language = params.language; this.currentHost = params.currentHost; - this.editMode = params.editMode; + this.mode = params.mode; } else { - live = PageRequestModeUtil.isLive(request); + mode = PageMode.get(request); user = WebAPILocator.getUserWebAPI().getUser(request); language = WebAPILocator.getLanguageWebAPI().getLanguage(request); currentHost = WebAPILocator.getHostWebAPI().getHost(request); - editMode = PageRequestModeUtil.isEditMode(request); request.setAttribute(RENDER_PARAMS_ATTRIBUTE, this); } diff --git a/dotCMS/src/main/java/com/dotmarketing/velocity/events/MethodExceptionEventHandlerImpl.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/events/MethodExceptionEventHandlerImpl.java similarity index 96% rename from dotCMS/src/main/java/com/dotmarketing/velocity/events/MethodExceptionEventHandlerImpl.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/events/MethodExceptionEventHandlerImpl.java index 7c3eaa966f65..d80c2a2d4f0c 100644 --- a/dotCMS/src/main/java/com/dotmarketing/velocity/events/MethodExceptionEventHandlerImpl.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/events/MethodExceptionEventHandlerImpl.java @@ -1,4 +1,4 @@ -package com.dotmarketing.velocity.events; +package com.dotcms.rendering.velocity.events; import java.io.BufferedReader; import java.io.IOException; @@ -15,8 +15,10 @@ import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; -import com.dotmarketing.util.VelocityUtil; -import com.dotmarketing.velocity.DotResourceLoader; + +import com.dotcms.rendering.velocity.services.DotResourceLoader; +import com.dotcms.rendering.velocity.util.VelocityUtil; + public class MethodExceptionEventHandlerImpl implements org.apache.velocity.app.event.MethodExceptionEventHandler { diff --git a/dotCMS/src/main/java/com/dotmarketing/velocity/events/NullSetEventHandlerImpl.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/events/NullSetEventHandlerImpl.java similarity index 82% rename from dotCMS/src/main/java/com/dotmarketing/velocity/events/NullSetEventHandlerImpl.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/events/NullSetEventHandlerImpl.java index c19e8dcbde2b..7a7bc889e05d 100644 --- a/dotCMS/src/main/java/com/dotmarketing/velocity/events/NullSetEventHandlerImpl.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/events/NullSetEventHandlerImpl.java @@ -1,4 +1,4 @@ -package com.dotmarketing.velocity.events; +package com.dotcms.rendering.velocity.events; public class NullSetEventHandlerImpl implements org.apache.velocity.app.event.NullSetEventHandler { diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/ContainerLoader.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/ContainerLoader.java new file mode 100644 index 000000000000..9de35a8df763 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/ContainerLoader.java @@ -0,0 +1,261 @@ +package com.dotcms.rendering.velocity.services; + +import com.dotcms.contenttype.business.ContentTypeAPI; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.rendering.velocity.util.VelocityUtil; + +import com.dotmarketing.beans.ContainerStructure; +import com.dotmarketing.beans.Identifier; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.CacheLocator; +import com.dotmarketing.business.DotStateException; +import com.dotmarketing.business.VersionableAPI; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.portlets.containers.model.Container; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; +import com.dotmarketing.util.UtilMethods; + +import java.io.InputStream; +import java.io.StringWriter; +import java.util.List; + +import org.apache.velocity.runtime.resource.ResourceManager; + +/** + * @author will + */ +public class ContainerLoader implements DotLoader { + +public static final String SHOW_PRE_POST_LOOP="SHOW_PRE_POST_LOOP"; + @Override + public InputStream writeObject(String id1, String id2, PageMode mode, String language, final String filePath) + throws DotDataException, DotSecurityException { + + VersionableAPI versionableAPI = APILocator.getVersionableAPI(); + Container container = null; + if (mode.showLive) { + container = (Container) versionableAPI.findLiveVersion(id1, sysUser(), true); + } else { + container = (Container) versionableAPI.findWorkingVersion(id1, sysUser(), true); + } + + Logger.debug(this, "DotResourceLoader:\tWriting out container inode = " + container.getInode()); + + return this.buildVelocity(container, id2, mode, filePath); + } + + + @Override + public void invalidate(Object obj, PageMode mode) { + Container container = (Container) obj; + String folderPath = mode.name() + java.io.File.separator; + String velocityRootPath = VelocityUtil.getVelocityRootPath(); + velocityRootPath += java.io.File.separator; + String filePath = folderPath + container.getIdentifier() + "." + VelocityType.CONTAINER.fileExtension; + java.io.File f = new java.io.File(velocityRootPath + filePath); + f.delete(); + DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); + vc.remove(ResourceManager.RESOURCE_TEMPLATE + filePath); + } + + private InputStream buildVelocity(Container container, String uuid, PageMode mode, String filePath) throws DotDataException, DotSecurityException { + + ContentTypeAPI typeAPI = APILocator.getContentTypeAPI(APILocator.systemUser()); + StringBuilder sb = new StringBuilder(); + + + List csList = APILocator.getContainerAPI() + .getContainerStructures(container); + + + // let's write this puppy out to our file + sb.append("#set ($SERVER_NAME =$host.getHostname() )"); + sb.append("#set ($CONTAINER_IDENTIFIER_INODE = '") + .append(container.getIdentifier()) + .append("')"); + sb.append("#set ($CONTAINER_UNIQUE_ID = '") + .append(uuid) + .append("')"); + sb.append("#set ($CONTAINER_INODE = '") + .append(container.getInode()) + .append("')"); + sb.append("#set ($CONTAINER_MAX_CONTENTLETS = ") + .append(container.getMaxContentlets()) + .append(")"); + sb.append("#set ($containerInode = '") + .append(container.getInode()) + .append("')"); + + sb.append("#set ($CONTENTLETS = $contentletList") + .append(container.getIdentifier()) + .append(uuid) + .append(")"); + sb.append("#set ($CONTAINER_NUM_CONTENTLETS = $totalSize") + .append(container.getIdentifier()) + .append(uuid) + .append(")"); + + sb.append("#if(!$CONTAINER_NUM_CONTENTLETS)") + .append("#set($CONTAINER_NUM_CONTENTLETS = 0)") + .append("#end"); + + + + sb.append("#set ($CONTAINER_NAME = \"") + .append(UtilMethods.espaceForVelocity(container.getTitle())) + .append("\")"); + + if (UtilMethods.isSet(container.getNotes())) { + sb.append("#set ($CONTAINER_NOTES = \"") + .append(UtilMethods.espaceForVelocity(container.getNotes())) + .append("\")"); + } else { + sb.append("#set ($CONTAINER_NOTES = \"\")"); + } + + + if (mode == PageMode.EDIT_MODE) { + StringWriter editWrapperDiv = new StringWriter(); + editWrapperDiv.append(""); + sb.append("#if($" + SHOW_PRE_POST_LOOP + ")"); + sb.append(editWrapperDiv); + sb.append("#end"); + + } + + + + // if the container needs to get its contentlets + if (container.getMaxContentlets() > 0) { + + + // pre loop if it exists + if (UtilMethods.isSet(container.getPreLoop())) { + sb.append("#if($" + SHOW_PRE_POST_LOOP + ")"); + sb.append(container.getPreLoop()); + sb.append("#end"); + } + // sb.append("$contentletList" + identifier.getId() + uuid + "
"); + + // START CONTENT LOOP + sb.append("#foreach ($contentletId in $contentletList") + .append(container.getIdentifier()) + .append(uuid) + .append(")"); + + + + // sb.append("\n#if($webapi.canParseContent($contentletId,"+EDIT_MODE+")) "); + sb.append("#set($_show_working_=false)"); + + // if timemachine future enabled + sb.append("#if($UtilMethods.isSet($request.getSession(false)) && $request.session.getAttribute(\"tm_date\"))"); + sb.append("#set($_tmdate=$date.toDate($webapi.parseLong($request.session.getAttribute(\"tm_date\"))))"); + sb.append("#set($_ident=$webapi.findIdentifierById($contentletId))"); + + // if the content has expired we rewrite the identifier so it isn't loaded + sb.append("#if($UtilMethods.isSet($_ident.sysExpireDate) && $_tmdate.after($_ident.sysExpireDate))"); + sb.append("#set($contentletId='')"); + sb.append("#end"); + + // if the content should be published then force to show the working version + sb.append("#if($UtilMethods.isSet($_ident.sysPublishDate) && $_tmdate.after($_ident.sysPublishDate))"); + sb.append("#set($_show_working_=true)"); + sb.append("#end"); + + sb.append("#if(! $webapi.contentHasLiveVersion($contentletId) && ! $_show_working_)") + .append("#set($contentletId='')") // working contentlet still not published + .append("#end"); + sb.append("#end"); + + sb.append("#set($CONTENT_INODE = '')"); + sb.append("#if($contentletId != '')"); + sb.append("#contentDetail($contentletId)"); + sb.append("#end"); + + + // ##Checking permission to see content + if (mode.showLive) { + sb.append("#if($contents.doesUserHasPermission($CONTENT_INODE, 1, $user, true))"); + } + + // ### START BODY ### + sb.append("#if($isWidget == true)"); + sb.append("$widgetCode"); + sb.append("#else"); + + for (int i = 0; i < csList.size(); i++) { + ContainerStructure cs = csList.get(i); + String ifelse = (i == 0) ? "if" : "elseif"; + sb.append("#" + ifelse + "($ContentletStructure ==\"" + cs.getStructureId() + "\")"); + sb.append(cs.getCode()); + } + if (csList.size() > 0) { + sb.append("#end"); + } + // ### END BODY ### + sb.append(" #end "); + + if (mode.showLive) { + sb.append("#end "); + } + + + + + // ##End of foreach loop + sb.append("#end "); + + + + + // post loop if it exists + if (UtilMethods.isSet(container.getPostLoop())) { + sb.append("#if($" + SHOW_PRE_POST_LOOP + ")"); + sb.append(container.getPostLoop()); + if (mode == PageMode.EDIT_MODE) { + sb.append(""); + } + sb.append("#end "); + } + + } else { + + sb.append(container.getCode()); + } + + + + return writeOutVelocity(filePath, sb.toString()); + } + + + + + + +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/ContentTypeLoader.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/ContentTypeLoader.java new file mode 100644 index 000000000000..324786a01c05 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/ContentTypeLoader.java @@ -0,0 +1,303 @@ +package com.dotcms.rendering.velocity.services; + + + +import com.dotcms.contenttype.business.ContentTypeAPI; +import com.dotcms.contenttype.model.field.CheckboxField; +import com.dotcms.contenttype.model.field.DateField; +import com.dotcms.contenttype.model.field.DateTimeField; +import com.dotcms.contenttype.model.field.Field; +import com.dotcms.contenttype.model.field.FileField; +import com.dotcms.contenttype.model.field.ImageField; +import com.dotcms.contenttype.model.field.RadioField; +import com.dotcms.contenttype.model.field.SelectField; +import com.dotcms.contenttype.model.field.TextAreaField; +import com.dotcms.contenttype.model.field.TextField; +import com.dotcms.contenttype.model.field.TimeField; +import com.dotcms.contenttype.model.field.WysiwygField; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.rendering.velocity.util.VelocityUtil; + +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.CacheLocator; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; +import com.dotmarketing.util.UtilMethods; + +import java.io.File; +import java.io.InputStream; +import java.util.List; + +import org.apache.velocity.runtime.resource.ResourceManager; + +/** + * @author will + */ +public class ContentTypeLoader implements DotLoader { + + private long fakeIdentifier = Long.MAX_VALUE; + private long fakeInode = Long.MAX_VALUE; + private String fakeTitle = "Content Title"; + + + + public void invalidate(ContentType contentType, PageMode mode) { + removeContentTypeFile(contentType); + } + + + + public InputStream buildVelocity(ContentType type, String filePath, PageMode mode ) { + + // let's write this puppy out to our file + StringBuilder sb = new StringBuilder(); + + // CONTENTLET CONTROLS BEGIN + sb.append("#set( $EDIT_CONTENT_PERMISSION =$EDIT_CONTENT_PERMISSION") + .append(fakeInode) + .append(" )"); + sb.append("#set( $CONTENT_INODE ='") + .append(fakeInode) + .append("' )"); + sb.append("#set( $IDENTIFIER_INODE ='") + .append(fakeIdentifier) + .append("' )"); + + // set all properties from the contentlet + sb.append("#set( $ContentInode ='") + .append(fakeInode) + .append("' )"); + sb.append("#set( $ContentIdentifier ='") + .append(fakeIdentifier) + .append("' )"); + sb.append("#set( $ContentletTitle =\"") + .append(UtilMethods.espaceForVelocity(fakeTitle)) + .append("\" )"); + + // Structure fields + List fields = type.fields(); + + + for (Field field : fields) { + + + String contField = field.dbColumn(); + String contFieldValue = null; + Object contFieldValueObject = null; + if (UtilMethods.isSet(contField)) { + try { + contFieldValueObject = field.name(); + contFieldValue = contFieldValueObject == null ? "" : contFieldValueObject.toString(); + } catch (Exception e) { + Logger.error(this.getClass(), "writeContentletToFile: " + e.getMessage()); + } + if (!(field instanceof DateTimeField || field instanceof DateField || field instanceof TimeField)) { + sb.append("#set( $") + .append(field.variable()) + .append(" =\"") + .append(UtilMethods.espaceForVelocity(contFieldValue) + .trim()) + .append("\" )"); + } + } + String fv = field.values() != null ? field.values() : ""; + if (field instanceof TextField || field instanceof TextAreaField || field instanceof WysiwygField) { + sb.append("#set( $") + .append(field.variable()) + .append(" =\"[ #fixBreaks($") + .append(field.variable()) + .append(") ]\")"); + } else if (field instanceof ImageField) { + // Identifier id = (Identifier) InodeFactory.getChildOfClassByRelationType(content, + // Identifier.class, field.getFieldRelationType()); + String uri = "/html/images/shim.gif"; + sb.append("#set( $") + .append(field.variable()) + .append("ImageInode =\"") + .append(Long.MAX_VALUE) + .append("\" )"); + sb.append("#set( $") + .append(field.variable()) + .append("ImageWidth =\"") + .append(150) + .append("\" )"); // Original value was 165 + sb.append("#set( $") + .append(field.variable()) + .append("ImageHeight =\"") + .append(150) + .append("\" )"); // Originak value was 65 + sb.append("#set( $") + .append(field.variable()) + .append("ImageExtension =\"gif\" )"); + sb.append("#set( $") + .append(field.variable()) + .append("ImageURI =\"") + .append(uri) + .append("\" )"); + sb.append("#set( $") + .append(field.variable()) + .append("ImageTitle =\"[ Test Image Structure ]\" )"); + } else if (field instanceof FileField) { + // Identifier id = (Identifier) InodeFactory.getChildOfClassByRelationType(content, + // Identifier.class, field.getFieldRelationType()); + String uri = "/html/images/shim.gif"; + sb.append("#set( $") + .append(field.variable()) + .append("FileInode =\"") + .append(Long.MAX_VALUE) + .append("\" )"); + sb.append("#set( $") + .append(field.variable()) + .append("FileExtension =\"gif\" )"); + sb.append("#set( $") + .append(field.variable()) + .append("FileURI =\"") + .append(uri) + .append("\" )"); + sb.append("#set( $") + .append(field.variable()) + .append("FileTitle =\"[ Test File Structure ]\" )"); + } else if (field instanceof SelectField) { + sb.append("#set( $") + .append(field.variable()) + .append("SelectLabelsValues = \"") + .append(fv.replaceAll("\\r\\n", " ") + .replaceAll("\\n", " ")) + .append("\")"); + } else if (field instanceof RadioField) { + sb.append("#set( $") + .append(field.variable()) + .append("RadioLabelsValues = \"") + .append(fv.replaceAll("\\r\\n", " ") + .replaceAll("\\n", " ")) + .append("\" )"); + } else if (field instanceof CheckboxField) { + sb.append("#set( $") + .append(field.variable()) + .append("CheckboxLabelsValues = \"") + .append(fv.replaceAll("\\r\\n", " ") + .replaceAll("\\n", " ")) + .append("\" )"); + } else if (field instanceof DateField) { + sb.append("#set( $") + .append(field.variable()) + .append(" =\"[ ") + .append(field.variable()) + .append(" ]\")"); + sb.append("#set( $") + .append(field.variable()) + .append("ShortFormat =\"[ ") + .append(field.variable()) + .append(" ]\")"); + sb.append("#set( $") + .append(field.variable()) + .append("DBFormat =\"[ ") + .append(field.variable()) + .append(" ]\")"); + } else if (field instanceof TimeField) { + sb.append("#set( $") + .append(field.variable()) + .append("ShortFormat =\"[ ") + .append(field.variable()) + .append(" ]\")"); + sb.append("#set( $") + .append(field.variable()) + .append(" =\"[ ") + .append(field.variable()) + .append("\" ])"); + } else if (field instanceof DateTimeField) { + sb.append("#set( $") + .append(field.variable()) + .append(" =\"[ ") + .append(field.variable()) + .append(" ] \")"); + sb.append("#set( $") + .append(field.variable()) + .append("ShortFormat =\"[ ") + .append(field.variable()) + .append(" ]\")"); + sb.append("#set( $") + .append(field.variable()) + .append("LongFormat =\"[ ") + .append(field.variable()) + .append(" ]\")"); + sb.append("#set( $") + .append(field.variable()) + .append("DBFormat =\"[ ") + .append(field.variable()) + .append(" ]\")"); + } + } + + // sets the categories as a list on velocity + sb.append("#set( $ContentletCategories =[] )"); + sb.append("#set( $ContentletCategoryNames =[] )"); + + + // This is code is repeated becuase the bug GETTYS-268, the content variables were been + // overwritten + // by the parse inside the some of the content fields + // To edit the look, see WEB-INF/velocity/static/preview/content_controls.vtl + + sb.append("#set( $EDIT_CONTENT_PERMISSION =$EDIT_CONTENT_PERMISSION") + .append(fakeIdentifier) + .append(" )"); + sb.append("#set( $CONTENT_INODE ='") + .append(fakeInode) + .append("' )"); + sb.append("#set( $IDENTIFIER_INODE ='") + .append(fakeIdentifier) + .append("' )"); + + sb.append("#set( $ContentInode ='") + .append(fakeInode) + .append("' )"); + sb.append("#set( $ContentIdentifier ='") + .append(fakeIdentifier) + .append("' )"); + sb.append("#set( $ContentletTitle =\"") + .append(UtilMethods.espaceForVelocity(fakeTitle)) + .append("\" )"); + sb.append("#set( $isWidget = false)"); + + return writeOutVelocity(filePath, sb.toString()); + } + + public void removeContentTypeFile(ContentType contentType) { + + } + + @Override + public InputStream writeObject(String id1, String id2, PageMode mode, String language, String filePath) + throws DotDataException, DotSecurityException { + + ContentTypeAPI contentTypeAPI = APILocator.getContentTypeAPI(sysUser()); + + + // Search for the given ContentType inode + ContentType foundContentType = contentTypeAPI.find(id1); + + + return buildVelocity(foundContentType, filePath, mode); + + } + + + + @Override + public void invalidate(Object obj, PageMode mode) { + ContentType contentType = (ContentType)obj; + String folderPath = mode.name() + File.separator; + String filePath = folderPath + contentType.inode() + "." + VelocityType.CONTENT_TYPE.fileExtension; + + String velocityRootPath = VelocityUtil.getVelocityRootPath(); + String absolutPath = velocityRootPath + File.separator + filePath; + java.io.File f = new java.io.File(absolutPath); + f.delete(); + DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); + vc.remove(ResourceManager.RESOURCE_TEMPLATE + filePath); + + } +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/ContentletLoader.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/ContentletLoader.java new file mode 100644 index 000000000000..7e2048530ee2 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/ContentletLoader.java @@ -0,0 +1,851 @@ +package com.dotcms.rendering.velocity.services; + +import com.dotcms.contenttype.model.field.BinaryField; +import com.dotcms.contenttype.model.field.CategoryField; +import com.dotcms.contenttype.model.field.CheckboxField; +import com.dotcms.contenttype.model.field.ConstantField; +import com.dotcms.contenttype.model.field.DateField; +import com.dotcms.contenttype.model.field.DateTimeField; +import com.dotcms.contenttype.model.field.Field; +import com.dotcms.contenttype.model.field.FileField; +import com.dotcms.contenttype.model.field.HiddenField; +import com.dotcms.contenttype.model.field.HostFolderField; +import com.dotcms.contenttype.model.field.ImageField; +import com.dotcms.contenttype.model.field.RadioField; +import com.dotcms.contenttype.model.field.SelectField; +import com.dotcms.contenttype.model.field.TagField; +import com.dotcms.contenttype.model.field.TimeField; +import com.dotcms.contenttype.model.type.BaseContentType; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.rendering.velocity.util.VelocityUtil; +import com.dotcms.rendering.velocity.viewtools.LanguageWebAPI; +import com.dotcms.services.VanityUrlServices; + +import com.dotmarketing.beans.Identifier; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.CacheLocator; +import com.dotmarketing.business.DotStateException; +import com.dotmarketing.comparators.ContentComparator; +import com.dotmarketing.comparators.WebAssetSortOrderComparator; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.portlets.categories.business.CategoryAPI; +import com.dotmarketing.portlets.categories.model.Category; +import com.dotmarketing.portlets.contentlet.business.ContentletAPI; +import com.dotmarketing.portlets.contentlet.business.DotContentletStateException; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.form.business.FormAPI; +import com.dotmarketing.portlets.languagesmanager.business.LanguageAPI; +import com.dotmarketing.portlets.languagesmanager.model.Language; +import com.dotmarketing.portlets.structure.model.Structure; +import com.dotmarketing.util.InodeUtils; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; +import com.dotmarketing.util.UtilMethods; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.apache.velocity.exception.ResourceNotFoundException; +import org.apache.velocity.runtime.resource.ResourceManager; + +import com.liferay.portal.model.User; +import com.liferay.util.FileUtil; + +/** + * @author will + */ +public class ContentletLoader implements DotLoader { + + private CategoryAPI categoryAPI = APILocator.getCategoryAPI(); + + public CategoryAPI getCategoryAPI() { + return categoryAPI; + } + + public void setCategoryAPI(CategoryAPI categoryAPI) { + this.categoryAPI = categoryAPI; + } + + + + public InputStream buildVelocity(Contentlet content, Identifier identifier, PageMode mode, String filePath) + throws DotDataException, DotSecurityException { + StringBuilder sb = new StringBuilder(); + + ContentletAPI conAPI = APILocator.getContentletAPI(); + + User systemUser = sysUser(); + + // let's write this puppy out to our file + + + + StringWriter contentDiv = new StringWriter(); + contentDiv.append(""); + + + sb.append("#if($EDIT_MODE)") + .append(contentDiv) + .append("#end"); + + + + // CONTENTLET CONTROLS BEGIN + sb.append("#if($EDIT_MODE)"); + sb.append("#set( $EDIT_CONTENT_PERMISSION=$EDIT_CONTENT_PERMISSION") + .append(identifier.getId()) + .append(")"); + sb.append("#end"); + + sb.append("#set($CONTENT_INODE='") + .append(content.getInode()) + .append("' )") + .append("#set($IDENTIFIER_INODE='") + .append(identifier.getId()) + .append("' )"); + + // set all properties from the contentlet + sb.append("#set($ContentInode='") + .append(content.getInode()) + .append("' )") + .append("#set($ContentIdentifier='") + .append(identifier.getId()) + .append("' )") + .append("#set($ContentletTitle=\"") + .append(UtilMethods.espaceForVelocity(conAPI.getName(content, APILocator.getUserAPI() + .getSystemUser(), true))) + .append("\" )"); + String modDateStr = UtilMethods.dateToHTMLDate((Date) content.getModDate(), "yyyy-MM-dd H:mm:ss"); + sb.append("#set($ContentLastModDate= $date.toDate(\"yyyy-MM-dd H:mm:ss\", \"") + .append(modDateStr) + .append("\"))") + .append("#set($ContentLastModUserId= \"") + .append(content.getModUser()) + .append("\")"); + if (content.getOwner() != null) + sb.append("#set($ContentOwnerId= \"") + .append(content.getOwner()) + .append("\")"); + + // Structure fields + + ContentType type = content.getContentType(); + + List fields = type.fields(); + + + String widgetCode = ""; + + for (Field field : fields) { + + String contField = field.dbColumn(); + String contFieldValue = null; + Object contFieldValueObject = null; + String velPath = mode.name() + "/"; + if (field instanceof HiddenField || field instanceof ConstantField) { + if (field.variable() + .equals("widgetPreexecute")) { + continue; + } + if (field.variable() + .equals("widgetCode")) { + widgetCode = "#set($" + field.variable() + "=$velutil.mergeTemplate(\"" + velPath + content.getInode() + + File.separator + field.inode() + "." + VelocityType.FIELD.fileExtension + "\"))"; + continue; + } else { + String fieldValues = field.values() == null ? "" : field.values(); + if (fieldValues.contains("$") || fieldValues.contains("#")) { + sb.append("#set($") + .append(field.variable()) + .append("= $velutil.mergeTemplate(\"") + .append(velPath) + .append(content.getInode()) + .append(File.separator) + .append(field.inode()) + .append(".") + .append(VelocityType.FIELD.fileExtension) + .append("\"))"); + } else { + sb.append("#set($") + .append(field.variable()) + .append("= \"") + .append(UtilMethods.espaceForVelocity(fieldValues) + .trim()) + .append("\")"); + } + continue; + } + } + + + if (UtilMethods.isSet(contField)) { + try { + contFieldValueObject = conAPI.getFieldValue(content, field); + contFieldValue = contFieldValueObject == null ? "" : contFieldValueObject.toString(); + } catch (Exception e) { + Logger.error(this.getClass(), "writeContentletToFile: " + e.getMessage()); + } + if (!(field instanceof DateTimeField || field instanceof DateField || field instanceof TimeField)) { + if (contFieldValue.contains("$") || contFieldValue.contains("#")) { + sb.append("#set($") + .append(field.variable()) + .append("=$velutil.mergeTemplate(\"") + .append(velPath) + .append(content.getInode()) + .append(File.separator) + .append(field.inode()) + .append(".") + .append(VelocityType.FIELD.fileExtension) + .append("\"))"); + } else { + sb.append("#set($") + .append(field.variable()) + .append("=\"") + .append(UtilMethods.espaceForVelocity(contFieldValue) + .trim()) + .append("\")"); + } + } + + } + + if (field instanceof ImageField || field instanceof FileField) { + String identifierValue = content.getStringProperty(field.variable()); + if (InodeUtils.isSet(identifierValue)) { + if (PageMode.EDIT_MODE == mode) { + sb.append("#set($") + .append(field.variable()) + .append("Object= $filetool.getFile('") + .append(identifierValue) + .append("',false,") + .append(content.getLanguageId()) + .append(" ))"); + } else { + sb.append("#set($") + .append(field.variable()) + .append("Object= $filetool.getFile('") + .append(identifierValue) + .append("',true,") + .append(content.getLanguageId()) + .append(" ))"); + } + } else { + sb.append("#set($") + .append(field.variable()) + .append("Object= $filetool.getNewFile())"); + } + if (field instanceof ImageField) { + sb.append("#set($") + .append(field.variable()) + .append("ImageInode=$!{") + .append(field.variable()) + .append("Object.getInode()} )"); + sb.append("#set($") + .append(field.variable()) + .append("ImageIdentifier=$!{") + .append(field.variable()) + .append("Object.getIdentifier()} )"); + sb.append("#set($") + .append(field.variable()) + .append("ImageWidth=$!{") + .append(field.variable()) + .append("Object.getWidth()} )"); + sb.append("#set($") + .append(field.variable()) + .append("ImageHeight=$!{") + .append(field.variable()) + .append("Object.getHeight()} )"); + sb.append("#set($") + .append(field.variable()) + .append("ImageExtension=$!{") + .append(field.variable()) + .append("Object.getExtension()} )"); + sb.append("#set($") + .append(field.variable()) + .append("ImageURI=$filetool.getURI($!{") + .append(field.variable()) + .append("Object}, ") + .append(content.getLanguageId()) + .append(" ))"); + sb.append("#set($") + .append(field.variable()) + .append("ImageTitle=$UtilMethods.espaceForVelocity($!{") + .append(field.variable()) + .append("Object.getTitle()}) )"); + sb.append("#set($") + .append(field.variable()) + .append("ImageFriendlyName=$UtilMethods.espaceForVelocity($!{") + .append(field.variable()) + .append("Object.getFriendlyName()}) )"); + + sb.append("#set($") + .append(field.variable()) + .append("ImagePath=$!{") + .append(field.variable()) + .append("Object.getPath()})"); + sb.append("#set($") + .append(field.variable()) + .append("ImageName=$!{") + .append(field.variable()) + .append("Object.getFileName()})"); + + } else { + sb.append("#set($") + .append(field.variable()) + .append("FileInode=$!{") + .append(field.variable()) + .append("Object.getInode()} )"); + sb.append("#set($") + .append(field.variable()) + .append("FileIdentifier=$!{") + .append(field.variable()) + .append("Object.getIdentifier()} )"); + sb.append("#set($") + .append(field.variable()) + .append("FileExtension=$!{") + .append(field.variable()) + .append("Object.getExtension()} )"); + sb.append("#set($") + .append(field.variable()) + .append("FileURI=$filetool.getURI($!{") + .append(field.variable()) + .append("Object}, ") + .append(content.getLanguageId()) + .append(" ))"); + sb.append("#set($") + .append(field.variable()) + .append("FileTitle=$!{") + .append(field.variable()) + .append("Object.getTitle()} )"); + sb.append("#set($") + .append(field.variable()) + .append("FileFriendlyName=$UtilMethods.espaceForVelocity($!{") + .append(field.variable()) + .append("Object.getFriendlyName()} ))"); + + sb.append("#set($") + .append(field.variable()) + .append("FilePath=$UtilMethods.espaceForVelocity($!{") + .append(field.variable()) + .append("Object.getPath()}) )"); + sb.append("#set($") + .append(field.variable()) + .append("FileName=$UtilMethods.espaceForVelocity($!{") + .append(field.variable()) + .append("Object.getFileName()} ))"); + } + } // http://jira.dotmarketing.net/browse/DOTCMS-2178 + else if (field instanceof BinaryField) { + java.io.File binFile; + String fileName = ""; + String filesize = ""; + try { + binFile = content.getBinary(field.variable()); + if (binFile != null) { + fileName = binFile.getName(); + filesize = FileUtil.getsize(binFile); + } + } catch (IOException e) { + Logger.error(this.getClass(), "Unable to retrive binary file for content id " + content.getIdentifier() + + " field " + field.variable(), e); + continue; + } + sb.append("#set($") + .append(field.variable()) + .append("BinaryFileTitle=\"") + .append(UtilMethods.espaceForVelocity(fileName)) + .append("\" )"); + sb.append("#set($") + .append(field.variable()) + .append("BinaryFileSize=\"") + .append(UtilMethods.espaceForVelocity(filesize)) + .append("\" )"); + String binaryFileURI = fileName.length() > 0 + ? UtilMethods.espaceForVelocity("/contentAsset/raw-data/" + content.getIdentifier() + "/" + + field.variable() + "/" + content.getInode()) + : ""; + sb.append("#set($") + .append(field.variable()) + .append("BinaryFileURI=\"") + .append(binaryFileURI) + .append("\" )"); + } else if (field instanceof SelectField) { + sb.append("#set($") + .append(field.variable()) + .append("SelectLabelsValues=\"") + .append(field.values() + .replaceAll("\\r\\n", " ") + .replaceAll("\\n", " ")) + .append("\")"); + } else if (field instanceof RadioField) { + sb.append("#set($") + .append(field.variable()) + .append("RadioLabelsValues=\"") + .append(field.values() + .replaceAll("\\r\\n", " ") + .replaceAll("\\n", " ")) + .append("\" )"); + } else if (field instanceof CheckboxField) { + sb.append("#set($") + .append(field.variable()) + .append("CheckboxLabelsValues=\"") + .append(field.values() + .replaceAll("\\r\\n", " ") + .replaceAll("\\n", " ")) + .append("\" )"); + } else if (field instanceof DateField) { + String shortFormat = ""; + String dbFormat = ""; + if (contFieldValueObject != null && contFieldValueObject instanceof Date) { + shortFormat = UtilMethods.dateToHTMLDate((Date) contFieldValueObject, "MM/dd/yyyy"); + dbFormat = UtilMethods.dateToHTMLDate((Date) contFieldValueObject, "yyyy-MM-dd"); + } + sb.append("#set($") + .append(field.variable()) + .append("=$date.toDate(\"yyyy-MM-dd\", \"") + .append(dbFormat) + .append("\"))"); + sb.append("#set($") + .append(field.variable()) + .append("ShortFormat=\"") + .append(shortFormat) + .append("\" )"); + sb.append("#set($") + .append(field.variable()) + .append("DBFormat=\"") + .append(dbFormat) + .append("\" )"); + } else if (field instanceof TimeField) { + String shortFormat = ""; + if (contFieldValueObject != null && contFieldValueObject instanceof Date) { + shortFormat = UtilMethods.dateToHTMLDate((Date) contFieldValueObject, "H:mm:ss"); + } + sb.append("#set( $") + .append(field.variable()) + .append("ShortFormat=\"") + .append(shortFormat) + .append("\" )"); + sb.append("#set( $") + .append(field.variable()) + .append("= $date.toDate(\"H:mm:ss\", \"") + .append(shortFormat) + .append("\"))"); + } else if (field instanceof DateTimeField) { + String shortFormat = ""; + String longFormat = ""; + String dbFormat = ""; + if (contFieldValueObject != null && contFieldValueObject instanceof Date) { + shortFormat = UtilMethods.dateToHTMLDate((Date) contFieldValueObject, "MM/dd/yyyy"); + longFormat = UtilMethods.dateToHTMLDate((Date) contFieldValueObject, "MM/dd/yyyy H:mm:ss"); + dbFormat = UtilMethods.dateToHTMLDate((Date) contFieldValueObject, "yyyy-MM-dd H:mm:ss"); + } + sb.append("#set( $") + .append(field.variable()) + .append("= $date.toDate(\"yyyy-MM-dd H:mm:ss\", \"") + .append(dbFormat) + .append("\"))"); + sb.append("#set( $") + .append(field.variable()) + .append("ShortFormat=\"") + .append(shortFormat) + .append("\" )"); + sb.append("#set( $") + .append(field.variable()) + .append("LongFormat=\"") + .append(longFormat) + .append("\" )"); + sb.append("#set( $") + .append(field.variable()) + .append("DBFormat=\"") + .append(dbFormat) + .append("\" )"); + } // http://jira.dotmarketing.net/browse/DOTCMS-2869 + // else if (field.getFieldType().equals(Field.FieldType.CUSTOM_FIELD.toString())){ + // sb.append("#set( $" + field.variable() + "Code=\"" + + // UtilMethods.espaceForVelocity(field.getValues()) + "\" )"); + // }//http://jira.dotmarketing.net/browse/DOTCMS-3232 + else if (field instanceof HostFolderField) { + if (InodeUtils.isSet(content.getFolder())) { + sb.append("#set( $ConHostFolder='") + .append(content.getFolder()) + .append("' )"); + } else { + sb.append("#set( $ConHostFolder='") + .append(content.getHost()) + .append("' )"); + } + } + + else if (field instanceof CategoryField) { + + // Get the Category Field + Category category = categoryAPI.find(field.values(), systemUser, false); + // Get all the Contentlets Categories + List selectedCategories = categoryAPI.getParents(content, systemUser, false); + + // Initialize variables + String catInodes = ""; + Set categoryList = new HashSet(); + List categoryTree = categoryAPI.getAllChildren(category, systemUser, false); + + if (selectedCategories.size() > 0 && categoryTree != null) { + for (int k = 0; k < categoryTree.size(); k++) { + Category cat = (Category) categoryTree.get(k); + for (Category categ : selectedCategories) { + if (categ.getInode() + .equalsIgnoreCase(cat.getInode())) { + categoryList.add(cat); + } + } + } + } + + if (categoryList.size() > 0) { + StringBuilder catbuilder = new StringBuilder(); + Iterator it = categoryList.iterator(); + while (it.hasNext()) { + Category cat = (Category) it.next(); + catbuilder.append("\"") + .append(cat.getInode()) + .append("\""); + if (it.hasNext()) { + catbuilder.append(","); + } + } + catInodes = catbuilder.toString(); + + sb.append("#set( $") + .append(field.variable()) + .append("FilteredCategories=$categories.filterCategoriesByUserPermissions([") + .append(catInodes) + .append("] ))"); + sb.append("#set( $") + .append(field.variable()) + .append("Categories=$categories.fetchCategoriesInodes($") + .append(field.variable()) + .append("FilteredCategories))"); + sb.append("#set( $") + .append(field.variable()) + .append("CategoriesNames=$categories.fetchCategoriesNames($") + .append(field.variable()) + .append("FilteredCategories))"); + sb.append("#set( $") + .append(field.variable()) + .append("=$") + .append(field.variable()) + .append("Categories)"); + sb.append("#set( $") + .append(field.variable()) + .append("CategoriesKeys=$categories.fetchCategoriesKeys($") + .append(field.variable()) + .append("FilteredCategories))"); + } else { + sb.append("#set( $") + .append(field.variable()) + .append("FilteredCategories=$contents.getEmptyList())"); + sb.append("#set( $") + .append(field.variable()) + .append("Categories=$contents.getEmptyList())"); + sb.append("#set( $") + .append(field.variable()) + .append("CategoriesNames=$contents.getEmptyList())"); + sb.append("#set( $") + .append(field.variable()) + .append("=$contents.getEmptyList())"); + sb.append("#set( $") + .append(field.variable()) + .append("CategoriesKeys=$contents.getEmptyList())"); + } + } else if (field instanceof TagField) { + content.setTags(); + String value = content.getStringProperty(field.variable()); + sb.append("#set($") + .append(field.variable()) + .append("=\"") + .append(UtilMethods.espaceForVelocity(value) + .trim()) + .append("\")"); + } + } + + + // get the contentlet categories to make a list + String categories = ""; + Set categoryList = new HashSet(categoryAPI.getParents(content, systemUser, false)); + if (categoryList != null && categoryList.size() > 0) { + StringBuilder catbuilder = new StringBuilder(); + Iterator it = categoryList.iterator(); + while (it.hasNext()) { + Category category = (Category) it.next(); + catbuilder.append("\"") + .append(category.getInode()) + .append("\""); + if (it.hasNext()) { + catbuilder.append(","); + } + } + categories = catbuilder.toString(); + + sb.append("#set($ContentletFilteredCategories=$categories.filterCategoriesByUserPermissions([") + .append(categories) + .append("] ))"); + sb.append("#set($ContentletCategories=$categories.fetchCategoriesInodes($ContentletFilteredCategories))"); + sb.append("#set($ContentletCategoryNames=$categories.fetchCategoriesNames($ContentletFilteredCategories))"); + sb.append("#set($ContentletCategoryKeys=$categories.fetchCategoriesKeys($ContentletFilteredCategories))"); + } else { + sb.append("#set($ContentletFilteredCategories=$contents.getEmptyList())"); + sb.append("#set($ContentletCategories=$contents.getEmptyList())"); + sb.append("#set($ContentletCategoryNames=$contents.getEmptyList())"); + sb.append("#set($ContentletCategoryKeys=$contents.getEmptyList())"); + } + + // This needs to be here because the all fields like cats etc.. need to be parsed first and + // it needs to be before + // the $CONTENT_INODE is reset sb.append("#set( $CONTENT_INODE=\"" + content.getInode() + + // "\" )"); + // http://jira.dotmarketing.net/browse/DOTCMS-2808 + sb.append(widgetCode); + + // This is code is repeated because the bug GETTYS-268, the content + // variables were been overwritten + // by the parse inside the some of the content fields + // To edit the look, see + // WEB-INF/velocity/static/preview/content_controls.vtl + + if (PageMode.EDIT_MODE == mode) { + sb.append("#set( $EDIT_CONTENT_PERMISSION=$EDIT_CONTENT_PERMISSION") + .append(identifier.getId()) + .append(" )"); + } + + sb.append("#set( $CONTENT_INODE=\"") + .append(content.getInode()) + .append("\" )"); + sb.append("#set( $IDENTIFIER_INODE=\"") + .append(identifier.getId()) + .append("\" )"); + + sb.append("#set( $ContentInode=\"") + .append(content.getInode()) + .append("\" )"); + sb.append("#set( $ContentIdentifier=\"") + .append(identifier.getId()) + .append("\" )"); + sb.append("#set( $ContentletTitle=\"") + .append(UtilMethods.espaceForVelocity(conAPI.getName(content, APILocator.getUserAPI() + .getSystemUser(), true))) + .append("\" )"); + sb.append("#set( $ContentletStructure=\"") + .append(content.getContentTypeId()) + .append("\" )"); + sb.append("#set( $ContentletContentType=\"") + .append(content.getContentTypeId()) + .append("\" )"); + if (type.baseType() == BaseContentType.WIDGET) { + sb.append("#set( $isWidget= \"") + .append(true) + .append("\")"); + if (type.name() + .equals(FormAPI.FORM_WIDGET_STRUCTURE_NAME_FIELD_NAME)) { + sb.append("#set($isFormWidget= \"") + .append(true) + .append("\")"); + } else { + sb.append("#set($isFormWidget= \"") + .append(false) + .append("\")"); + } + } else { + sb.append("#set($isWidget= \"") + .append(false) + .append("\")"); + } + + // close contentlet div + sb.append("#if($API_EDIT_MODE)") + .append("") + .append("#end"); + + return writeOutVelocity(filePath, sb.toString()); + } + + @SuppressWarnings("unchecked") + public List sortContentlets(List contentletList, String sortBy) { + + Logger.debug(this.getClass(), "I'm ordering by " + sortBy); + + if (sortBy.equals("tree_order")) { + Collections.sort(contentletList, new WebAssetSortOrderComparator()); + } else { + Collections.sort(contentletList, new ContentComparator("asc")); + } + + return contentletList; + + } + + /** + * Will remove all contentlet files within a structure for both live and working. Uses the + * system user. + * + * @param contentlets + * @throws DotSecurityException + * @throws DotDataException + */ + public void invalidate(Structure structure) throws DotDataException, DotSecurityException { + ContentletAPI conAPI = APILocator.getContentletAPI(); + int limit = 500; + int offset = 0; + List contentlets = conAPI.findByStructure(structure, APILocator.getUserAPI() + .getSystemUser(), false, limit, offset); + int size = contentlets.size(); + while (size > 0) { + for (Contentlet contentlet : contentlets) { + invalidate(contentlet); + } + offset += limit; + contentlets = conAPI.findByStructure(structure, APILocator.getUserAPI() + .getSystemUser(), false, limit, offset); + size = contentlets.size(); + } + } + + + + @Override + public InputStream writeObject(String id1, String id2, PageMode mode, String language, String filePath) { + try { + + Identifier identifier = APILocator.getIdentifierAPI() + .find(id1); + Contentlet contentlet = null; + if (CacheLocator.getVeloctyResourceCache() + .isMiss(filePath)) { + if (LanguageWebAPI.canDefaultContentToDefaultLanguage()) { + LanguageAPI langAPI = APILocator.getLanguageAPI(); + language = Long.toString(langAPI.getDefaultLanguage() + .getId()); + } else { + throw new ResourceNotFoundException("Contentlet is a miss in the cache"); + } + } + + try { + contentlet = APILocator.getContentletAPI() + .findContentletByIdentifier(identifier.getId(), mode.showLive, new Long(language), APILocator.getUserAPI() + .getSystemUser(), true); + } catch (DotContentletStateException e) { + contentlet = null; + } + + if (contentlet == null || !InodeUtils.isSet(contentlet.getInode()) || contentlet.isArchived()) { + + LanguageAPI langAPI = APILocator.getLanguageAPI(); + long lid = langAPI.getDefaultLanguage() + .getId(); + if (lid != Long.parseLong(language)) { + Contentlet cc = APILocator.getContentletAPI() + .findContentletByIdentifier(identifier.getId(), mode.showLive, lid, APILocator.getUserAPI() + .getSystemUser(), true); + if (cc != null && UtilMethods.isSet(cc.getInode()) && !cc.isArchived() + && LanguageWebAPI.canApplyToAllLanguages(cc)) { + contentlet = cc; + } else { + CacheLocator.getVeloctyResourceCache() + .addMiss(filePath); + throw new ResourceNotFoundException("Contentlet Velocity file not found:" + filePath); + } + } + } + + Logger.debug(this, "DotResourceLoader:\tWriting out contentlet inode = " + contentlet.getInode()); + return buildVelocity(contentlet, identifier, mode, filePath); + + } catch (Exception e) { + throw new ResourceNotFoundException("Contentlet Velocity file not found:" + filePath); + } + } + + + + + @Override + public void invalidate(Object obj, PageMode mode) { + Contentlet asset = (Contentlet) obj; + CacheLocator.getContentletCache() + .remove(asset.getInode()); + + String folderPath = mode.name() + java.io.File.separator; + String velocityRootPath = VelocityUtil.getVelocityRootPath(); + velocityRootPath += java.io.File.separator; + + Set langs = new HashSet(); + langs.add(asset.getLanguageId()); + if (LanguageWebAPI.canApplyToAllLanguages(asset)) { + for (Language ll : APILocator.getLanguageAPI() + .getLanguages()) { + langs.add(ll.getId()); + } + } + for (Long langId : langs) { + String filePath = folderPath + asset.getIdentifier() + "_" + langId + "." + VelocityType.CONTENT.fileExtension; + java.io.File f = new java.io.File(velocityRootPath + filePath); + f.delete(); + DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); + vc.remove(ResourceManager.RESOURCE_TEMPLATE + filePath); + } + List fields; + try { + fields = asset.getContentType() + .fields(); + for (Field field : fields) { + new FieldLoader().invalidate(field, asset, mode); + } + } catch (DotDataException | DotSecurityException e) { + throw new DotStateException(e); + } + + + try { + if (asset.getContentType() + .baseType() == BaseContentType.HTMLPAGE) { + new PageLoader().invalidate(asset, mode); + } + + if (asset != null && asset.isVanityUrl()) { + // remove from cache + VanityUrlServices.getInstance() + .invalidateVanityUrl(asset); + } + if (asset != null && asset.isKeyValue()) { + // remove from cache + CacheLocator.getKeyValueCache() + .remove(asset); + } + } catch (DotDataException | DotSecurityException e) { + throw new DotStateException(e); + } + } + +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/DotLoader.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/DotLoader.java new file mode 100644 index 000000000000..741ca6140ce3 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/DotLoader.java @@ -0,0 +1,80 @@ +package com.dotcms.rendering.velocity.services; + +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.DotStateException; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotRuntimeException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.util.Config; +import com.dotmarketing.util.ConfigUtils; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; + +import java.io.BufferedWriter; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; + +import com.liferay.portal.model.User; +/** + * The DotLoaders exist to distill CMS objects down to Velocity templates - + * which can then be cached in Velocity and parsed very quickly. + * This is done because the performance of rendering velocity templates is + * ~10x greater vs. pulling the objects out of a cache and using them RAW + * within Velocity + * @author will + * + */ +public interface DotLoader { + default User sysUser() { + try { + return APILocator.getUserAPI() + .getSystemUser(); + } catch (DotDataException e) { + throw new DotRuntimeException(e); + } + } + + public InputStream writeObject(String id1, String id2, PageMode mode, String language, String filePath) + throws DotDataException, DotSecurityException; + + default void invalidate(Object obj) { + for(PageMode mode : PageMode.values()) { + invalidate(obj, mode); + } + } + + public void invalidate(Object obj, PageMode mode); + + + default void invalidate(Object obj, PageMode ...modes) { + for(PageMode mode : modes) { + invalidate(obj, mode); + } + } + + default InputStream writeOutVelocity(final String filePath, final String strOut) { + if (Config.getBooleanProperty("SHOW_VELOCITYFILES", false)) { + try { + File f = new File(ConfigUtils.getDynamicVelocityPath() + java.io.File.separator + filePath); + f.mkdirs(); + f.delete(); + try (final BufferedWriter out = new java.io.BufferedWriter(new VelocityPrettyWriter(new FileOutputStream(f)))) { + out.write(strOut); + } + } catch (Exception e) { + new DotStateException(e); + } + } + try { + return new ByteArrayInputStream(strOut.getBytes("UTF-8")); + } catch (UnsupportedEncodingException e1) { + Logger.error(this.getClass(), e1.getMessage(), e1); + return new ByteArrayInputStream(strOut.getBytes()); + + } + } + +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/DotResourceCache.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/DotResourceCache.java new file mode 100644 index 000000000000..2f4a29d3e332 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/DotResourceCache.java @@ -0,0 +1,220 @@ +/** + * + */ +package com.dotcms.rendering.velocity.services; + +import java.io.File; +import java.util.HashSet; + +import java.util.Set; + +import org.apache.velocity.runtime.RuntimeConstants; +import org.apache.velocity.runtime.RuntimeServices; +import org.apache.velocity.runtime.resource.Resource; +import org.apache.velocity.runtime.resource.ResourceCache; +import org.apache.velocity.runtime.resource.ResourceManager; + +import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.rendering.velocity.util.VelocityUtil; +import com.dotcms.repackage.com.google.common.collect.ImmutableSet; +import com.dotmarketing.business.Cachable; +import com.dotmarketing.business.CacheLocator; +import com.dotmarketing.business.DotCacheAdministrator; +import com.dotmarketing.business.DotCacheException; +import com.dotmarketing.util.Logger; + +import com.liferay.util.StringUtil; + +/** + * @author Jason Tesser + * @author Andres Olarte + * @since 1.6.5 The DotResourceCache was created to allow velocities cache to be distributed across + * nodes in a cluster. It also allows the dotCMS to set velocity to always cache and pull + * from cache Our services methods which generate the velocity files will handle the filling + * and removing of The cache. If something is not in cache though the DotResourceLoader will + * be called. + */ +public class DotResourceCache implements ResourceCache, Cachable { + + + private DotCacheAdministrator cache; + + private String primaryGroup = "VelocityCache"; + private String macroCacheGroup = "VelocityMacroCache"; + // region's name for the cache + private String[] groupNames = {primaryGroup, macroCacheGroup}; + private static final String MACRO_PREFIX = "MACRO_PREFIX"; + private final Set ignoreGlobalVM; + + + + public DotResourceCache() { + cache = CacheLocator.getCacheAdministrator(); + String files = System.getProperty(RuntimeConstants.VM_LIBRARY); + Set holder = new HashSet<>(); + for (String file : files.split(",")) { + if (file != null) { + // System.out.println("FILE: " +file); + holder.add(file.trim()); + } + } + ignoreGlobalVM = ImmutableSet.copyOf(holder); + } + + public String[] getMacro(String name) { + + + String[] rw = null; + try { + rw = (String[]) cache.get(MACRO_PREFIX + name, macroCacheGroup); + } catch (DotCacheException e) { + Logger.debug(this, "Cache Entry not found", e); + } + return rw; + + } + + public void putMacro(String name, String content) { + if (name == null || content == null) { + Logger.warn(this.getClass(), "Cannot add a null macro to cache:" + name + " / " + content); + return; + } + String[] rw = {name, content}; + cache.put(MACRO_PREFIX + name, rw, macroCacheGroup); + } + + /* + * (non-Javadoc) + * + * @see org.apache.velocity.runtime.resource.ResourceCache#get(java.lang.Object) + */ + public Resource get(Object resourceKey) { + + String cleanedResourceKey = cleanKey(resourceKey.toString()); + String group = primaryGroup; + + Resource resource = null; + String key = group + cleanedResourceKey; + try { + resource = (Resource) cache.get(key, group); + } catch (DotCacheException e) { + Logger.debug(this, "Cache Entry not found", e); + } + return resource != null ? resource : null; + } + + /* + * (non-Javadoc) + * + * @see + * org.apache.velocity.runtime.resource.ResourceCache#initialize(org.apache.velocity.runtime. + * RuntimeServices) + */ + public void initialize(RuntimeServices rs) { + cache = CacheLocator.getCacheAdministrator(); + } + + public void addMiss(Object resourceKey) { + Logger.info(this.getClass(), "velocityMiss:" + resourceKey); + } + + public boolean isMiss(Object resourceKey) { + return false; + } + + /* + * (non-Javadoc) + * + * @see org.apache.velocity.runtime.resource.ResourceCache#put(java.lang.Object, + * org.apache.velocity.runtime.resource.Resource) + */ + public Resource put(Object resourceKey, Resource resource) { + if (resource != null && ignoreGlobalVM.contains(resource.getName())) { + return resource; + } + + String cleanedResourceKey = cleanKey(resourceKey.toString()); + String group = primaryGroup; + + + + String key = group + cleanedResourceKey; + // Add the key to the cache + cache.put(key, resource, group); + + return resource; + + } + + /* + * (non-Javadoc) + * + * @see org.apache.velocity.runtime.resource.ResourceCache#remove(java.lang.Object) + */ + public Resource remove(Object resourceKey) { + + String cleanedResourceKey = cleanKey(resourceKey.toString()); + String group = primaryGroup; + + + String key = group + cleanedResourceKey; + + try { + cache.remove(key, group); + } catch (Exception e) { + Logger.debug(this, e.getMessage(), e); + } + return null; + } + + public void clearCache() { + for (String group : groupNames) { + cache.flushGroup(group); + } + + } + + @Deprecated + public void clearMenuCache() { + + } + + public String[] getGroups() { + return groupNames; + } + + public String getPrimaryGroup() { + return primaryGroup; + } + + private String cleanKey(String key) { + if (key.startsWith(ResourceManager.RESOURCE_TEMPLATE + "")) + key = key.substring((ResourceManager.RESOURCE_TEMPLATE + "").length()); + + if (key.startsWith(File.separatorChar + "")) { + key = key.substring(1); + } + if (key.startsWith("/")) { + key = key.substring(1); + } + key = StringUtil.replace(key, '\\', '/'); + return key; + } + + @Deprecated + public String getMenuGroup() { + return primaryGroup; + } + + public void removeContentTypeFile(ContentType contentType) { + String folderPath = "working/"; + String filePath = folderPath + contentType.inode() + "." + VelocityType.CONTENT_TYPE.fileExtension; + + String velocityRootPath = VelocityUtil.getVelocityRootPath(); + String absolutPath = velocityRootPath + File.separator + filePath; + java.io.File f = new java.io.File(absolutPath); + f.delete(); + remove(ResourceManager.RESOURCE_TEMPLATE + filePath); + } + +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/DotResourceLoader.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/DotResourceLoader.java new file mode 100644 index 000000000000..ac44999476f8 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/DotResourceLoader.java @@ -0,0 +1,158 @@ +package com.dotcms.rendering.velocity.services; + + +import com.dotcms.repackage.org.apache.commons.collections.ExtendedProperties; + +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.CacheLocator; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; +import com.dotmarketing.util.UtilMethods; + +import java.io.InputStream; + +import org.apache.velocity.exception.ResourceNotFoundException; +import org.apache.velocity.runtime.resource.Resource; +import org.apache.velocity.runtime.resource.loader.ResourceLoader; + +public class DotResourceLoader extends ResourceLoader { + + + private static DotResourceLoader instance; + + + public DotResourceLoader() { + super(); + } + + + @Override + public InputStream getResourceStream(final String filePath) throws ResourceNotFoundException { + if (!UtilMethods.isSet(filePath)) { + throw new ResourceNotFoundException("cannot find resource"); + } + + + final VelocityType type = VelocityType.resolveVelocityType(filePath); + synchronized (filePath.intern()) { + + + + String paths = (filePath.charAt(0) == '/') ? filePath.substring(1, filePath.length()) : filePath; + + final String[] path = paths.split("[/\\.]", -1); + final PageMode mode = PageMode.get(path[0]); + final String id1 = path[1].indexOf("_") > -1 ? path[1].substring(0, path[1].indexOf("_")) : path[1]; + final String language = path[1].indexOf("_") > -1 ? path[1].substring(path[1].indexOf("_") + 1, path[1].length()) + : String.valueOf(APILocator.getLanguageAPI() + .getDefaultLanguage() + .getId()); + + final String id2 = path.length > 3 ? path[2] : null; + + + Logger.debug(this, "DotResourceLoader:\tInode: " + id1); + + try { + switch (type) { + case NOT_VELOCITY: { + CacheLocator.getVeloctyResourceCache() + .addMiss(path); + throw new ResourceNotFoundException("Cannot find velocity file : " + path); + } + case CONTAINER: { + return new ContainerLoader().writeObject(id1, id2, mode, language, filePath); + } + case TEMPLATE: { + + return new TemplateLoader().writeObject(id1, id2, mode, language, filePath); + + } + case CONTENT: { + return new ContentletLoader().writeObject(id1, id2, mode, language, filePath); + } + case FIELD: { + return new FieldLoader().writeObject(id1, id2, mode, language, filePath); + } + case CONTENT_TYPE: { + return new ContentTypeLoader().writeObject(id1, id2, mode, language, filePath); + } + case SITE: { + return new SiteLoader().writeObject(id1, id2, mode, language, filePath); + + } + case HTMLPAGE: { + return new PageLoader().writeObject(id1, id2, mode, language, filePath); + + } + case VELOCITY_MACROS: { + return VTLLoader.instance() + .writeObject(id1, id2, mode, language, filePath); + } + case VTL: { + return VTLLoader.instance() + .writeObject(id1, id2, mode, language, filePath); + } + case VELOCITY_LEGACY_VL: { + return VTLLoader.instance() + .writeObject(id1, id2, mode, language, filePath); + } + default: { + CacheLocator.getVeloctyResourceCache() + .addMiss(path); + throw new ResourceNotFoundException("Cannot find velocity file : " + path); + } + } + + } catch (Exception e) { + throw new ResourceNotFoundException("Cannot parse velocity file : " + path, e); + } + } + + } + + /* + * (non-Javadoc) + * + * @see + * org.apache.velocity.runtime.resource.loader.FileResourceLoader#getLastModified(org.apache. + * velocity.runtime.resource.Resource) + */ + @Override + public long getLastModified(Resource resource) { + return 0; + } + + /* + * (non-Javadoc) + * + * @see + * org.apache.velocity.runtime.resource.loader.FileResourceLoader#isSourceModified(org.apache. + * velocity.runtime.resource.Resource) + */ + @Override + public boolean isSourceModified(Resource resource) { + return false; + } + + public static DotResourceLoader getInstance() { + if (instance == null) { + synchronized (DotResourceLoader.class) { + if (instance == null) { + instance = new DotResourceLoader(); + } + } + } + return instance; + } + + + @Override + public void init(ExtendedProperties configuration) { + // TODO Auto-generated method stub + + } + + + +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/FieldLoader.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/FieldLoader.java new file mode 100644 index 000000000000..6009b51d442c --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/FieldLoader.java @@ -0,0 +1,99 @@ +package com.dotcms.rendering.velocity.services; + + +import com.dotcms.contenttype.model.field.ConstantField; +import com.dotcms.contenttype.model.field.Field; +import com.dotcms.contenttype.model.field.HiddenField; +import com.dotcms.rendering.velocity.util.VelocityUtil; + +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.CacheLocator; +import com.dotmarketing.business.DotStateException; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.portlets.contentlet.business.ContentletAPI; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; +import com.dotmarketing.util.UtilMethods; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +import org.apache.velocity.runtime.resource.ResourceManager; + +/** + * @author Jason Tesser + * @since 1.6.5 + * + */ +public class FieldLoader implements DotLoader { + public void invalidate(String fieldInode, String contentletIdent, PageMode mode,String filePath) throws DotDataException, DotSecurityException { + removeFieldFile(fieldInode, contentletIdent, mode); + } + + public InputStream buildVelocity(String fieldInode, String contentInode, PageMode mode,String filePath) throws DotDataException, DotSecurityException { + InputStream result; + Field field = APILocator.getContentTypeFieldAPI().find(fieldInode); + if(!UtilMethods.isSet(field)){ + Logger.warn(this.getClass(),"Field not found. Unable to load velocity code"); + return new ByteArrayInputStream("".toString().getBytes()); + } + ContentletAPI conAPI = APILocator.getContentletAPI(); + Contentlet content = conAPI.find(contentInode, APILocator.getUserAPI().getSystemUser(), true); + if(!UtilMethods.isSet(content)){ + Logger.warn(this.getClass(),"Content not found. Unable to load velocity code"); + return new ByteArrayInputStream("".toString().getBytes()); + } + Object contFieldValueObject = conAPI.getFieldValue(content, field); + String contFieldValue = ""; + + + + if(field instanceof ConstantField || field instanceof HiddenField){ + contFieldValue = field.values() == null ? "" : field.values(); + }else{ + contFieldValue = contFieldValueObject == null ? "" : contFieldValueObject.toString(); + } + + if(contFieldValue != null && contFieldValue.endsWith("#")){ + contFieldValue = contFieldValue.substring(0, contFieldValue.length()-1); + contFieldValue += "$esc.h"; + } + + + return writeOutVelocity(filePath, contFieldValue); + + + } + + public void removeFieldFile (String fieldInode, String contentInode, PageMode mode) { + + } + + @Override + public InputStream writeObject(String id1, String id2, PageMode mode, String language, String filePath) + throws DotDataException, DotSecurityException { + + return this.buildVelocity(id2, id1, mode, filePath); + + } + + + public void invalidate(Field field, Contentlet content, PageMode mode) { + String velocityRootPath = VelocityUtil.getVelocityRootPath(); + velocityRootPath += java.io.File.separator; + String folderPath = mode.name() + java.io.File.separator; + String filePath=folderPath + content.getInode() + "_" + field.id() + "." + VelocityType.FIELD.fileExtension; + java.io.File f = new java.io.File(velocityRootPath + filePath); + f.delete(); + DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); + vc.remove(ResourceManager.RESOURCE_TEMPLATE + filePath ); + } + + @Override + public void invalidate(Object obj, PageMode mode) { + throw new DotStateException("Not Implemented, use invalidate(String fieldInode, String contentInode, PageMode mode) "); + + } +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/PageContextBuilder.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/PageContextBuilder.java new file mode 100644 index 000000000000..bc20e995356b --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/PageContextBuilder.java @@ -0,0 +1,294 @@ +package com.dotcms.rendering.velocity.services; + +import static com.dotmarketing.business.PermissionAPI.PERMISSION_CAN_ADD_CHILDREN; +import static com.dotmarketing.business.PermissionAPI.PERMISSION_PUBLISH; +import static com.dotmarketing.business.PermissionAPI.PERMISSION_READ; +import static com.dotmarketing.business.PermissionAPI.PERMISSION_WRITE; + +import com.dotcms.contenttype.model.type.BaseContentType; +import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.enterprise.LicenseUtil; +import com.dotcms.enterprise.license.LicenseLevel; +import com.dotcms.publisher.endpoint.bean.PublishingEndPoint; +import com.dotcms.repackage.com.ibm.icu.text.SimpleDateFormat; + +import com.dotmarketing.beans.ContainerStructure; +import com.dotmarketing.beans.Identifier; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.CacheLocator; +import com.dotmarketing.business.PermissionAPI; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.factories.MultiTreeAPI; +import com.dotmarketing.portlets.containers.model.Container; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.htmlpageasset.model.IHTMLPage; +import com.dotmarketing.portlets.structure.model.Structure; +import com.dotmarketing.portlets.templates.model.Template; +import com.dotmarketing.tag.model.Tag; +import com.dotmarketing.util.Config; +import com.dotmarketing.util.PageMode; +import com.dotmarketing.util.UtilMethods; + +import java.io.StringWriter; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.velocity.context.Context; + +import com.google.common.collect.Table; +import com.liferay.portal.model.User; + +public class PageContextBuilder { + private static PermissionAPI permissionAPI = APILocator.getPermissionAPI(); + + final IHTMLPage htmlPage; + final User user; + final Map ctxMap; + final PageMode mode; + final Date timeMachine; + List pageFoundTags; + + final static String WIDGET_PRE_EXECUTE = "WIDGET_PRE_EXECUTE"; + public PageContextBuilder(IHTMLPage htmlPage, User user, PageMode mode, Date timeMachine) + throws DotSecurityException, DotDataException { + super(); + this.htmlPage = htmlPage; + this.user = user; + this.ctxMap = new HashMap<>(); + this.mode = mode; + this.timeMachine = timeMachine; + populateContext(); + populateContainers(); + } + + + + public PageContextBuilder(IHTMLPage htmlPage, User user, PageMode mode) throws DotSecurityException, DotDataException { + this(htmlPage, user, mode, null); + } + + private void populateContext() throws DotDataException, DotSecurityException { + + + ctxMap.put(mode.name(), Boolean.TRUE); + + + + + + + // set the page cache var + if (htmlPage.getCacheTTL() > 0 && LicenseUtil.getLevel() >= LicenseLevel.COMMUNITY.level) { + ctxMap.put("dotPageCacheDate", new java.util.Date()); + ctxMap.put("dotPageCacheTTL", htmlPage.getCacheTTL()); + } + + String templateId = htmlPage.getTemplateId(); + Template template = (mode.showLive) ? (Template) APILocator.getVersionableAPI() + .findLiveVersion(templateId, user, false) + : (Template) APILocator.getVersionableAPI() + .findWorkingVersion(templateId, user, false); + + Identifier pageIdent = APILocator.getIdentifierAPI() + .find(htmlPage.getIdentifier()); + + // gets pageChannel for this path + java.util.StringTokenizer st = new java.util.StringTokenizer(String.valueOf(pageIdent.getURI()), "/"); + String pageChannel = null; + if (st.hasMoreTokens()) { + pageChannel = st.nextToken(); + } + + // to check user has permission to write on this page + List receivingEndpoints = APILocator.getPublisherEndPointAPI() + .getReceivingEndPoints(); + boolean hasAddChildrenPermOverHTMLPage = + permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_CAN_ADD_CHILDREN, user); + boolean hasWritePermOverHTMLPage = permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_WRITE, user); + boolean hasPublishPermOverHTMLPage = permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_PUBLISH, user); + boolean hasRemotePublishPermOverHTMLPage = + hasPublishPermOverHTMLPage && LicenseUtil.getLevel() >= LicenseLevel.STANDARD.level; + boolean hasEndPoints = UtilMethods.isSet(receivingEndpoints) && !receivingEndpoints.isEmpty(); + boolean canUserWriteOnTemplate = + permissionAPI.doesUserHavePermission(template, PERMISSION_WRITE, user) && APILocator.getPortletAPI() + .hasTemplateManagerRights(user); + + ctxMap.put("dotPageMode", mode.name()); + + ctxMap.put("ADD_CHILDREN_HTMLPAGE_PERMISSION", hasAddChildrenPermOverHTMLPage); + ctxMap.put("EDIT_HTMLPAGE_PERMISSION", hasWritePermOverHTMLPage); + ctxMap.put("PUBLISH_HTMLPAGE_PERMISSION", hasPublishPermOverHTMLPage); + ctxMap.put("REMOTE_PUBLISH_HTMLPAGE_PERMISSION", hasRemotePublishPermOverHTMLPage); + ctxMap.put("REMOTE_PUBLISH_END_POINTS", hasEndPoints); + ctxMap.put("canAddForm", LicenseUtil.getLevel() >= LicenseLevel.STANDARD.level ? true : false); + ctxMap.put("canViewDiff", LicenseUtil.getLevel() >= LicenseLevel.STANDARD.level ? true : false); + ctxMap.put("pageChannel", pageChannel); + ctxMap.put("HTMLPAGE_ASSET_STRUCTURE_TYPE", true); + ctxMap.put("HTMLPAGE_IS_CONTENT", true); + + + ctxMap.put("EDIT_TEMPLATE_PERMISSION", canUserWriteOnTemplate); + + + ctxMap.put(ContainerLoader.SHOW_PRE_POST_LOOP, true); + ctxMap.put("HTMLPAGE_INODE", htmlPage.getInode()); + ctxMap.put("HTMLPAGE_IDENTIFIER", htmlPage.getIdentifier()); + ctxMap.put("HTMLPAGE_FRIENDLY_NAME", UtilMethods.espaceForVelocity(htmlPage.getFriendlyName())); + ctxMap.put("HTMLPAGE_TITLE", UtilMethods.espaceForVelocity(htmlPage.getTitle())); + ctxMap.put("TEMPLATE_INODE", template.getIdentifier()); + ctxMap.put("HTMLPAGE_META", UtilMethods.espaceForVelocity(htmlPage.getMetadata())); + ctxMap.put("HTMLPAGE_DESCRIPTION", UtilMethods.espaceForVelocity(htmlPage.getSeoDescription())); + ctxMap.put("HTMLPAGE_KEYWORDS", UtilMethods.espaceForVelocity(htmlPage.getSeoKeywords())); + ctxMap.put("HTMLPAGE_SECURE", htmlPage.isHttpsRequired()); + ctxMap.put("VTLSERVLET_URI", UtilMethods.encodeURIComponent(pageIdent.getURI())); + ctxMap.put("HTMLPAGE_REDIRECT", UtilMethods.espaceForVelocity(htmlPage.getRedirect())); + ctxMap.put("pageTitle", UtilMethods.espaceForVelocity(htmlPage.getTitle())); + ctxMap.put("friendlyName", UtilMethods.espaceForVelocity(htmlPage.getFriendlyName())); + ctxMap.put("HTML_PAGE_LAST_MOD_DATE", UtilMethods.espaceForVelocity(htmlPage.getFriendlyName())); + ctxMap.put("HTMLPAGE_MOD_DATE", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(htmlPage.getModDate())); + + + + } + + + + private void populateContainers() throws DotDataException, DotSecurityException { + Table> pageContents = new MultiTreeAPI().getPageMultiTrees(htmlPage, mode.showLive); + + + + if (!pageContents.isEmpty()) { + for (final String containerId : pageContents.rowKeySet()) { + for (final String uniqueId : pageContents.row(containerId) + .keySet()) { + Set cons = pageContents.get(containerId, uniqueId); + + Container c = (mode.showLive) ? (Container) APILocator.getVersionableAPI() + .findLiveVersion(containerId, user, false) + : (Container) APILocator.getVersionableAPI() + .findWorkingVersion(containerId, user, false); + + boolean hasWritePermissionOnContainer = + permissionAPI.doesUserHavePermission(c, PERMISSION_WRITE, user, false) && APILocator.getPortletAPI() + .hasContainerManagerRights(user); + boolean hasReadPermissionOnContainer = permissionAPI.doesUserHavePermission(c, PERMISSION_READ, user, false); + ctxMap.put("EDIT_CONTAINER_PERMISSION" + c.getIdentifier(), hasWritePermissionOnContainer); + if (Config.getBooleanProperty("SIMPLE_PAGE_CONTENT_PERMISSIONING", true)) + ctxMap.put("USE_CONTAINER_PERMISSION" + c.getIdentifier(), true); + else + ctxMap.put("USE_CONTAINER_PERMISSION" + c.getIdentifier(), hasReadPermissionOnContainer); + + // to check user has permission to write this container + boolean hasWritePermOverTheStructure = false; + + for (ContainerStructure cs : APILocator.getContainerAPI() + .getContainerStructures(c)) { + Structure st = CacheLocator.getContentTypeCache() + .getStructureByInode(cs.getStructureId()); + + hasWritePermOverTheStructure |= permissionAPI.doesUserHavePermission(st, PERMISSION_WRITE, user); + } + + ctxMap.put("ADD_CONTENT_PERMISSION" + c.getIdentifier(), new Boolean(hasWritePermOverTheStructure)); + + List contentlets = APILocator.getContentletAPI() + .findContentletsByIdentifiers(cons.stream() + .toArray(String[]::new), mode.showLive, -1, user, false); + + // get contentlets only for main frame + + if (contentlets != null) { + for (Contentlet contentlet : contentlets) { + ctxMap.put("EDIT_CONTENT_PERMISSION" + contentlet.getIdentifier(), + permissionAPI.doesUserHavePermission(contentlet, PERMISSION_WRITE, user)); + ContentType type = contentlet.getContentType(); + if (type.baseType() == BaseContentType.WIDGET) { + com.dotcms.contenttype.model.field.Field field = type.fieldMap() + .get("widgetPreexecute"); + if (field != null && UtilMethods.isSet(field.values())) { + + String x = ctxMap.containsKey(WIDGET_PRE_EXECUTE) ? "" + : (String) ctxMap.get(WIDGET_PRE_EXECUTE); + ctxMap.put(WIDGET_PRE_EXECUTE, x + field.values() + "\n"); + } + } + + // Check if we want to accrue the tags associated to each contentlet on + // this page + if (Config.getBooleanProperty("ACCRUE_TAGS_IN_CONTENTS_ON_PAGE", false)) { + + + // Search for the tags associated to this contentlet inode + List contentletFoundTags = APILocator.getTagAPI() + .getTagsByInode(contentlet.getInode()); + if (contentletFoundTags != null) { + this.pageFoundTags.addAll(contentletFoundTags); + } + + } + + } + } + // sets contentletlist with all the files to load per + // container + ctxMap.put("contentletList" + c.getIdentifier() + uniqueId, contentlets.stream() + .map(con -> con.getIdentifier()) + .toArray(size -> new String[size])); + ctxMap.put("totalSize" + c.getIdentifier() + uniqueId, new Integer(contentlets.size())); + + } + } + } + } + + + + public List getPageFoundTags() { + return pageFoundTags; + } + + public String getWidgetPreExecute() { + return (String) ctxMap.getOrDefault(WIDGET_PRE_EXECUTE, null); + } + + + + + public Context addAll(Context incoming) { + + for (String key : this.ctxMap.keySet()) { + incoming.put(key, ctxMap.get(key)); + } + + + + return incoming; + } + + + + public String asString() { + + + final StringWriter s = new StringWriter(); + for (String key : this.ctxMap.keySet()) { + s.append("#set($") + .append(key) + .append("=") + .append(new StringifyObject(ctxMap.get(key)).from()) + .append(')'); + } + + + return s.toString(); + + } + + + +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/PageLoader.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/PageLoader.java new file mode 100644 index 000000000000..042aaae0437a --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/PageLoader.java @@ -0,0 +1,219 @@ +package com.dotcms.rendering.velocity.services; + +import com.dotcms.rendering.velocity.util.VelocityUtil; +import com.dotcms.repackage.bsh.This; + +import com.dotmarketing.beans.Host; +import com.dotmarketing.beans.Identifier; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.CacheLocator; +import com.dotmarketing.business.DotStateException; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotRuntimeException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.portlets.contentlet.business.ContentletAPI; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.htmlpageasset.model.HTMLPageAsset; +import com.dotmarketing.portlets.htmlpageasset.model.IHTMLPage; +import com.dotmarketing.portlets.templates.model.Template; +import com.dotmarketing.tag.model.Tag; +import com.dotmarketing.util.Config; +import com.dotmarketing.util.InodeUtils; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; +import com.dotmarketing.util.TagUtil; + +import java.io.File; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import org.apache.velocity.runtime.resource.ResourceManager; + +import com.liferay.portal.model.User; + +/** + * @author will + * + * To change this generated comment edit the template variable "typecomment": + * Window>Preferences>Java>Templates. To enable and disable the creation of type comments go + * to Window>Preferences>Java>Code Generation. + */ +public class PageLoader implements DotLoader { + + + + @Override + public void invalidate(Object obj) { + IHTMLPage htmlPage = (IHTMLPage) obj; + for (PageMode mode : PageMode.values()) { + invalidate(htmlPage, mode); + } + + + } + + @Override + public void invalidate(Object obj, PageMode mode) { + HTMLPageAsset htmlPage =null; + if(obj instanceof IHTMLPage) { + htmlPage = (HTMLPageAsset) obj; + }else if(obj instanceof Contentlet) { + htmlPage = APILocator.getHTMLPageAssetAPI().fromContentlet((Contentlet) obj); + } + if(htmlPage==null) { + return; + } + + + + String folderPath = mode.name() + File.separator; + String velocityRootPath = VelocityUtil.getVelocityRootPath(); + String languageStr = htmlPage.getLanguageId() +""; + String filePath = folderPath + htmlPage.getIdentifier() + languageStr + "." + VelocityType.HTMLPAGE.fileExtension; + velocityRootPath += java.io.File.separator; + java.io.File f = new java.io.File(velocityRootPath + filePath); + f.delete(); + DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); + vc.remove(ResourceManager.RESOURCE_TEMPLATE + filePath); + + } + + + + public InputStream buildStream(IHTMLPage htmlPage, PageMode mode, final String filePath) + throws DotStateException, DotDataException { + Identifier identifier = APILocator.getIdentifierAPI() + .find(htmlPage); + try { + return buildStream(htmlPage, identifier, mode, filePath); + } catch (Exception e) { + Logger.error(this.getClass(), e.getMessage(), e); + throw new DotRuntimeException(e.getMessage()); + } + } + + + public InputStream buildStream(IHTMLPage htmlPage, Identifier identifier, PageMode mode, final String filePath) + throws DotDataException, DotSecurityException { + String folderPath = mode.name() + File.separator; + InputStream result; + StringBuilder sb = new StringBuilder(); + + ContentletAPI conAPI = APILocator.getContentletAPI(); + Template cmsTemplate = APILocator.getHTMLPageAssetAPI() + .getTemplate(htmlPage, mode.showLive); + + + User sys = APILocator.systemUser(); + + + if (cmsTemplate == null || !InodeUtils.isSet(cmsTemplate.getInode())) { + Logger.error(This.class, "PAGE DOES NOT HAVE A VALID TEMPLATE (template unpublished?) : page id " + + htmlPage.getIdentifier() + ":" + identifier.getURI()); + } + + + + // List of tags found in this page + List pageFoundTags = new ArrayList<>(); + + // Check if we want to accrue the tags of this HTMLPage contentlet + if (Config.getBooleanProperty("ACCRUE_TAGS_IN_PAGES", true)) { + + List htmlPageFoundTags = APILocator.getTagAPI() + .getTagsByInode(htmlPage.getInode()); + if (htmlPageFoundTags != null && !htmlPageFoundTags.isEmpty()) { + pageFoundTags.addAll(htmlPageFoundTags); + } + } + + + + sb.append("#set($dotPageContent = $dotcontent.find(\"" + htmlPage.getInode() + "\" ))"); + + + // set the host variables + + Host host = APILocator.getHTMLPageAssetAPI() + .getParentHost(htmlPage); + sb.append("#if(!$doNotParseTemplate)") + .append("#parse('") + .append(folderPath) + .append(host.getIdentifier()) + .append(".") + .append(VelocityType.SITE.fileExtension) + .append("')") + .append("#end"); + + + sb.append(new PageContextBuilder(htmlPage, sys, mode).asString()); + + + // Now we need to use the found tags in order to accrue them each time this page is visited + if (!pageFoundTags.isEmpty()) { + // Velocity call to accrue tags on each request to this page + sb.append("$tags.accrueTags(\"" + TagUtil.tagListToString(pageFoundTags) + "\" )"); + } + if (htmlPage.isHttpsRequired()) { + sb.append(" #if(!$ADMIN_MODE && !$request.isSecure())"); + sb.append("#if($request.getQueryString())"); + sb.append("#set ($REDIRECT_URL = \"https://${request.getServerName()}$request.getAttribute('javax.servlet.forward.request_uri')?$request.getQueryString()\")"); + sb.append("#else"); + sb.append("#set ($REDIRECT_URL = \"https://${request.getServerName()}$request.getAttribute('javax.servlet.forward.request_uri')\")"); + sb.append("#end"); + sb.append("$response.sendRedirect(\"$REDIRECT_URL\")"); + sb.append("#end"); + } + + sb.append("#if($HTMLPAGE_REDIRECT != \"\")"); + sb.append("$response.setStatus(301)"); + sb.append("$response.setHeader(\"Location\", \"$HTMLPAGE_REDIRECT\")"); + sb.append("#end"); + + + sb.append("#if(!$doNotParseTemplate)"); + if (cmsTemplate.isDrawed()) {// We have a designed template + // Setting some theme variables + sb.append("#set ($dotTheme = $templatetool.theme(\"") + .append(cmsTemplate.getTheme()) + .append("\",\"") + .append(host.getIdentifier()) + .append("\"))"); + sb.append("#set ($dotThemeLayout = $templatetool.themeLayout(\"") + .append(cmsTemplate.getInode()) + .append("\"))"); + // Merging our template + sb.append("#parse(\"$dotTheme.templatePath\")"); + } else { + sb.append("#parse('") + .append(folderPath) + .append(cmsTemplate.getIdentifier()) + .append(".") + .append(VelocityType.TEMPLATE.fileExtension) + .append("')"); + } + sb.append("#end"); + + return writeOutVelocity(filePath, sb.toString()); + + + } + + + @Override + public InputStream writeObject(String id1, String id2, PageMode mode, String language, final String filePath) + throws DotDataException, DotSecurityException { + + HTMLPageAsset page = APILocator.getHTMLPageAssetAPI() + .fromContentlet(APILocator.getContentletAPI() + .findContentletByIdentifier(id1, mode.showLive, Long.parseLong(language), sysUser(), true)); + + + return buildStream(page, mode, filePath); + + + } + + +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/SiteLoader.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/SiteLoader.java new file mode 100644 index 000000000000..a995176981a3 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/SiteLoader.java @@ -0,0 +1,108 @@ +package com.dotcms.rendering.velocity.services; + + +import com.dotcms.rendering.velocity.util.VelocityUtil; + +import com.dotmarketing.beans.Host; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.CacheLocator; +import com.dotmarketing.business.UserAPI; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.portlets.containers.model.Container; +import com.dotmarketing.portlets.hostvariable.bussiness.HostVariableAPI; +import com.dotmarketing.portlets.hostvariable.model.HostVariable; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; +import com.dotmarketing.util.UtilMethods; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.Iterator; +import java.util.List; + +import org.apache.velocity.runtime.resource.ResourceManager; + +import com.liferay.portal.model.User; + + +public class SiteLoader implements DotLoader { + + + @SuppressWarnings("unchecked") + public InputStream buildStream(Host host, PageMode mode, String filePath) throws DotDataException, DotSecurityException { + + InputStream result; + StringBuilder sb = new StringBuilder(); + HostVariableAPI hostVariableAPI = APILocator.getHostVariableAPI(); + UserAPI userAPI = APILocator.getUserAPI(); + User user = userAPI.getSystemUser(); + List hvars = hostVariableAPI.getVariablesForHost(host.getIdentifier(), user, false); + + if (hvars.size() > 0) { + Iterator hostvars = hvars.iterator(); + + sb.append("#set ($host_variable = $contents.getEmptyMap())"); + int counter = 1; + while (hostvars.hasNext()) { + HostVariable next = (HostVariable) hostvars.next(); + sb.append("#set ($_dummy = $host_variable.put(\"") + .append(String.valueOf(next.getKey())) + .append("\", \"") + .append(String.valueOf(UtilMethods.espaceForVelocity(next.getValue()))) + .append("\"))"); + + counter++; + + } + } + + return writeOutVelocity(filePath, sb.toString()); + } + + + public void unpublishPageFile(Host host) { + + removeHostFile(host, false); + } + + + + public void removeHostFile(Host host, boolean EDIT_MODE) { + + } + + @Override + public InputStream writeObject(String id1, String id2, PageMode mode, String language, String filePath) + throws DotDataException, DotSecurityException { + + Host host = APILocator.getHostAPI() + .find(id1, sysUser(), false); + + return buildStream(host, mode, filePath); + + } + + @Override + public void invalidate(Object obj) { + for(PageMode mode : PageMode.values()) { + invalidate(obj, mode); + } + } + + @Override + public void invalidate(Object obj, PageMode mode) { + Host host = (Host)obj; + String folderPath = mode.name() + java.io.File.separator; + String velocityRootPath = VelocityUtil.getVelocityRootPath(); + String filePath = folderPath + host.getIdentifier() + "." + VelocityType.SITE.fileExtension; + velocityRootPath += java.io.File.separator; + java.io.File f = new java.io.File(velocityRootPath + filePath); + f.delete(); + DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); + vc.remove(ResourceManager.RESOURCE_TEMPLATE + filePath); + + } + +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/StringifyObject.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/StringifyObject.java new file mode 100644 index 000000000000..7b7005990e72 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/StringifyObject.java @@ -0,0 +1,104 @@ +package com.dotcms.rendering.velocity.services; + +import com.dotcms.repackage.com.ibm.icu.text.SimpleDateFormat; + +import java.io.StringWriter; +import java.util.Collection; +import java.util.Date; +import java.util.Iterator; + +final class StringifyObject { + final String stringified; + + public StringifyObject(final Object o) { + + if(o instanceof String[]) { + this.stringified = stringifyObject((String[]) o); + } + else if(o instanceof Collection) { + this.stringified = stringifyObject((Collection) o); + } + else if(o instanceof Boolean) { + + this.stringified = stringifyObject((Boolean) o); + } + else if(o instanceof Date) { + + this.stringified = stringifyObject((Date) o); + } + else if(o instanceof String) { + + this.stringified = stringifyObject((String) o); + } + else { + this.stringified = o.toString(); + } + } + + + private String stringifyObject(final String[] str) { + StringWriter sw = new StringWriter(); + sw.append('['); + for (int i = 0; i < str.length; i++) { + sw.append('"') + .append(str[i]) + .append("\""); + if (i != str.length - 1) { + sw.append(","); + } + } + sw.append(']'); + return sw.toString(); + } + + private String stringifyObject(final Collection co) { + StringWriter sw = new StringWriter(); + + sw.append('['); + Iterator it = co.iterator(); + while (it.hasNext()) { + Object obj = it.next(); + sw.append('"') + .append(obj.toString()) + .append("\""); + + if(it.hasNext()) { + sw.append(","); + } + } + sw.append(']'); + return sw.toString(); + } + + private String stringifyObject(final Boolean o) { + + return ((Boolean)o).toString(); + } + + private String stringifyObject(final String x) { + StringWriter sw = new StringWriter(); + if (x.startsWith("$")) { + return sw.toString(); + } else { + sw.append('"'); + sw.append(x.toString()); + sw.append('"'); + return sw.toString(); + } + } + + private String stringifyObject(final Date x) { + StringWriter sw = new StringWriter(); + String d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(x); + sw.append('"'); + sw.append(d); + sw.append('"'); + return sw.toString(); + } + + + + public String from() { + return this.stringified ; + } +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/TemplateLoader.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/TemplateLoader.java new file mode 100644 index 000000000000..6aa75fc9f57f --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/TemplateLoader.java @@ -0,0 +1,102 @@ +package com.dotcms.rendering.velocity.services; + + +import com.dotcms.rendering.velocity.util.VelocityUtil; + +import com.dotmarketing.beans.Identifier; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.CacheLocator; +import com.dotmarketing.business.DotStateException; +import com.dotmarketing.business.VersionableAPI; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.portlets.templates.model.Template; +import com.dotmarketing.util.Constants; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; + +import java.io.InputStream; + +import org.apache.velocity.runtime.resource.ResourceManager; + +/** + * @author will + * + * To change this generated comment edit the template variable "typecomment": + * Window>Preferences>Java>Templates. To enable and disable the creation of type comments go + * to Window>Preferences>Java>Code Generation. + */ +public class TemplateLoader implements DotLoader { + + + + public InputStream buildVelocity(Template template, PageMode mode, String filePath) + throws DotStateException, DotDataException { + Identifier identifier = APILocator.getIdentifierAPI() + .find(template); + return buildVelocity(template, identifier, mode, filePath); + } + + public InputStream buildVelocity(Template template, Identifier identifier, PageMode mode, String filePath) { + + + StringBuilder templateBody = new StringBuilder(); + + + templateBody.append(Constants.TEMPLATE_PREPROCESS); + templateBody.append(template.getBody()); + templateBody.append(Constants.TEMPLATE_POSTPROCESS); + + + + return writeOutVelocity(filePath, templateBody.toString()); + } + + + + @Override + public InputStream writeObject(String id1, String id2, PageMode mode, String language, String filePath) + throws DotDataException, DotSecurityException { + + Identifier identifier = APILocator.getIdentifierAPI() + .find(id1); + VersionableAPI versionableAPI = APILocator.getVersionableAPI(); + Template template = null; + if (mode.showLive) { + template = (Template) versionableAPI.findLiveVersion(identifier, sysUser(), true); + + } else { + template = (Template) versionableAPI.findWorkingVersion(identifier, sysUser(), true); + } + + Logger.debug(this, "DotResourceLoader:\tWriting out Template inode = " + template.getInode()); + + return buildVelocity(template, mode, filePath); + + + } + + @Override + public void invalidate(Object obj) { + for (PageMode mode : PageMode.values()) { + invalidate(obj, mode); + } + + } + + @Override + public void invalidate(Object obj, PageMode mode) { + Template template = (Template) obj; + String velocityRootPath = VelocityUtil.getVelocityRootPath(); + velocityRootPath += java.io.File.separator; + + String folderPath = mode.name() + java.io.File.separator; + String filePath = folderPath + template.getIdentifier() + "." + VelocityType.TEMPLATE.fileExtension; + java.io.File f = new java.io.File(velocityRootPath + filePath); + f.delete(); // todo: check if the file exists before remove? + DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); + vc.remove(ResourceManager.RESOURCE_TEMPLATE + filePath); + + + } +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/VTLLoader.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/VTLLoader.java new file mode 100644 index 000000000000..0e25444b5844 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/VTLLoader.java @@ -0,0 +1,145 @@ +package com.dotcms.rendering.velocity.services; + +import com.dotmarketing.util.Config; +import com.dotmarketing.util.ConfigUtils; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; +import com.dotmarketing.util.UtilMethods; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; + +import org.apache.velocity.exception.ResourceNotFoundException; + +import com.liferay.util.FileUtil; + +public class VTLLoader implements DotLoader { + private static String velocityCanoncalPath; + private static String assetCanoncalPath; + private static String assetRealCanoncalPath; + private static String VELOCITY_ROOT; + private static VTLLoader vtlServices; + + private VTLLoader() { + init(); + } + + public static VTLLoader instance() { + if (vtlServices == null) { + synchronized (VTLLoader.class) { + if (vtlServices == null) { + vtlServices = new VTLLoader(); + } + } + } + return vtlServices; + } + + private void init() { + String velocityRootPath = Config.getStringProperty("VELOCITY_ROOT", "/WEB-INF/velocity"); + if (velocityRootPath.startsWith("/WEB-INF")) { + String startPath = velocityRootPath.substring(0, 8); + String endPath = velocityRootPath.substring(9, velocityRootPath.length()); + velocityRootPath = FileUtil.getRealPath(startPath) + File.separator + endPath; + } + + VELOCITY_ROOT = velocityRootPath + File.separator; + + File f = new File(VELOCITY_ROOT); + try { + if(f.exists()){ + velocityCanoncalPath = f.getCanonicalPath(); + } + } catch (IOException e) { + Logger.fatal(this,e.getMessage(),e); + } + + try { + if(UtilMethods.isSet(Config.getStringProperty("ASSET_REAL_PATH"))){ + f = new File(Config.getStringProperty("ASSET_REAL_PATH")); + if(f.exists()){ + assetRealCanoncalPath = f.getCanonicalPath(); + } + } + } catch (IOException e) { + Logger.fatal(this,e.getMessage(),e); + } + + try { + if(UtilMethods.isSet(Config.getStringProperty("ASSET_PATH"))){ + f = new File(FileUtil.getRealPath(Config.getStringProperty("ASSET_PATH"))); + if(f.exists()){ + assetCanoncalPath = f.getCanonicalPath(); + } + } + } catch (IOException e) { + Logger.fatal(this,e.getMessage(),e); + } + + + } + + InputStream streamFile(String filePath) throws IOException { + boolean serveFile = false; + Logger.debug(this, "Not a CMS Velocity File : " + filePath); + + java.io.File f = null; + String lookingFor = ""; + if (filePath.startsWith("dynamic")) { + lookingFor = ConfigUtils.getDynamicContentPath() + File.separator + "velocity" + File.separator + filePath; + + } else { + lookingFor = VELOCITY_ROOT + filePath; + } + f = new java.io.File(lookingFor); + if (!f.exists()) { + f = new java.io.File(filePath); + } + if (!f.exists()) { + throw new ResourceNotFoundException("cannot find resource"); + } + String canon = f.getCanonicalPath(); + File dynamicContent = new File(ConfigUtils.getDynamicContentPath()); + + if (assetRealCanoncalPath != null && canon.startsWith(assetRealCanoncalPath)) { + serveFile = true; + } else if (velocityCanoncalPath != null && canon.startsWith(velocityCanoncalPath)) { + serveFile = true; + } else if (assetCanoncalPath != null && canon.startsWith(assetCanoncalPath)) { + serveFile = true; + } else if (canon.startsWith(dynamicContent.getCanonicalPath())) { + serveFile = true; + } + if (!serveFile) { + Logger.warn(this, "POSSIBLE HACK ATTACK DotResourceLoader: " + lookingFor); + throw new ResourceNotFoundException("cannot find resource"); + } + return new BufferedInputStream(Files.newInputStream(f.toPath())); + + } + + + @Override + public InputStream writeObject(String id1, String id2, PageMode mode, String language, String filePath) { + try { + return streamFile(filePath); + } catch (IOException e) { + throw new ResourceNotFoundException("cannot find resource:" + filePath); + } + } + + @Override + public void invalidate(Object obj) { + // TODO Auto-generated method stub + + } + + @Override + public void invalidate(Object obj, PageMode mode) { + // TODO Auto-generated method stub + + } +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/VelocityPrettyWriter.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/VelocityPrettyWriter.java new file mode 100644 index 000000000000..7da76b3f82eb --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/VelocityPrettyWriter.java @@ -0,0 +1,69 @@ +package com.dotcms.rendering.velocity.services; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; + +public class VelocityPrettyWriter extends OutputStreamWriter { + + public VelocityPrettyWriter(OutputStream out) throws UnsupportedEncodingException { + super(out, "UTF8"); + + } + + + public VelocityPrettyWriter(OutputStream out, Charset cs) throws UnsupportedEncodingException { + super(out, "UTF8"); + + } + + @Override + public void write(char[] chars) throws IOException { + chars = replacePounds(chars); + super.write(new String(chars)); + } + + @Override + public void write(String chars) throws IOException { + + chars = new String(replacePounds(chars.toCharArray())); + super.write(chars); + } + + @Override + public void write(char[] chars, int start, int len) throws IOException { + chars = replacePounds(chars); + + + super.write(chars, start, chars.length); + } + + @Override + public void write(String chars, int start, int len) throws IOException { + chars = new String(replacePounds(chars.toCharArray())); + + super.write(chars, start, chars.length()); + } + + + private char[] replacePounds(char[] chars) { + StringBuffer sw = new StringBuffer(); + + + for (char c : chars) { + if (c == '#') { + sw.append('\n'); + } + sw.append(c); + } + + return sw.toString() + .toCharArray(); + + } + + + +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/VelocityType.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/VelocityType.java new file mode 100644 index 000000000000..d5776ee9fe31 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/services/VelocityType.java @@ -0,0 +1,37 @@ +package com.dotcms.rendering.velocity.services; + + +import com.dotmarketing.util.UtilMethods; + +public enum VelocityType { + CONTAINER("container"), + CONTENT("contentlet"), + CONTENT_MAP("oldContentMap"), + FIELD("fields"), + HTMLPAGE("dotHtmlPage"), + TEMPLATE("templateLayout"), + CONTENT_TYPE("contentType"), + SITE("site"), + VTL("vtl"), + VELOCITY_MACROS("vm"), + VELOCITY_LEGACY_VL("vl"), + NOT_VELOCITY("not_velocity"); + final public String fileExtension; + + VelocityType(String fileExtension) { + this.fileExtension = fileExtension.toLowerCase(); + } + + + public static VelocityType resolveVelocityType(final String path) { +; final String extenstion = UtilMethods.getFileExtension(path); + + + for (final VelocityType val : VelocityType.values()) { + if (extenstion.equals(val.fileExtension)) { + return val; + } + } + return VelocityType.NOT_VELOCITY; + } +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/servlet/VelocityLiveServlet.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/servlet/VelocityLiveServlet.java new file mode 100644 index 000000000000..85c7691ab73d --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/servlet/VelocityLiveServlet.java @@ -0,0 +1,391 @@ +package com.dotcms.rendering.velocity.servlet; + +import com.dotcms.business.CloseDB; +import com.dotcms.enterprise.LicenseUtil; +import com.dotcms.enterprise.license.LicenseLevel; +import com.dotcms.rendering.velocity.services.VelocityType; +import com.dotcms.rendering.velocity.util.VelocityUtil; +import com.dotcms.rendering.velocity.viewtools.RequestWrapper; +import com.dotcms.visitor.business.VisitorAPI; +import com.dotcms.visitor.domain.Visitor; + +import com.dotmarketing.beans.Host; +import com.dotmarketing.beans.Identifier; +import com.dotmarketing.beans.UserProxy; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.BlockPageCache; +import com.dotmarketing.business.BlockPageCache.PageCacheParameters; +import com.dotmarketing.business.CacheLocator; +import com.dotmarketing.business.web.HostWebAPI; +import com.dotmarketing.business.web.LanguageWebAPI; +import com.dotmarketing.business.web.WebAPILocator; +import com.dotmarketing.db.DbConnectionFactory; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.factories.ClickstreamFactory; +import com.dotmarketing.filters.CMSFilter; +import com.dotmarketing.filters.CMSUrlUtil; +import com.dotmarketing.filters.Constants; +import com.dotmarketing.portlets.htmlpageasset.model.IHTMLPage; +import com.dotmarketing.portlets.rules.business.RulesEngine; +import com.dotmarketing.portlets.rules.model.Rule; +import com.dotmarketing.util.Config; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; +import com.dotmarketing.util.UtilMethods; +import com.dotmarketing.util.WebKeys; + +import java.io.File; +import java.io.FilterWriter; +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.net.URLDecoder; +import java.util.Optional; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.apache.velocity.context.Context; +import org.apache.velocity.exception.MethodInvocationException; +import org.apache.velocity.exception.ParseErrorException; +import org.apache.velocity.exception.ResourceNotFoundException; + +import com.liferay.portal.language.LanguageException; +import com.liferay.portal.language.LanguageUtil; +import com.liferay.portal.model.User; + +public class VelocityLiveServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + private static HostWebAPI hostWebAPI = WebAPILocator.getHostWebAPI(); + private static VisitorAPI visitorAPI = APILocator.getVisitorAPI(); + private String CHARSET = "UTF-8"; + + + + @Override + @CloseDB + protected void service(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { + + final String uri = URLDecoder.decode((req.getAttribute(Constants.CMS_FILTER_URI_OVERRIDE) != null) + ? (String) req.getAttribute(Constants.CMS_FILTER_URI_OVERRIDE) + : req.getRequestURI(), "UTF-8"); + + + + RequestWrapper request = new RequestWrapper(req); + request.setRequestUri(uri); + + + Host host = hostWebAPI.getCurrentHostNoThrow(request); + + + // Checking if host is active + boolean hostlive; + + + try { + hostlive = APILocator.getVersionableAPI() + .hasLiveVersion(host); + } catch (Exception e1) { + UtilMethods.closeDbSilently(); + throw new ServletException(e1); + } + if (!hostlive) { + try { + response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, + LanguageUtil.get("server-unavailable-error-message")); + } catch (LanguageException e) { + Logger.error(CMSFilter.class, e.getMessage(), e); + response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); + } + return; + } + + + if (DbConnectionFactory.isMsSql() && LicenseUtil.getLevel() < LicenseLevel.PROFESSIONAL.level) { + request.getRequestDispatcher("/portal/no_license.jsp") + .forward(request, response); + return; + } + + if (DbConnectionFactory.isOracle() && LicenseUtil.getLevel() < LicenseLevel.PRIME.level) { + request.getRequestDispatcher("/portal/no_license.jsp") + .forward(request, response); + return; + } + if (!LicenseUtil.isASAllowed()) { + request.getRequestDispatcher("/portal/no_license.jsp") + .forward(request, response); + return; + + } + + try { + + + if (uri == null) { + response.sendError(500, "VelocityServlet called without running through the CMS Filter"); + Logger.error(this.getClass(), + "You cannot call the VelocityServlet without passing the requested url via a requestAttribute called " + + Constants.CMS_FILTER_URI_OVERRIDE); + return; + } + + + // we will always need a visitor in admin mode + if (PageMode.get(request).isAdmin) { + visitorAPI.getVisitor(request, true); + } + LanguageWebAPI langWebAPI = WebAPILocator.getLanguageWebAPI(); + langWebAPI.checkSessionLocale(request); + + doLiveMode(request, response); + + + } catch (ResourceNotFoundException rnfe) { + Logger.error(this, "ResourceNotFoundException" + rnfe.toString(), rnfe); + response.sendError(404); + return; + } catch (ParseErrorException pee) { + Logger.error(this, "Template Parse Exception : " + pee.toString(), pee); + response.sendError(500, "Template Parse Exception"); + } catch (MethodInvocationException mie) { + Logger.error(this, "MethodInvocationException" + mie.toString(), mie); + response.sendError(500, "MethodInvocationException Error on template"); + } catch (Throwable e) { + Logger.error(this, "Exception" + e.toString(), e); + response.sendError(500, "Exception Error on template"); + + } finally { + DbConnectionFactory.closeSilently(); + } + + } + + public void init(ServletConfig config) throws ServletException { + + Logger.info(this.getClass(), "VelocityLiveServlet"); + } + + + /** + * + * @param request + * @param response + * @throws Exception + */ + public void doLiveMode(HttpServletRequest request, HttpServletResponse response) throws Exception { + LicenseUtil.startLiveMode(); + try { + + String uri = URLDecoder.decode(request.getRequestURI(), UtilMethods.getCharsetConfiguration()); + Host host = hostWebAPI.getCurrentHostNoThrow(request); + + + // Find the current language + long currentLanguageId = VelocityUtil.getLanguageId(request); + + + // now we check identifier cache first (which DOES NOT have a 404 cache ) + Identifier ident = APILocator.getIdentifierAPI() + .find(host, uri); + if (ident == null || ident.getId() == null) { + throw new ResourceNotFoundException(String.format("Resource %s not found in Live mode!", uri)); + } + response.setContentType(CHARSET); + request.setAttribute("idInode", String.valueOf(ident.getId())); + Logger.debug(VelocityLiveServlet.class, "VELOCITY HTML INODE=" + ident.getId()); + + RulesEngine.fireRules(request, response); + + if (response.isCommitted()) { + /* + * Some form of redirect, error, or the request has already been fulfilled in some + * fashion by one or more of the actionlets. + */ + Logger.debug(VelocityLiveServlet.class, "An EVERY_PAGE RuleEngine Action has committed the response."); + return; + } + + + User user = null; + HttpSession session = request.getSession(false); + try { + if (session != null) + user = (User) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER); + } catch (Exception nsue) { + Logger.warn(this, "Exception trying to getUser: " + nsue.getMessage(), nsue); + } + + Logger.debug(VelocityLiveServlet.class, "Page Permissions for URI=" + uri); + + + IHTMLPage page; + + try { + page = VelocityUtil.getPage(ident, request, true, null); + } catch (DotDataException e) { + Logger.info(VelocityLiveServlet.class, "Unable to find live version of page. Identifier: " + ident.getId()); + throw new ResourceNotFoundException(String.format("Resource %s not found in Live mode!", uri)); + } + + // Verify and handle the case for unauthorized access of this contentlet + Boolean unauthorized = CMSUrlUtil.getInstance() + .isUnauthorizedAndHandleError(page, uri, user, request, response); + if (unauthorized) { + return; + } + + // Fire the page rules until we know we have permission. + RulesEngine.fireRules(request, response, page, Rule.FireOn.EVERY_PAGE); + + Logger.debug(VelocityLiveServlet.class, "Recording the ClickStream"); + if (Config.getBooleanProperty("ENABLE_CLICKSTREAM_TRACKING", false)) { + if (user != null) { + UserProxy userProxy = com.dotmarketing.business.APILocator.getUserProxyAPI() + .getUserProxy(user, APILocator.getUserAPI() + .getSystemUser(), false); + if (!userProxy.isNoclicktracking()) { + ClickstreamFactory.addRequest((HttpServletRequest) request, ((HttpServletResponse) response), host); + } + } else { + ClickstreamFactory.addRequest((HttpServletRequest) request, ((HttpServletResponse) response), host); + } + } + + // Begin page caching + String userId = (user != null) ? user.getUserId() + : APILocator.getUserAPI() + .getAnonymousUser() + .getUserId(); + String language = String.valueOf(currentLanguageId); + String urlMap = (String) request.getAttribute(WebKeys.WIKI_CONTENTLET_INODE); + String queryString = request.getQueryString(); + String persona = null; + Optional v = visitorAPI.getVisitor(request, false); + if (v.isPresent() && v.get() + .getPersona() != null) { + persona = v.get() + .getPersona() + .getKeyTag(); + } + + + PageCacheParameters cacheParameters = + new BlockPageCache.PageCacheParameters(userId, language, urlMap, queryString, persona); + + boolean buildCache = false; + String key = VelocityUtil.getPageCacheKey(request, response); + if (key != null) { + String cachedPage = CacheLocator.getBlockPageCache() + .get(page, cacheParameters); + if (cachedPage == null || "refresh".equals(request.getParameter("dotcache")) + || "refresh".equals(request.getAttribute("dotcache")) + || (request.getSession(false) != null && "refresh".equals(request.getSession(true) + .getAttribute("dotcache")))) { + // build cached response + buildCache = true; + } else { + // have cached response and are not refreshing, send it + response.getWriter() + .write(cachedPage); + return; + } + } + + Writer out = (buildCache) ? new StringWriter(4096) : new VelocityFilterWriter(response.getWriter()); + // get the context from the requst if possible + Context context = VelocityUtil.getWebContext(request, response); + request.setAttribute("velocityContext", context); + Logger.debug(VelocityLiveServlet.class, "HTMLPage Identifier:" + ident.getId()); + + PageMode mode = PageMode.get(request); + try { + VelocityUtil.getEngine() + .getTemplate( + mode.name() + File.separator + ident.getId() + "_" + page.getLanguageId() + "." + VelocityType.HTMLPAGE.fileExtension) + .merge(context, out); + } catch (Throwable e) { + Logger.warn(this, "can't do live mode merge", e); + } + session = request.getSession(false); + if (buildCache) { + String trimmedPage = out.toString() + .trim(); + response.getWriter() + .write(trimmedPage); + response.getWriter() + .close(); + synchronized (key.intern()) { + // CacheLocator.getHTMLPageCache().remove(page); + CacheLocator.getBlockPageCache() + .add(page, trimmedPage, cacheParameters); + } + } else { + out.close(); + } + } finally { + LicenseUtil.stopLiveMode(); + } + + } + + + + public class VelocityFilterWriter extends FilterWriter { + + private boolean firstNonWhiteSpace = false; + + public VelocityFilterWriter(Writer arg0) { + super(arg0); + + } + + @Override + public void write(char[] arg0) throws IOException { + if (firstNonWhiteSpace) { + super.write(arg0); + } else { + + for (int i = 0; i < arg0.length; i++) { + if (arg0[i] > 32) { + firstNonWhiteSpace = true; + } + if (firstNonWhiteSpace) { + super.write(arg0[i]); + } + + } + + } + + } + + @Override + public void write(String arg0) throws IOException { + if (firstNonWhiteSpace) { + super.write(arg0); + } else { + char[] stringChar = arg0.toCharArray(); + for (int i = 0; i < stringChar.length; i++) { + + if (stringChar[i] > 32) { + firstNonWhiteSpace = true; + super.write(arg0.substring(i, stringChar.length)); + break; + } + + } + + } + + } + + } + +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/servlet/VelocityPreviewServlet.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/servlet/VelocityPreviewServlet.java new file mode 100644 index 000000000000..8a2af7e52132 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/servlet/VelocityPreviewServlet.java @@ -0,0 +1,359 @@ +package com.dotcms.rendering.velocity.servlet; + +import com.dotcms.business.CloseDBIfOpened; +import com.dotcms.enterprise.LicenseUtil; +import com.dotcms.enterprise.license.LicenseLevel; +import com.dotcms.rendering.velocity.services.PageContextBuilder; +import com.dotcms.rendering.velocity.services.VelocityType; +import com.dotcms.rendering.velocity.util.VelocityUtil; +import com.dotcms.rendering.velocity.viewtools.DotTemplateTool; +import com.dotcms.rendering.velocity.viewtools.RequestWrapper; +import com.dotcms.rendering.velocity.viewtools.content.ContentMap; +import com.dotcms.visitor.business.VisitorAPI; + +import com.dotmarketing.beans.Host; +import com.dotmarketing.beans.Identifier; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.PermissionAPI; +import com.dotmarketing.business.web.HostWebAPI; +import com.dotmarketing.business.web.WebAPILocator; +import com.dotmarketing.db.DbConnectionFactory; +import com.dotmarketing.filters.CMSFilter; +import com.dotmarketing.filters.Constants; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.htmlpageasset.model.IHTMLPage; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; +import com.dotmarketing.util.UtilMethods; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.URLDecoder; +import java.util.Map; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.velocity.Template; +import org.apache.velocity.context.Context; +import org.apache.velocity.exception.MethodInvocationException; +import org.apache.velocity.exception.ParseErrorException; +import org.apache.velocity.exception.ResourceNotFoundException; + +import com.liferay.portal.language.LanguageException; +import com.liferay.portal.language.LanguageUtil; +import com.liferay.portal.model.User; + +public class VelocityPreviewServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + + private static PermissionAPI permissionAPI = APILocator.getPermissionAPI(); + + + + private static HostWebAPI hostWebAPI = WebAPILocator.getHostWebAPI(); + + private static VisitorAPI visitorAPI = APILocator.getVisitorAPI(); + + public static void setPermissionAPI(PermissionAPI permissionAPIRef) { + permissionAPI = permissionAPIRef; + } + + private String CHARSET = "UTF-8"; + + + + public static final String VELOCITY_CONTEXT = "velocityContext"; + + + @CloseDBIfOpened + protected void service(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { + + final String uri = URLDecoder.decode((req.getAttribute(Constants.CMS_FILTER_URI_OVERRIDE) != null) + ? (String) req.getAttribute(Constants.CMS_FILTER_URI_OVERRIDE) + : req.getRequestURI(), "UTF-8"); + + + + RequestWrapper request = new RequestWrapper(req); + request.setRequestUri(uri); + + + Host host = hostWebAPI.getCurrentHostNoThrow(request); + + PageMode mode = PageMode.get(request); + // Checking if host is active + boolean hostlive; + + + try { + hostlive = APILocator.getVersionableAPI() + .hasLiveVersion(host); + } catch (Exception e1) { + UtilMethods.closeDbSilently(); + throw new ServletException(e1); + } + if (!hostlive) { + try { + response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, + LanguageUtil.get("server-unavailable-error-message")); + } catch (LanguageException e) { + Logger.error(CMSFilter.class, e.getMessage(), e); + response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); + } + return; + } + + + if (DbConnectionFactory.isMsSql() && LicenseUtil.getLevel() < LicenseLevel.PROFESSIONAL.level) { + request.getRequestDispatcher("/portal/no_license.jsp") + .forward(request, response); + return; + } + + if (DbConnectionFactory.isOracle() && LicenseUtil.getLevel() < LicenseLevel.PRIME.level) { + request.getRequestDispatcher("/portal/no_license.jsp") + .forward(request, response); + return; + } + if (!LicenseUtil.isASAllowed()) { + request.getRequestDispatcher("/portal/no_license.jsp") + .forward(request, response); + return; + + } + + try { + + + if (uri == null) { + response.sendError(500, "VelocityServlet called without running through the CMS Filter"); + Logger.error(this.getClass(), + "You cannot call the VelocityServlet without passing the requested url via a requestAttribute called " + + Constants.CMS_FILTER_URI_OVERRIDE); + return; + } + + + + // we will always need a visitor in admin mode + if (mode.isAdmin) { + visitorAPI.getVisitor(request, true); + } + + + switch (mode) { + case PREVIEW_MODE: + Logger.debug(VelocityPreviewServlet.class, "VELOCITY SERVLET I'M ON PREVIEW MODE!!!"); + doPreviewMode(request, response); + break; + case EDIT_MODE: + Logger.debug(VelocityPreviewServlet.class, "VELOCITY SERVLET I'M ON EDIT MODE!!!"); + doEditMode(request, response); + break; + default: + response.sendError(HttpServletResponse.SC_UNAUTHORIZED); + return; + } + + + + } catch (ResourceNotFoundException rnfe) { + Logger.error(this, "ResourceNotFoundException" + rnfe.toString(), rnfe); + response.sendError(404); + return; + } catch (ParseErrorException pee) { + Logger.error(this, "Template Parse Exception : " + pee.toString(), pee); + response.sendError(500, "Template Parse Exception"); + } catch (MethodInvocationException mie) { + Logger.error(this, "MethodInvocationException" + mie.toString(), mie); + response.sendError(500, "MethodInvocationException Error on template"); + } catch (Exception e) { + Logger.error(this, "Exception" + e.toString(), e); + response.sendError(500, "Exception Error on template"); + + } finally { + DbConnectionFactory.closeSilently(); + } + + } + + public void init(ServletConfig config) throws ServletException { + + + + } + + public void doPreviewMode(HttpServletRequest request, HttpServletResponse response) throws Exception { + + String uri = URLDecoder.decode(request.getRequestURI(), UtilMethods.getCharsetConfiguration()); + PageMode mode = PageMode.PREVIEW_MODE; + + Host host = hostWebAPI.getCurrentHost(request); + + + // Getting the user to check the permissions + User user = com.liferay.portal.util.PortalUtil.getUser(request); + + // Getting the identifier from the uri + Identifier id = APILocator.getIdentifierAPI() + .find(host, uri); + request.setAttribute("idInode", id.getId()); + Logger.debug(VelocityPreviewServlet.class, "VELOCITY HTML INODE=" + id.getId()); + + Template template = null; + Template hostVariablesTemplate = null; + + // creates the context where to place the variables + response.setContentType(CHARSET); + Context context = VelocityUtil.getWebContext(request, response); + + IHTMLPage htmlPage = VelocityUtil.getPage(id, request, false, context); + if ("contentlet".equals(htmlPage.getType())) { + context.put("dotPageContent", new ContentMap(((Contentlet) htmlPage), user, true, host, context)); + } + + + + com.dotmarketing.portlets.templates.model.Template cmsTemplate = APILocator.getHTMLPageAssetAPI() + .getTemplate(htmlPage, true); + + + + VelocityUtil.makeBackendContext(context, htmlPage, cmsTemplate.getInode(), id.getURI(), request, mode, host); + + + + PageContextBuilder builder = new PageContextBuilder(htmlPage, user, PageMode.PREVIEW_MODE); + builder.addAll(context); + + + + hostVariablesTemplate = VelocityUtil.getEngine() + .getTemplate(PageMode.PREVIEW_MODE.name() + File.separator + host.getIdentifier() + "." + VelocityType.SITE.fileExtension); + + if (cmsTemplate.isDrawed()) {// We have a designed template + // Setting some theme variables + Map dotThemeData = DotTemplateTool.theme(cmsTemplate.getTheme(), host.getIdentifier()); + context.put("dotTheme", dotThemeData); + context.put("dotThemeLayout", DotTemplateTool.themeLayout(cmsTemplate.getInode())); + // Our designed template + template = VelocityUtil.getEngine() + .getTemplate((String) dotThemeData.get("templatePath")); + } else { + template = VelocityUtil.getEngine() + .getTemplate(PageMode.PREVIEW_MODE.name() + File.separator + cmsTemplate.getIdentifier() + "." + + VelocityType.TEMPLATE.fileExtension); + } + + + + PrintWriter out = response.getWriter(); + request.setAttribute("velocityContext", context); + try { + + if (builder.getWidgetPreExecute() != null) { + VelocityUtil.getEngine() + .evaluate(context, out, "", builder.getWidgetPreExecute()); + } + if (hostVariablesTemplate != null) + hostVariablesTemplate.merge(context, out); + template.merge(context, out); + + } catch (ParseErrorException e) { + out.append(e.getMessage()); + } + } + + + protected void doEditMode(HttpServletRequest request, HttpServletResponse response) throws Exception { + PageMode mode = PageMode.PREVIEW_MODE; + String uri = request.getRequestURI(); + + Host host = hostWebAPI.getCurrentHost(request); + + + // Getting the user to check the permissions + User user = com.liferay.portal.util.PortalUtil.getUser(request); + + + // Getting the identifier from the uri + Identifier id = APILocator.getIdentifierAPI() + .find(host, uri); + request.setAttribute("idInode", String.valueOf(id.getId())); + Logger.debug(VelocityPreviewServlet.class, "VELOCITY HTML INODE=" + id.getId()); + + Template template; + Template hostVariablesTemplate = null; + + // creates the context where to place the variables + response.setContentType(CHARSET); + request.setAttribute("EDIT_MODE", Boolean.TRUE); + Context context = VelocityUtil.getWebContext(request, response); + + IHTMLPage htmlPage = VelocityUtil.getPage(id, request, false, context); + + context.put("dotPageContent", new ContentMap(((Contentlet) htmlPage), user, mode, host, context)); + + + com.dotmarketing.portlets.templates.model.Template cmsTemplate = APILocator.getHTMLPageAssetAPI() + .getTemplate(htmlPage, true); + + if (cmsTemplate == null) {// DOTCMS-4051 + cmsTemplate = new com.dotmarketing.portlets.templates.model.Template(); + Logger.debug(VelocityPreviewServlet.class, "HTMLPAGE TEMPLATE NOT FOUND"); + } + + Identifier templateIdentifier = APILocator.getIdentifierAPI() + .find(cmsTemplate); + + Logger.debug(VelocityPreviewServlet.class, "VELOCITY TEMPLATE INODE=" + cmsTemplate.getInode()); + + VelocityUtil.makeBackendContext(context, htmlPage, cmsTemplate.getInode(), id.getURI(), request, mode, host); + + + PageContextBuilder builder = new PageContextBuilder(htmlPage, user, PageMode.PREVIEW_MODE); + builder.addAll(context); + + hostVariablesTemplate = VelocityUtil.getEngine() + .getTemplate(PageMode.EDIT_MODE.name() + File.separator + host.getIdentifier() + "." + VelocityType.SITE.fileExtension); + + if (cmsTemplate.isDrawed()) {// We have a designed template + // Setting some theme variables + Map dotThemeData = DotTemplateTool.theme(cmsTemplate.getTheme(), host.getIdentifier()); + context.put("dotTheme", dotThemeData); + context.put("dotThemeLayout", DotTemplateTool.themeLayout(cmsTemplate.getInode())); + // Our designed template + template = VelocityUtil.getEngine() + .getTemplate((String) dotThemeData.get("templatePath")); + } else { + template = VelocityUtil.getEngine() + .getTemplate(PageMode.EDIT_MODE.name() + File.separator + templateIdentifier.getId() + "." + + VelocityType.TEMPLATE.fileExtension); + } + + PrintWriter out = response.getWriter(); + request.setAttribute("velocityContext", context); + try { + if (builder.getWidgetPreExecute() != null) { + VelocityUtil.getEngine() + .evaluate(context, out, "", builder.getWidgetPreExecute()); + } + if (hostVariablesTemplate != null) + hostVariablesTemplate.merge(context, out); + template.merge(context, out); + + } catch (ParseErrorException e) { + out.append(e.getMessage()); + } + } + + + +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/util/VelocityProfiler.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/util/VelocityProfiler.java new file mode 100644 index 000000000000..cc2a89e30721 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/util/VelocityProfiler.java @@ -0,0 +1,28 @@ +package com.dotcms.rendering.velocity.util; + +import com.dotmarketing.util.Logger; + +import com.liferay.portal.model.User; + +public class VelocityProfiler { + + public static void log(Class cl,String msg){ + Logger.info(cl, msg); + Logger.info(VelocityProfiler.class, cl.toString() + msg); + } + + public static void log(Class cl,String methodName,String msg){ + Logger.info(cl, methodName + " : " + msg); + Logger.info(VelocityProfiler.class, cl.toString() + " : " + methodName + " : " + msg); + } + + public static void log(Class cl,String methodName,String msg,User user){ + if(user == null || user.getUserId() == null){ + log(cl, methodName, msg); + }else{ + Logger.info(cl, "UserId : "+user.getUserId()+ " : " + methodName + " : " + msg); + Logger.info(VelocityProfiler.class,"UserId : "+user.getUserId()+ " : " + cl.toString() + " : " + methodName + " : " + msg); + } + } + +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/util/VelocityUtil.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/util/VelocityUtil.java new file mode 100644 index 000000000000..e295af09cb8e --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/util/VelocityUtil.java @@ -0,0 +1,607 @@ +package com.dotcms.rendering.velocity.util; + +import static com.dotmarketing.business.PermissionAPI.PERMISSION_PUBLISH; + +import com.dotcms.enterprise.LicenseUtil; +import com.dotcms.enterprise.license.LicenseLevel; +import com.dotcms.rendering.velocity.viewtools.LanguageWebAPI; +import com.dotcms.rendering.velocity.viewtools.RequestWrapper; +import com.dotcms.visitor.domain.Visitor; + +import com.dotmarketing.beans.Host; +import com.dotmarketing.beans.Identifier; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.DotStateException; +import com.dotmarketing.business.Role; +import com.dotmarketing.business.web.WebAPILocator; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotRuntimeException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.htmlpageasset.model.IHTMLPage; +import com.dotmarketing.portlets.languagesmanager.model.DisplayedLanguage; +import com.dotmarketing.portlets.languagesmanager.model.Language; +import com.dotmarketing.util.Config; +import com.dotmarketing.util.Constants; +import com.dotmarketing.util.InodeUtils; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; +import com.dotmarketing.util.PortletURLUtil; +import com.dotmarketing.util.StringUtils; +import com.dotmarketing.util.UtilMethods; +import com.dotmarketing.util.WebKeys; + +import java.io.File; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.context.Context; +import org.apache.velocity.exception.ParseErrorException; +import org.apache.velocity.exception.ResourceNotFoundException; +import org.apache.velocity.tools.view.ToolboxManager; +import org.apache.velocity.tools.view.context.ChainedContext; +import org.apache.velocity.tools.view.servlet.ServletToolboxManager; + +import com.liferay.portal.model.User; +import com.liferay.util.SystemProperties; + + +public class VelocityUtil { + + private static VelocityEngine ve = null; + private static boolean DEFAULT_PAGE_TO_DEFAULT_LANGUAGE = LanguageWebAPI.canDefaultPageToDefaultLanguage(); + + private synchronized static void init(){ + if(ve != null) + return; + ve = new VelocityEngine(); + try{ + ve.init(SystemProperties.getProperties()); + + Logger.debug(VelocityUtil.class, SystemProperties.getProperties().toString()); + }catch (Exception e) { + Logger.error(VelocityUtil.class,e.getMessage(),e); + } + } + + public static VelocityEngine getEngine(){ + if(ve == null){ + init(); + if(ve == null){ + Logger.fatal(VelocityUtil.class,"Velocity Engine unable to initialize : THIS SHOULD NEVER HAPPEN"); + throw new DotRuntimeException("Velocity Engine unable to initialize : THIS SHOULD NEVER HAPPEN"); + } + } + return ve; + } + /** + * Changes $ and # to velocity escapes. This is helps filter out velocity code injections. + * @param s + * @return + */ + public static String cleanVelocity(String s) { + if (s==null) { + return null; + } + s=s.replace("$", "${esc.dollar}"); + s=s.replace("#", "${esc.hash}"); + return s; + } + + + + public String parseVelocity(String velocityCode, Context ctx){ + VelocityEngine ve = VelocityUtil.getEngine(); + StringWriter stringWriter = new StringWriter(); + try { + ve.evaluate(ctx, stringWriter, "VelocityUtil:parseVelocity", velocityCode); + }catch (Exception e) { + Logger.error(this,e.getMessage(),e); + } + return stringWriter.toString(); + + } + + + public static String convertToVelocityVariable(final String variable, boolean firstLetterUppercase){ + + + return (firstLetterUppercase) + ? StringUtils.camelCaseUpper(variable) + : StringUtils.camelCaseLower(variable); + + } + + + public static Boolean isNotAllowedVelocityVariableName(String variable){ + + + String [] notallwdvelvars={"inode","type", "modDate", "owner", "ownerCanRead", "ownerCanWrite", "ownerCanPublish", + "modUser", "working", "live", "deleted", "locked","structureInode", "languageId", "permissions", + "identifier", "conHost", "conFolder", "Host", "folder"}; + Boolean found=false; + for(String notallowed : notallwdvelvars){ + if(variable.equalsIgnoreCase(notallowed)){ + found=true; + } + + } + return found; + } + + /** + * Returns a basic Velocity Context without any toolbox or request + * response, session objects; + * @return + */ + + public static Context getBasicContext() { + Context context = new VelocityContext(); + context.put("UtilMethods", new UtilMethods()); + context.put("PortletURLUtil", new PortletURLUtil()); + context.put("quote", "\""); + context.put("pounds", "##"); + context.put("return", "\n"); + context.put("velocityContext", context); + context.put("language", "1"); + context.put("InodeUtils", new InodeUtils()); + return context; + } + + + /** + * Gets creates Velocity context will all the toolbox, user, host, language and request stuff + * inside the map + * @param request + * @param response + * @return + */ + public static ChainedContext getWebContext(HttpServletRequest request, HttpServletResponse response) { + return getWebContext(getBasicContext(), request, response); + } + + + public static ChainedContext getWebContext(Context ctx, HttpServletRequest request, HttpServletResponse response) { + + if ( ctx == null ) { + ctx = getBasicContext(); + } + + // http://jira.dotmarketing.net/browse/DOTCMS-2917 + + //get the context from the request if possible + ChainedContext context; + if ( request.getAttribute( com.dotcms.rendering.velocity.Constants.VELOCITY_CONTEXT ) != null && request.getAttribute( com.dotcms.rendering.velocity.Constants.VELOCITY_CONTEXT ) instanceof ChainedContext ) { + return (ChainedContext) request.getAttribute( "velocityContext" ); + } else { + RequestWrapper rw = new RequestWrapper( request ); + if ( request.getAttribute( "User-Agent" ) != null && request.getAttribute( "User-Agent" ).equals( Constants.USER_AGENT_DOTCMS_BROWSER ) ) { + rw.setCustomUserAgentHeader( Constants.USER_AGENT_DOTCMS_BROWSER ); + } + context = new ChainedContext( ctx, getEngine(), rw, response, Config.CONTEXT ); + } + + context.put("context", context); + Logger.debug(VelocityUtil.class, "ChainedContext=" + context); + /* + * if we have a toolbox manager, get a toolbox from it See + * /WEB-INF/toolbox.xml + */ + context.setToolbox(getToolboxManager().getToolboxContext(context)); + + + // put the list of languages on the page + context.put("languages", getLanguages()); + HttpSession session = request.getSession(false); + if(!UtilMethods.isSet(request.getAttribute(WebKeys.HTMLPAGE_LANGUAGE)) && session!=null) + context.put("language", (String) session.getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE)); + else + context.put("language", request.getAttribute(WebKeys.HTMLPAGE_LANGUAGE)); + + try { + Host host; + host = WebAPILocator.getHostWebAPI().getCurrentHost(request); + context.put("host", host); + } catch (Exception e) { + Logger.error(VelocityUtil.class,e.getMessage(),e); + } + context.put("pdfExport", false); + context.put("dotPageMode", PageMode.get(request)); + if(request.getSession(false)!=null){ + try { + User user = (com.liferay.portal.model.User) request.getSession().getAttribute(com.dotmarketing.util.WebKeys.CMS_USER); + context.put("user", user); + + Visitor visitor = (Visitor) request.getSession().getAttribute(WebKeys.VISITOR); + context.put("visitor", visitor); + + } catch (Exception nsue) { + Logger.error(VelocityUtil.class, nsue.getMessage(), nsue); + } + } + return context; + + } + + public static String mergeTemplate(String templatePath, Context ctx) throws ResourceNotFoundException, ParseErrorException, Exception{ + VelocityEngine ve = VelocityUtil.getEngine(); + Template template = null; + StringWriter sw = new StringWriter(); + template = ve.getTemplate(templatePath); + + template.merge(ctx, sw); + + return sw.toString(); + + } + + public static String eval(String velocity, Context ctx) throws ResourceNotFoundException, ParseErrorException, Exception{ + VelocityEngine ve = VelocityUtil.getEngine(); + StringWriter sw = new StringWriter(); + ve.evaluate(ctx, sw, "velocity eval", velocity); + return sw.toString(); + + } + private static ToolboxManager toolboxManager=null; + public static ToolboxManager getToolboxManager () { + if ( toolboxManager == null ) { + synchronized ( VelocityUtil.class ) { + if ( toolboxManager == null ) { + toolboxManager = ServletToolboxManager.getInstance( Config.CONTEXT, Config.getStringProperty("TOOLBOX_MANAGER_PATH", "/WEB-INF/toolbox.xml")); + } + } + + } + return toolboxManager; + } + + private static List languages =null; + + private static List getLanguages(){ + if(languages ==null){ + synchronized (VelocityUtil.class) { + if(languages ==null){ + languages = APILocator.getLanguageAPI().getLanguages(); + } + } + } + return languages; + + } + + + public static void makeBackendContext(Context context, IHTMLPage htmlPage, String cmsTemplateInode, String idURI, HttpServletRequest request, + PageMode mode, Host host) throws DotDataException { + + context.put("context", context); + + // stick some useful variables in the context + if (htmlPage != null) { + context.put("HTMLPAGE_INODE", String.valueOf(htmlPage.getInode())); + context.put("HTMLPAGE_IDENTIFIER", String.valueOf(htmlPage.getIdentifier())); + context.put("HTMLPAGE_TITLE", htmlPage.getTitle()); + context.put("HTMLPAGE_META", htmlPage.getMetadata()); + //http://jira.dotmarketing.net/browse/DOTCMS-6427 + context.put("HTMLPAGE_DESCRIPTION", htmlPage.getSeoDescription()); + context.put("HTMLPAGE_KEYWORDS", htmlPage.getSeoKeywords()); + context.put("HTMLPAGE_SECURE", String.valueOf(htmlPage.isHttpsRequired())); + context.put("HTMLPAGE_REDIRECT", htmlPage.getRedirect()); + context.put("friendlyName", htmlPage.getFriendlyName()); + context.put("pageTitle", htmlPage.getTitle()); + context.put("dotPageMode", mode); + Date moddate = htmlPage.getModDate(); + + moddate = new Date(moddate.getTime()); + + context.put("HTML_PAGE_LAST_MOD_DATE", moddate); + + try { + context.put("htmlPageInode", htmlPage.getInode()); + + // for browsing the tree + String view = java.net.URLEncoder.encode("(working=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + + " and deleted=" + com.dotmarketing.db.DbConnectionFactory.getDBFalse() + "and language_id = " + + (String) request.getSession().getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE) + ")", "UTF-8"); + context.put("view", view); + } catch (Exception e) { + Logger.warn(VelocityUtil.class, e.toString(), e); + } + } + + context.put("HTMLPAGE_SERVER_NAME", request.getServerName()); + context.put("VTLSERVLET_URI", UtilMethods.encodeURIComponent(idURI)); + if (request.getQueryString() != null && request.getQueryString().length() > 0) { + context.put("queryString", request.getQueryString()); + } else { + context.put("queryString", ""); + } + context.put("TEMPLATE_INODE", String.valueOf(cmsTemplateInode)); + + context.put("mainFrame", request.getParameter("mainFrame")); + context.put("previewFrame", request.getParameter("previewFrame")); + context.put(mode.name(), true); + if (mode == PageMode.EDIT_MODE) { + // gets user id from request for mod user + com.liferay.portal.model.User backendUser = null; + + try { + backendUser = com.liferay.portal.util.PortalUtil.getUser(request); + // Skin skin = backendUser.getSkin(); + // context.put("USER_SKIN", skin.getSkinId()); + } catch (Exception nsue) { + Logger.warn(VelocityUtil.class, "Exception trying yo getUser: " + nsue.getMessage(), nsue); + } + + // to check user has permission to publish this page + boolean permission = APILocator.getPermissionAPI().doesUserHavePermission(htmlPage, PERMISSION_PUBLISH, backendUser); + context.put("permission", new Boolean(permission)); + + // Check if the user is a CMS Administrator + boolean adminUser = false; + try { + + + String adminRoleKey = ""; + try { + Role adminRole = APILocator.getRoleAPI().loadRoleByKey(Config.getStringProperty("CMS_ADMINISTRATOR_ROLE", "CMS Administrator")); + adminRoleKey = adminRole.getRoleKey(); + } catch (Exception e) { + } + + Role[] userRoles = (Role[]) APILocator.getRoleAPI().loadRolesForUser(backendUser.getUserId()).toArray(new Role[0]); + for (int i = 0; i < userRoles.length; i++) { + Role userRole = (Role) userRoles[i]; + if (userRole.getRoleKey().equals(adminRoleKey)) { + adminUser = true; + } + } + } catch (Exception e) { + } + context.put("cmsAdminUser", new Boolean(adminUser)); + + } + + // gets pageChannel for this path + String pageChannel = UtilMethods.getPageChannel(idURI); + context.put("pageChannel", pageChannel); + context.put("PREVIEW_MODE", new Boolean(mode == PageMode.PREVIEW_MODE)); + context.put("EDIT_MODE", new Boolean(mode == PageMode.EDIT_MODE)); + context.put("ADMIN_MODE", new Boolean(mode.isAdmin)); + + // for publish button on admin control + // I HAVE TO FIX THIS!!!!! FOR THE NEW ONE + context.put("TEMPLATE_LIVE_CONTENT", new Boolean(false)); + context.put("CONTAINER_LIVE_CONTENT", new Boolean(false)); + context.put("CONTENTLET_LIVE_CONTENT", new Boolean(false)); + + + + + context.put("livePage", mode.showLive); + + context.put("language", (String) request.getSession().getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE)); + + if (mode.isAdmin) { + + // Making sure you are viewing the latest list of languages on any + // admin mode + languages = APILocator.getLanguageAPI().getLanguages(); + context.put("languages", languages); + + // gets user id from request for mod user + com.liferay.portal.model.User backendUser = null; + + try { + backendUser = com.liferay.portal.util.PortalUtil.getUser(request); + // Skin skin = backendUser.getSkin(); + // context.put("USER_SKIN", skin.getSkinId()); + context.put("backendUser", backendUser); + } catch (Exception nsue) { + Logger.warn(VelocityUtil.class, "Exception trying yo getUser: " + nsue.getMessage(), nsue); + } + + HttpSession session = request.getSession(); + context.put("directorURL", session.getAttribute(com.dotmarketing.util.WebKeys.DIRECTOR_URL)); + context.put("viewFoldersURL", session.getAttribute(com.dotmarketing.util.WebKeys.VIEW_FOLDERS_URL)); + context.put("previewPageURL", session.getAttribute(com.dotmarketing.util.WebKeys.PREVIEW_PAGE_URL)); + context.put("viewContentsURL", session.getAttribute(com.dotmarketing.util.WebKeys.VIEW_CONTENTS_URL)); + context.put("viewBrowserURL", session.getAttribute(com.dotmarketing.util.WebKeys.VIEW_BROWSER_URL)); + + + + } + + context.put("host", host); + + } + + + + + /** + * This method tries to build a cache key based on information given in the + * request. Post requests are ignored and will not be cached. + * + * @param request + * - The {@link HttpServletRequest} object. + * @return The page cache key if the page can be cached. If it can't be + * cached or caching is not available, returns null. + * @throws DotSecurityException + * @throws DotDataException + */ + public static String getPageCacheKey(HttpServletRequest request, HttpServletResponse response) throws DotDataException, DotSecurityException { + if (LicenseUtil.getLevel() <= LicenseLevel.COMMUNITY.level) { + return null; + } + // don't cache posts + if (!"GET".equalsIgnoreCase(request.getMethod())) { + return null; + } + // nocache passed either as a session var, as a request var or as a + // request attribute + if ("no".equals(request.getParameter("dotcache")) + || "no".equals(request.getAttribute("dotcache")) + || (request.getSession(false) !=null && "no".equals(request.getSession(true).getAttribute("dotcache")))) { + return null; + } + String idInode = (String) request.getAttribute("idInode"); + Identifier id; + + try { + id=APILocator.getIdentifierAPI().find(idInode); + } catch (DotDataException e1) { + Logger.warn(VelocityUtil.class, "can't load page identifier",e1); + return null; + } + + IHTMLPage page = getPage(id, request, false, null); + if (page == null || page.getCacheTTL() < 1) { + return null; + } + StringBuilder sb = new StringBuilder(); + sb.append(page.getInode()); + sb.append("_" + page.getModDate().getTime()); + return sb.toString(); + } + + public static long getLanguageId(HttpServletRequest request) { + return WebAPILocator.getLanguageWebAPI().getLanguage(request).getId(); + } + + /** + * Retrieves the list of languages a given Content Page ({@link Contentlet}) + * is available on. This is useful for keeping users from selecting a page + * language that has no associated content at the moment. + * + * @param contentlet + * - The Content Page. + * @return The {@link List} of languages the content page is available on. + */ + public static List getAvailableContentPageLanguages( + Contentlet contentlet) { + List languages = new ArrayList(); + List allDisplayLanguages = new ArrayList(); + + boolean doesContentHaveDefaultLang = false; + + for (Language language : APILocator.getLanguageAPI().getLanguages()) { + if (language.getId() != contentlet.getLanguageId()) { + try { + APILocator.getContentletAPI() + .findContentletByIdentifier( + contentlet.getIdentifier(), false, + language.getId(), + APILocator.getUserAPI().getSystemUser(), + false); + } catch (Exception e) { + Logger.debug( + VelocityUtil.class, + "The page is not available in language " + + language.getId() + ". Just keep going."); + + if(DEFAULT_PAGE_TO_DEFAULT_LANGUAGE) { + allDisplayLanguages.add(new DisplayedLanguage(language, true)); + } + + continue; + } + } + if(language.getId()==APILocator.getLanguageAPI().getDefaultLanguage().getId()) { + doesContentHaveDefaultLang = true; + } + + languages.add(new DisplayedLanguage(language, false)); + + if(DEFAULT_PAGE_TO_DEFAULT_LANGUAGE) { + allDisplayLanguages.add(new DisplayedLanguage(language, false)); + } + } + + if(DEFAULT_PAGE_TO_DEFAULT_LANGUAGE && doesContentHaveDefaultLang){ + return allDisplayLanguages; + } + + return languages; + } + + /** + * This returns the proper ihtml page based on id, state and language + * @param id + * @param request + * @param live + * @return + * @throws DotDataException + * @throws DotSecurityException + */ + public static IHTMLPage getPage(Identifier id, HttpServletRequest request, boolean live, Context context) throws DotDataException, DotSecurityException{ + + long langId = getLanguageId(request); + request.setAttribute("idInode", String.valueOf(id.getId())); + + IHTMLPage htmlPage; + + + Contentlet contentlet; + + try{ + contentlet = APILocator.getContentletAPI() + .findContentletByIdentifier(id.getId(), + live, + langId, + APILocator.getUserAPI().getSystemUser(), false); + htmlPage = APILocator.getHTMLPageAssetAPI().fromContentlet(contentlet); + + } catch(DotStateException dse){ + if(DEFAULT_PAGE_TO_DEFAULT_LANGUAGE && langId!= APILocator.getLanguageAPI().getDefaultLanguage().getId()){ + contentlet = APILocator.getContentletAPI() + .findContentletByIdentifier(id.getId(), + live, + APILocator.getLanguageAPI().getDefaultLanguage().getId(), + APILocator.getUserAPI().getSystemUser(), false); + htmlPage = APILocator.getHTMLPageAssetAPI().fromContentlet(contentlet); + } else{ + throw new DotDataException("Can't find content. Identifier: " + id.getId() + ", Live: " +live+ ", Lang: " + langId, dse); + } + + } + + if(UtilMethods.isSet(context)){ + context.put("availablePageLangs", getAvailableContentPageLanguages(contentlet)); + } + + + return htmlPage; + } + + /** + * Gets the Velocity Root Path. Looks for it on the Config, if not found the it get defaulted to /WEB-INF/velocity + * + * @return String + */ + public static String getVelocityRootPath() { + Logger.debug(VelocityUtil.class, "Fetching the velocity ROOT path..."); + + String velocityRootPath; + + velocityRootPath = Config.getStringProperty("VELOCITY_ROOT", "/WEB-INF/velocity"); + if (velocityRootPath.startsWith("/WEB-INF")) { + Logger.debug(VelocityUtil.class, "Velocity ROOT Path not found, defaulting it to '/WEB-INF/velocity'"); + String startPath = velocityRootPath.substring(0, 8); + String endPath = velocityRootPath.substring(9, velocityRootPath.length()); + velocityRootPath = com.liferay.util.FileUtil.getRealPath(startPath) + File.separator + endPath; + } + + Logger.debug(VelocityUtil.class, String.format("Velocity ROOT path found: %s", velocityRootPath)); + return velocityRootPath; + } + +} diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/BrowserAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/BrowserAPI.java similarity index 99% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/BrowserAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/BrowserAPI.java index ea7cc31edf81..e990ca78d4d5 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/BrowserAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/BrowserAPI.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import com.dotcms.contenttype.exception.NotFoundInDbException; import com.dotmarketing.beans.Host; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/CASTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CASTool.java similarity index 96% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/CASTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CASTool.java index 578a9bc14f0f..918cc47dde85 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/CASTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CASTool.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import java.util.ArrayList; import java.util.List; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/CMSUsersWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CMSUsersWebAPI.java similarity index 96% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/CMSUsersWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CMSUsersWebAPI.java index 538d702355af..c709e2098902 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/CMSUsersWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CMSUsersWebAPI.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import com.dotcms.repackage.com.google.common.collect.ImmutableList; import com.dotcms.util.SecurityUtils; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/CategoriesWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CategoriesWebAPI.java similarity index 97% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/CategoriesWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CategoriesWebAPI.java index 6cbb9c2cb9de..1b868f290bde 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/CategoriesWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CategoriesWebAPI.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import java.util.ArrayList; import java.util.HashMap; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/CommentsWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CommentsWebAPI.java similarity index 97% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/CommentsWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CommentsWebAPI.java index 9378c0f593e5..3818ded71ba5 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/CommentsWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CommentsWebAPI.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import java.util.ArrayList; import java.util.Comparator; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/ContainerWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/ContainerWebAPI.java similarity index 93% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/ContainerWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/ContainerWebAPI.java index a022b9ae6c67..ba692b1fe1cd 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/ContainerWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/ContainerWebAPI.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import java.util.List; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/ContentsWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/ContentsWebAPI.java similarity index 97% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/ContentsWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/ContentsWebAPI.java index b0db20e3e577..12f1d60de22e 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/ContentsWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/ContentsWebAPI.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import java.util.ArrayList; import java.util.Collections; @@ -545,25 +545,7 @@ public HashMap searchWithLuceneQuery(String structureType, String luceneConditio } - /** - * This methods retrieves the disk paths for a list of contents hits retrieved from lucene - * this method is used in the dynamic containers code to get the list of contents paths - * @param assets The assets hits - * @param working True if you want the working path to the content file, false if you the live path to the file - * @return A list of paths to the contents - */ - public List getContentsPathsFromLuceneHits(LuceneHits assets, boolean working) { - ArrayList paths = new ArrayList(); - for (int i = 0; i < assets.length(); i++) { - Logger.debug(this, "getContentsPathsFromLuceneHits: Adding asset path: " - + (working ? "/working/" : "/live/") + assets.doc(i).get("identifier") + "_" - + assets.doc(i).get("languageId") + "." + Config.getStringProperty("VELOCITY_CONTENT_EXTENSION")); - paths.add((working ? "/working/" : "/live/") + assets.doc(i).get("identifier") + "_" - + assets.doc(i).get("languageId") + "." + Config.getStringProperty("VELOCITY_CONTENT_EXTENSION")); - } - return paths; - } /** * This methods retrieves the identifier for a list of contents hits retrieved from lucene diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/CryptWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CryptWebAPI.java similarity index 90% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/CryptWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CryptWebAPI.java index d28fd0ff704c..93d1d9eaefea 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/CryptWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/CryptWebAPI.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import com.dotmarketing.cms.factories.PublicEncryptionFactory; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/DateViewWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DateViewWebAPI.java similarity index 89% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/DateViewWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DateViewWebAPI.java index 5be560bdcccd..1dc753b9c70f 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/DateViewWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DateViewWebAPI.java @@ -1,7 +1,4 @@ -/** - * com.dotmarketing.viewtools - */ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import java.util.Date; import java.util.GregorianCalendar; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/DotCMSDocumentationAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotCMSDocumentationAPI.java similarity index 87% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/DotCMSDocumentationAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotCMSDocumentationAPI.java index 6e9b85f9d89c..8ecdfe1ac043 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/DotCMSDocumentationAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotCMSDocumentationAPI.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import java.util.ArrayList; import java.util.List; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/DotCMSMacroWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotCMSMacroWebAPI.java similarity index 99% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/DotCMSMacroWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotCMSMacroWebAPI.java index 5f97b26bce47..1dd957c2ded5 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/DotCMSMacroWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotCMSMacroWebAPI.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Date; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/DotLoggerTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotLoggerTool.java similarity index 97% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/DotLoggerTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotLoggerTool.java index bbe6c821305d..c0b09fa0628d 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/DotLoggerTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotLoggerTool.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import com.dotcms.repackage.org.apache.logging.log4j.LogManager; import com.dotcms.repackage.org.apache.logging.log4j.Logger; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/DotRenderTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotRenderTool.java similarity index 79% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/DotRenderTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotRenderTool.java index 9eedfc27fefb..0925a142d06d 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/DotRenderTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotRenderTool.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import org.apache.velocity.tools.view.tools.ViewRenderTool; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/DotTemplateTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotTemplateTool.java similarity index 97% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/DotTemplateTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotTemplateTool.java index 545a4d387c1e..d18a8b849bb1 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/DotTemplateTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/DotTemplateTool.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import java.io.IOException; import java.util.HashMap; @@ -19,7 +19,7 @@ import com.dotmarketing.business.APILocator; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotSecurityException; -import com.dotmarketing.factories.InodeFactory; + import com.dotmarketing.portlets.fileassets.business.FileAsset; import com.dotmarketing.portlets.folders.model.Folder; import com.dotmarketing.portlets.templates.design.bean.TemplateLayout; @@ -101,9 +101,6 @@ public static TemplateLayout themeLayout ( final String themeInode, final Boolea Template template = APILocator.getTemplateAPI().findWorkingTemplate(ident.getId(), sysUser, false); - if (!template.getInode().equals(themeInode)) { - template = (Template) InodeFactory.getInode(themeInode, Template.class); - } drawedBody = template.getDrawedBody(); title = template.getTitle(); diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/ESContentTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/ESContentTool.java similarity index 66% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/ESContentTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/ESContentTool.java index 4a3138d6c9bd..88b332671ef3 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/ESContentTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/ESContentTool.java @@ -1,5 +1,18 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; +import com.dotcms.content.elasticsearch.business.ESSearchResults; + +import com.dotmarketing.beans.Host; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.web.UserWebAPI; +import com.dotmarketing.business.web.WebAPILocator; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.portlets.contentlet.business.ContentletAPI; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; +import com.dotcms.rendering.velocity.viewtools.content.ContentMap; import java.util.ArrayList; import java.util.List; @@ -10,19 +23,8 @@ import org.apache.velocity.context.Context; import org.apache.velocity.tools.view.context.ViewContext; import org.apache.velocity.tools.view.tools.ViewTool; - -import com.dotcms.content.elasticsearch.business.ESSearchResults; import org.elasticsearch.action.search.SearchResponse; -import com.dotmarketing.beans.Host; -import com.dotmarketing.business.APILocator; -import com.dotmarketing.business.web.UserWebAPI; -import com.dotmarketing.business.web.WebAPILocator; -import com.dotmarketing.exception.DotDataException; -import com.dotmarketing.exception.DotSecurityException; -import com.dotmarketing.portlets.contentlet.business.ContentletAPI; -import com.dotmarketing.portlets.contentlet.model.Contentlet; -import com.dotmarketing.util.Logger; -import com.dotmarketing.viewtools.content.ContentMap; + import com.liferay.portal.model.User; public class ESContentTool implements ViewTool { @@ -30,44 +32,27 @@ public class ESContentTool implements ViewTool { private HttpServletRequest req; private User user = null; - private boolean ADMIN_MODE; - private boolean PREVIEW_MODE; - private boolean EDIT_MODE; - private boolean LIVE; - private String tmDate; private Context context; ContentletAPI esapi = APILocator.getContentletAPI(); private Host currentHost; - + private PageMode mode; @Override public void init(Object initData) { userAPI = WebAPILocator.getUserWebAPI(); - LIVE = true; + this.context = ((ViewContext) initData).getVelocityContext(); this.req = ((ViewContext) initData).getRequest(); - tmDate=null; - ADMIN_MODE=false; - PREVIEW_MODE=false; - EDIT_MODE=false; - HttpSession session = req.getSession(false); + + mode = PageMode.get(this.req); try { user = userAPI.getLoggedInFrontendUser(req); } catch (Exception e) { Logger.error(this, "Error finding the logged in user", e); } - if(session!=null){ - tmDate = (String) session.getAttribute("tm_date"); - boolean tm=tmDate!=null; - ADMIN_MODE = !tm && (session.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null); - PREVIEW_MODE = !tm && ((session.getAttribute(com.dotmarketing.util.WebKeys.PREVIEW_MODE_SESSION) != null) && ADMIN_MODE); - EDIT_MODE = !tm && ((session.getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) != null) && ADMIN_MODE); - if(EDIT_MODE || PREVIEW_MODE){ - LIVE = false; - } - } + try{ this.currentHost = WebAPILocator.getHostWebAPI().getCurrentHost(req); }catch(Exception e){ @@ -79,15 +64,15 @@ public void init(Object initData) { public ESSearchResults search(String esQuery) throws DotSecurityException, DotDataException{ - - ESSearchResults cons = esapi.esSearch(esQuery, LIVE, user, true); + + ESSearchResults cons = esapi.esSearch(esQuery, mode.showLive, user, true); List maps = new ArrayList(); for(Object x : cons){ Contentlet con = (Contentlet)x; - maps.add(new ContentMap(con, user, !LIVE,currentHost,context)); + maps.add(new ContentMap(con, user, !mode.showLive,currentHost,context)); } return new ESSearchResults(cons.getResponse(), maps); @@ -96,7 +81,7 @@ public ESSearchResults search(String esQuery) throws DotSecurityException, DotDa public SearchResponse raw(String esQuery) throws DotSecurityException, DotDataException{ - return esapi.esSearchRaw(esQuery, LIVE, user, true); + return esapi.esSearchRaw(esQuery, mode.showLive, user, true); } diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/FileTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/FileTool.java similarity index 97% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/FileTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/FileTool.java index defc40801bf2..a39ef11e42e0 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/FileTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/FileTool.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import com.dotmarketing.beans.Identifier; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.DotStateException; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/FolderWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/FolderWebAPI.java similarity index 95% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/FolderWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/FolderWebAPI.java index a207d5e47804..9e8c45b6ee49 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/FolderWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/FolderWebAPI.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import java.util.List; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/GlobalVariableWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/GlobalVariableWebAPI.java similarity index 97% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/GlobalVariableWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/GlobalVariableWebAPI.java index 76a4ad7731b2..7290980b69e9 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/GlobalVariableWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/GlobalVariableWebAPI.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import javax.servlet.http.HttpServletRequest; import org.apache.velocity.tools.view.context.ViewContext; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/GlossaryWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/GlossaryWebAPI.java similarity index 99% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/GlossaryWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/GlossaryWebAPI.java index 1d9d80205a00..2167100e31fa 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/GlossaryWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/GlossaryWebAPI.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.util.List; import javax.servlet.http.HttpServletRequest; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/JSONTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/JSONTool.java similarity index 99% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/JSONTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/JSONTool.java index 7481ad6b5477..5469dba531f3 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/JSONTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/JSONTool.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.util.HashMap; import java.util.List; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/LangBackendWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/LangBackendWebAPI.java similarity index 91% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/LangBackendWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/LangBackendWebAPI.java index a382c0220994..d09218638ac7 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/LangBackendWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/LangBackendWebAPI.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import javax.servlet.http.HttpServletRequest; import org.apache.velocity.context.Context; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/LanguageWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/LanguageWebAPI.java similarity index 96% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/LanguageWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/LanguageWebAPI.java index 4397d73c4d93..007cfef90bad 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/LanguageWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/LanguageWebAPI.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import static com.dotcms.contenttype.model.type.KeyValueContentType.MULTILINGUABLE_FALLBACK_KEY; import com.dotmarketing.business.APILocator; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/MailerTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/MailerTool.java similarity index 98% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/MailerTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/MailerTool.java index 81e3cec32fb2..4d816a29dd60 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/MailerTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/MailerTool.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.util.Date; import javax.mail.Message; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/MarkdownTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/MarkdownTool.java similarity index 93% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/MarkdownTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/MarkdownTool.java index 90372a590127..3a3f3239f1b9 100755 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/MarkdownTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/MarkdownTool.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.io.StringWriter; import javax.servlet.http.HttpServletRequest; @@ -17,6 +16,7 @@ import com.dotmarketing.business.web.WebAPILocator; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.fileassets.business.FileAsset; +import com.dotmarketing.util.PageMode; import com.dotmarketing.util.VelocityUtil; import com.github.rjeschke.txtmark.Configuration; import com.github.rjeschke.txtmark.Processor; @@ -75,11 +75,8 @@ public String parseFile(String path, boolean parseFirst) throws Throwable { } private String getFileContents(String path, boolean parseFirst) throws Throwable { - boolean EDIT_MODE = false; - if (request != null) { - EDIT_MODE = (request.getSession().getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) != null) - && request.getSession().getAttribute("tm_date") == null; - } + boolean EDIT_MODE = PageMode.get(request) == PageMode.EDIT_MODE; + String templatePath = path; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/MessagesTools.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/MessagesTools.java similarity index 86% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/MessagesTools.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/MessagesTools.java index 9c3ce9ef8adc..cca6721f8a11 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/MessagesTools.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/MessagesTools.java @@ -1,21 +1,4 @@ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.util.List; import java.util.Locale; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/PersonaTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/PersonaTool.java similarity index 94% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/PersonaTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/PersonaTool.java index 278bc70e8b48..e95cbb1f4ace 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/PersonaTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/PersonaTool.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.util.List; import java.util.Optional; @@ -19,6 +18,7 @@ import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.personas.model.Persona; import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; import com.liferay.portal.PortalException; @@ -41,8 +41,7 @@ public void init(Object obj) { if (session != null) { timemachine = session.getAttribute("tm_date") != null; - ADMIN_MODE = !timemachine && session != null - && (session.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null); + boolean ADMIN_MODE = PageMode.get(request) .isAdmin; try { user = WebAPILocator.getUserWebAPI().getLoggedInUser(request); } catch (DotRuntimeException | PortalException | SystemException e) { diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/PluginWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/PluginWebAPI.java similarity index 97% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/PluginWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/PluginWebAPI.java index 833bff78d1cb..7db08fb2e612 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/PluginWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/PluginWebAPI.java @@ -1,8 +1,4 @@ -/** - * - */ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.util.List; import org.apache.velocity.tools.view.tools.ViewTool; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/RequestWrapper.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/RequestWrapper.java similarity index 99% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/RequestWrapper.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/RequestWrapper.java index 4f61e95bdcb6..9213661bd6d9 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/RequestWrapper.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/RequestWrapper.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/SQLResultsViewTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/SQLResultsViewTool.java similarity index 99% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/SQLResultsViewTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/SQLResultsViewTool.java index d7293bd85d26..3b58e66b1994 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/SQLResultsViewTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/SQLResultsViewTool.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.util.ArrayList; import java.util.HashMap; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/StringsWebApi.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/StringsWebApi.java similarity index 94% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/StringsWebApi.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/StringsWebApi.java index da4d21808bb3..5c1a50fa6464 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/StringsWebApi.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/StringsWebApi.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.io.StringWriter; import org.apache.velocity.tools.view.tools.ViewTool; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/StructuresWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/StructuresWebAPI.java similarity index 99% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/StructuresWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/StructuresWebAPI.java index c7e77cedde6f..58d684cac91e 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/StructuresWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/StructuresWebAPI.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.util.ArrayList; import java.util.List; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/SubmitContentWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/SubmitContentWebAPI.java similarity index 98% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/SubmitContentWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/SubmitContentWebAPI.java index c75e8dd29b8f..7c7191af376c 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/SubmitContentWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/SubmitContentWebAPI.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.util.ArrayList; import java.util.List; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/TagsWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/TagsWebAPI.java similarity index 94% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/TagsWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/TagsWebAPI.java index 6fb261f5109c..1ff268503393 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/TagsWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/TagsWebAPI.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import com.dotcms.visitor.domain.Visitor; import com.dotmarketing.beans.UserProxy; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/UserAgentTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/UserAgentTool.java similarity index 97% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/UserAgentTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/UserAgentTool.java index fe2fecc436c9..0566ebadac42 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/UserAgentTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/UserAgentTool.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import javax.servlet.http.HttpServletRequest; import org.apache.velocity.tools.view.context.ViewContext; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/UserCommentsWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/UserCommentsWebAPI.java similarity index 92% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/UserCommentsWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/UserCommentsWebAPI.java index 1da62250364e..9fd979225ee1 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/UserCommentsWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/UserCommentsWebAPI.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; /** * This is the webAPI thatr let the developer call the UserCommentsFactory from the velocity pages * @author Salvador Di Nardo diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/VelocityWebUtil.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/VelocityWebUtil.java new file mode 100644 index 000000000000..6433d4fd473f --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/VelocityWebUtil.java @@ -0,0 +1,151 @@ +package com.dotcms.rendering.velocity.viewtools; + +import com.dotmarketing.util.*; + +import org.apache.velocity.Template; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.context.Context; +import org.apache.velocity.exception.ParseErrorException; +import org.apache.velocity.exception.ResourceNotFoundException; +import org.apache.velocity.tools.view.context.ViewContext; +import org.apache.velocity.tools.view.tools.ViewTool; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.StringWriter; + +/** + * @author Jason Tesser + * @since 1.6.5 + * + */ +public class VelocityWebUtil implements ViewTool { + + static final String _logVariable = "LOG_VELOCITY_TEMPLATES"; + private Context ctx; + private HttpServletRequest req; + boolean debug = false; + + // private HttpServletRequest request; + public void init(Object obj) { + ViewContext context = (ViewContext) obj; + this.req = context.getRequest(); + this.ctx = context.getVelocityContext(); + this.debug = Config.getBooleanProperty(_logVariable, false); + + if (!this.debug) { + try { + if (ctx.get("request") != null) { + if (((HttpServletRequest) ctx.get("request")).getParameter(_logVariable) != null + || (req.getSession(false) != null && req.getSession(false) + .getAttribute(_logVariable) != null)) { + this.debug = true; + + + if ("false".equals(req.getParameter(_logVariable))) { + this.debug = true; + req.getSession() + .removeAttribute(_logVariable); + } else { + req.getSession() + .setAttribute(_logVariable, "true"); + } + + + + } + } + } catch (Exception e) { + Logger.debug(VelocityWebUtil.class, e.getMessage(), e); + } + } + + } + + public String mergeTemplate(String templatePath) throws ResourceNotFoundException, ParseErrorException, Exception { + + VelocityEngine ve = VelocityUtil.getEngine(); + Template template = null; + StringWriter sw = new StringWriter(); + String threadName = Thread.currentThread() + .getName(); + if (this.debug) { + Logger.info(VelocityWebUtil.class, _logVariable + ": " + templatePath); + } + try { + String newThreadName = (threadName.contains("{")) ? threadName.replaceAll("\\{[^\\}]*\\}", "{" + templatePath + "}") + : threadName + " {" + templatePath + "}"; + Thread.currentThread() + .setName(newThreadName); + template = ve.getTemplate(templatePath); + + template.merge(ctx, sw); + return sw.toString(); + } catch (ParseErrorException e) { + if (null != ctx) { + + /* + * In Edit mode we are allow to fail and be noisy, but on Preview and Live mode we + * just want to continue with the render of the page. + */ + PageMode mode = (PageMode) ctx.get(WebKeys.PAGE_MODE_SESSION); + + if (null == mode || mode != PageMode.EDIT_MODE) { + Logger.error(this.getClass(), "Error parsing elements", e); + return sw.toString(); + } + } + + throw e; + } finally { + Thread.currentThread() + .setName(threadName); + } + + + } + + + public void mergeTemplate(String templatePath, HttpServletResponse response) + throws ResourceNotFoundException, ParseErrorException, Exception { + VelocityEngine ve = VelocityUtil.getEngine(); + Template template = null; + String threadName = Thread.currentThread() + .getName(); + try { + Thread.currentThread() + .setName(threadName + " >" + templatePath); + if (this.debug) { + Logger.info(VelocityWebUtil.class, _logVariable + ": " + templatePath); + } + + template = ve.getTemplate(templatePath); + template.merge(ctx, response.getWriter()); + } finally { + Thread.currentThread() + .setName(threadName); + } + } + + + + public boolean doesVelocityResourceExist(String templatePath) { + VelocityEngine ve = VelocityUtil.getEngine(); + try { + ve.getTemplate(templatePath); + } catch (ResourceNotFoundException e) { + return false; + } catch (Exception e) { + Logger.debug(VelocityWebUtil.class, e.getMessage(), e); + } + return true; + } + + public boolean isVelocityFile(String path) { + if (!UtilMethods.isSet(path)) { + return false; + } + path = path.toLowerCase(); + return (path.endsWith(".vtl") || path.endsWith(".vm") || path.endsWith(".html") || path.endsWith(".htm")); + } +} diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/WebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/WebAPI.java similarity index 95% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/WebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/WebAPI.java index 34cd733cb30b..18804a681f31 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/WebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/WebAPI.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.io.IOException; import java.io.StringWriter; import java.text.SimpleDateFormat; @@ -47,6 +46,7 @@ import com.dotmarketing.util.CookieUtil; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; import com.dotmarketing.util.UtilHTML; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.VelocityUtil; @@ -95,14 +95,11 @@ public void init(Object obj) { - - HttpSession session = request.getSession(false); + PageMode mode = PageMode.get(request); + ADMIN_MODE = mode.isAdmin; + PREVIEW_MODE = mode==PageMode.PREVIEW_MODE; + EDIT_MODE = mode==PageMode.EDIT_MODE; - if(session!=null){ - ADMIN_MODE = (session.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null); - PREVIEW_MODE = ((session.getAttribute(com.dotmarketing.util.WebKeys.PREVIEW_MODE_SESSION) != null) && ADMIN_MODE); - EDIT_MODE = ((session.getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) != null) && ADMIN_MODE); - } } // Utility Methods @@ -439,9 +436,6 @@ public String getAssetInode(String path, Host host){ } HttpSession session = request.getSession(); - boolean ADMIN_MODE = (session.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null); - boolean PREVIEW_MODE = ((session.getAttribute(com.dotmarketing.util.WebKeys.PREVIEW_MODE_SESSION) != null) && ADMIN_MODE); - boolean EDIT_MODE = ((session.getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) != null) && ADMIN_MODE); Identifier id = APILocator.getIdentifierAPI().find(host, path); if(id!=null && InodeUtils.isSet(id.getId()) && id.getAssetType().equals("contentlet")){ @@ -840,9 +834,6 @@ public boolean doesUserHasPermissionOverFile (long fileInode, int permission) th } public boolean doesUserHasPermissionOverFile (String fileInode, int permission) throws DotDataException { - HttpSession session = request.getSession(); - boolean ADMIN_MODE = (session.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null); - boolean EDIT_MODE = ((session.getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) != null) && ADMIN_MODE); Permissionable fileAsset = null; Identifier ident = getIdentifierByInode(fileInode); diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/WebsiteWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/WebsiteWebAPI.java similarity index 98% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/WebsiteWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/WebsiteWebAPI.java index 80d6264d003b..5618f049b43e 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/WebsiteWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/WebsiteWebAPI.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import java.util.ArrayList; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/WikiTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/WikiTool.java similarity index 99% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/WikiTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/WikiTool.java index f7cf7bec2ac7..ee4476ce2c1c 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/WikiTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/WikiTool.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools; - +package com.dotcms.rendering.velocity.viewtools; import java.io.StringWriter; import org.apache.velocity.tools.view.tools.ViewTool; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/WorkflowTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/WorkflowTool.java similarity index 99% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/WorkflowTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/WorkflowTool.java index 2f7f56821e20..b07fe0fdfa35 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/WorkflowTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/WorkflowTool.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import com.dotmarketing.business.Permissionable; import java.util.List; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/XmlTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/XmlTool.java similarity index 94% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/XmlTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/XmlTool.java index e221d2c235c0..9c39b7db3c7e 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/XmlTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/XmlTool.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -30,6 +30,10 @@ import org.apache.velocity.tools.generic.ValueParser; import org.apache.velocity.tools.view.tools.ViewTool; + +import com.dotcms.rendering.velocity.viewtools.bean.XmlToolDoc; +import com.dotcms.rendering.velocity.viewtools.cache.XmlToolCache; +import com.dotcms.rendering.velocity.viewtools.util.ConversionUtils; import com.dotcms.repackage.org.dom4j.Attribute; import com.dotcms.repackage.org.dom4j.Document; import com.dotcms.repackage.org.dom4j.DocumentHelper; @@ -38,9 +42,7 @@ import com.dotcms.repackage.org.dom4j.io.SAXReader; import com.dotmarketing.util.Logger; -import com.dotmarketing.viewtools.cache.XmlToolCache; -import com.dotmarketing.viewtools.util.ConversionUtils; -import com.dotmarketing.viewtools.bean.XmlToolDoc; + /** *

diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/XsltTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/XsltTool.java similarity index 97% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/XsltTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/XsltTool.java index 21c121cd6e3e..d7e8f8f0dc33 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/XsltTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/XsltTool.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import com.dotcms.repackage.javax.xml.transform.Source; import com.dotcms.repackage.javax.xml.transform.Transformer; @@ -21,8 +21,8 @@ import com.dotmarketing.util.Config; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; -import com.dotmarketing.viewtools.bean.XSLTranformationDoc; -import com.dotmarketing.viewtools.cache.XSLTransformationCache; +import com.dotcms.rendering.velocity.viewtools.bean.XSLTranformationDoc; +import com.dotcms.rendering.velocity.viewtools.cache.XSLTransformationCache; import com.liferay.portal.PortalException; import com.liferay.portal.SystemException; import com.liferay.portal.model.User; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/XssWebAPI.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/XssWebAPI.java similarity index 96% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/XssWebAPI.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/XssWebAPI.java index 5b18e8ccd053..cc3821557ac9 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/XssWebAPI.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/XssWebAPI.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools; +package com.dotcms.rendering.velocity.viewtools; import org.apache.velocity.tools.view.tools.ViewTool; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/bean/XSLTranformationDoc.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/bean/XSLTranformationDoc.java similarity index 92% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/bean/XSLTranformationDoc.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/bean/XSLTranformationDoc.java index b7ee4f841b9b..cdbc836d5934 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/bean/XSLTranformationDoc.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/bean/XSLTranformationDoc.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools.bean; +package com.dotcms.rendering.velocity.viewtools.bean; /** * Object that manipulate XML with XSL transformation diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/bean/XmlToolDoc.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/bean/XmlToolDoc.java similarity index 85% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/bean/XmlToolDoc.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/bean/XmlToolDoc.java index 6d06be765122..73d41b1575a3 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/bean/XmlToolDoc.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/bean/XmlToolDoc.java @@ -1,8 +1,6 @@ -package com.dotmarketing.viewtools.bean; - -import com.dotmarketing.viewtools.XmlTool; - +package com.dotcms.rendering.velocity.viewtools.bean; +import com.dotcms.rendering.velocity.viewtools.XmlTool; /** * Object that manipulate XmlTool in the Cache diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/cache/XSLTransformationCache.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/cache/XSLTransformationCache.java similarity index 93% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/cache/XSLTransformationCache.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/cache/XSLTransformationCache.java index 86af410751e2..49f775072b8f 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/cache/XSLTransformationCache.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/cache/XSLTransformationCache.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools.cache; +package com.dotcms.rendering.velocity.viewtools.cache; import java.util.Date; @@ -11,7 +11,7 @@ import com.dotmarketing.business.VersionableAPI; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.util.Logger; -import com.dotmarketing.viewtools.bean.XSLTranformationDoc; +import com.dotcms.rendering.velocity.viewtools.bean.XSLTranformationDoc; /** * This class manage the XSLTransformation plugin cache diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/cache/XmlToolCache.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/cache/XmlToolCache.java similarity index 92% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/cache/XmlToolCache.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/cache/XmlToolCache.java index 119256313b11..1835b0d2727c 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/cache/XmlToolCache.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/cache/XmlToolCache.java @@ -1,7 +1,7 @@ -package com.dotmarketing.viewtools.cache; - +package com.dotcms.rendering.velocity.viewtools.cache; import java.util.Date; +import com.dotcms.rendering.velocity.viewtools.bean.XmlToolDoc; import com.dotcms.repackage.org.bouncycastle.crypto.digests.SHA1Digest; import com.dotcms.repackage.org.bouncycastle.util.encoders.Base64; @@ -9,7 +9,6 @@ import com.dotmarketing.business.DotCacheAdministrator; import com.dotmarketing.business.DotCacheException; import com.dotmarketing.util.Logger; -import com.dotmarketing.viewtools.bean.XmlToolDoc; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/BinaryMap.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/BinaryMap.java similarity index 99% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/content/BinaryMap.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/BinaryMap.java index c8ca64b056c9..5ff9df98e233 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/BinaryMap.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/BinaryMap.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools.content; +package com.dotcms.rendering.velocity.viewtools.content; import com.dotcms.repackage.org.apache.commons.lang.builder.ToStringBuilder; import com.dotmarketing.business.APILocator; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/CheckboxMap.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/CheckboxMap.java similarity index 96% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/content/CheckboxMap.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/CheckboxMap.java index df7fc8b3abee..66220b2e90df 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/CheckboxMap.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/CheckboxMap.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools.content; +package com.dotcms.rendering.velocity.viewtools.content; import java.util.ArrayList; import java.util.List; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/ContentMap.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/ContentMap.java similarity index 94% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/content/ContentMap.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/ContentMap.java index e832e342597c..6d7d8882da53 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/ContentMap.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/ContentMap.java @@ -1,8 +1,9 @@ /** * */ -package com.dotmarketing.viewtools.content; +package com.dotcms.rendering.velocity.viewtools.content; +import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.*; @@ -13,6 +14,8 @@ import org.apache.velocity.context.Context; import com.dotcms.contenttype.model.type.BaseContentType; +import com.dotcms.rendering.velocity.services.VelocityType; +import com.dotcms.rendering.velocity.util.VelocityUtil; import com.dotcms.repackage.org.apache.commons.lang.builder.ToStringBuilder; import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; @@ -30,9 +33,9 @@ import com.dotmarketing.util.Config; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; import com.dotmarketing.util.UtilMethods; -import com.dotmarketing.util.VelocityUtil; -import com.dotmarketing.viewtools.ContentsWebAPI; +import com.dotcms.rendering.velocity.viewtools.ContentsWebAPI; import com.liferay.portal.model.User; /** @@ -61,16 +64,18 @@ public class ContentMap { private Structure structure; private String title; private Context context; - + public ContentMap(Contentlet content, User user, PageMode mode, Host host, Context context) { + this( content, user, !mode.showLive, host, context) ; + } public ContentMap(Contentlet content, User user, boolean EDIT_OR_PREVIEW_MODE, Host host, Context context) { - this.content = content; - this.conAPI = APILocator.getContentletAPI(); - this.perAPI = APILocator.getPermissionAPI(); - this.fields = FieldsCache.getFieldsByStructureInode(content.getStructureInode()); - this.user = user; - this.EDIT_OR_PREVIEW_MODE = EDIT_OR_PREVIEW_MODE; - this.host = host; - this.context = context; + this.content = content; + this.conAPI = APILocator.getContentletAPI(); + this.perAPI = APILocator.getPermissionAPI(); + this.fields = FieldsCache.getFieldsByStructureInode(content.getStructureInode()); + this.user = user; + this.EDIT_OR_PREVIEW_MODE = EDIT_OR_PREVIEW_MODE; + this.host = host; + this.context = context; } /** @@ -286,7 +291,7 @@ public String toString() { Template template = null; StringWriter sw = new StringWriter(); - template = ve.getTemplate((EDIT_OR_PREVIEW_MODE ? "working/":"live/") + content.getInode() + "_" + f.getInode() + "." + Config.getStringProperty("VELOCITY_FIELD_EXTENSION")); + template = ve.getTemplate((EDIT_OR_PREVIEW_MODE ? PageMode.PREVIEW_MODE.name():PageMode.LIVE.name()) + File.separator + content.getInode() + File.separator + f.getInode() + "." + VelocityType.FIELD.fileExtension); template.merge(context, sw); ret = sw.toString(); } diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/ContentTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/ContentTool.java similarity index 96% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/content/ContentTool.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/ContentTool.java index 81a44723778f..94f03ed590e0 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/ContentTool.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/ContentTool.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools.content; +package com.dotcms.rendering.velocity.viewtools.content; import java.io.StringWriter; import java.util.ArrayList; @@ -27,10 +27,11 @@ import com.dotmarketing.util.Config; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; import com.dotmarketing.util.PaginatedArrayList; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; -import com.dotmarketing.viewtools.content.util.ContentUtils; +import com.dotcms.rendering.velocity.viewtools.content.util.ContentUtils; import com.liferay.portal.model.User; /** @@ -51,10 +52,8 @@ public class ContentTool implements ViewTool { private HttpServletRequest req; private User user = null; - private boolean ADMIN_MODE; - private boolean PREVIEW_MODE; - private boolean EDIT_MODE; - private boolean EDIT_OR_PREVIEW_MODE; + + private boolean EDIT_OR_PREVIEW_MODE=false; private String tmDate; private Context context; private Host currentHost; @@ -76,21 +75,14 @@ public void init(Object initData) { } tmDate=null; - ADMIN_MODE=false; - PREVIEW_MODE=false; - EDIT_MODE=false; + HttpSession session = req.getSession(false); - - + PageMode mode = PageMode.get(req); + EDIT_OR_PREVIEW_MODE=!mode.showLive; if(session!=null){ tmDate = (String) session.getAttribute("tm_date"); boolean tm=tmDate!=null; - ADMIN_MODE = !tm && (session.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null || req.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null); - PREVIEW_MODE = !tm && ((session.getAttribute(com.dotmarketing.util.WebKeys.PREVIEW_MODE_SESSION) != null || req.getAttribute(com.dotmarketing.util.WebKeys.PREVIEW_MODE_SESSION) != null) && ADMIN_MODE); - EDIT_MODE = !tm && ((session.getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) != null || req.getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) != null) && ADMIN_MODE); - if(EDIT_MODE || PREVIEW_MODE){ - EDIT_OR_PREVIEW_MODE = true; - } + } try{ this.currentHost = WebAPILocator.getHostWebAPI().getCurrentHost(req); diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/FileAssetMap.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/FileAssetMap.java similarity index 97% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/content/FileAssetMap.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/FileAssetMap.java index fe97d4a0438e..419f373373dc 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/FileAssetMap.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/FileAssetMap.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools.content; - +package com.dotcms.rendering.velocity.viewtools.content; import com.dotcms.repackage.org.apache.commons.beanutils.BeanUtils; import com.dotcms.repackage.org.apache.commons.lang.builder.ToStringBuilder; import com.dotmarketing.business.APILocator; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/MultiSelectMap.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/MultiSelectMap.java similarity index 96% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/content/MultiSelectMap.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/MultiSelectMap.java index 4b0865375286..c6c4c7d92e32 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/MultiSelectMap.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/MultiSelectMap.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools.content; +package com.dotcms.rendering.velocity.viewtools.content; import java.util.ArrayList; import java.util.List; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/PaginatedContentList.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/PaginatedContentList.java similarity index 95% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/content/PaginatedContentList.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/PaginatedContentList.java index 220e1608b73e..06829a7b56aa 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/PaginatedContentList.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/PaginatedContentList.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools.content; - +package com.dotcms.rendering.velocity.viewtools.content; import com.dotcms.repackage.org.apache.commons.lang.builder.ToStringBuilder; import com.dotmarketing.util.PaginatedArrayList; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/RadioMap.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/RadioMap.java similarity index 96% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/content/RadioMap.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/RadioMap.java index 1f55b6e5f873..b405079161f4 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/RadioMap.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/RadioMap.java @@ -1,5 +1,4 @@ -package com.dotmarketing.viewtools.content; - +package com.dotcms.rendering.velocity.viewtools.content; import java.util.ArrayList; import java.util.List; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/SelectMap.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/SelectMap.java similarity index 96% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/content/SelectMap.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/SelectMap.java index c5f5f5ddec33..7823b364cf00 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/SelectMap.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/SelectMap.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools.content; +package com.dotcms.rendering.velocity.viewtools.content; import java.util.ArrayList; import java.util.List; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/TagList.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/TagList.java similarity index 94% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/content/TagList.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/TagList.java index b609716517d3..c5c201f501b8 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/TagList.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/TagList.java @@ -1,7 +1,7 @@ /** * */ -package com.dotmarketing.viewtools.content; +package com.dotcms.rendering.velocity.viewtools.content; import java.util.ArrayList; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/util/ContentUtils.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/util/ContentUtils.java similarity index 99% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/content/util/ContentUtils.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/util/ContentUtils.java index c371501dfe34..c73a93934eb1 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/content/util/ContentUtils.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/content/util/ContentUtils.java @@ -1,6 +1,8 @@ -package com.dotmarketing.viewtools.content.util; +package com.dotcms.rendering.velocity.viewtools.content.util; import com.dotcms.content.elasticsearch.business.ESMappingAPIImpl; +import com.dotcms.rendering.velocity.viewtools.content.PaginatedContentList; + import com.dotmarketing.beans.Identifier; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.FactoryLocator; @@ -15,7 +17,7 @@ import com.dotmarketing.util.Logger; import com.dotmarketing.util.PaginatedArrayList; import com.dotmarketing.util.UtilMethods; -import com.dotmarketing.viewtools.content.PaginatedContentList; + import com.liferay.portal.model.User; import java.util.ArrayList; diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavResult.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavResult.java new file mode 100644 index 000000000000..cffdb9e0f6a3 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavResult.java @@ -0,0 +1,374 @@ +package com.dotcms.rendering.velocity.viewtools.navigation; + +import com.dotcms.rendering.velocity.util.VelocityUtil; + +import com.dotmarketing.beans.Host; +import com.dotmarketing.beans.Identifier; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.PermissionAPI; +import com.dotmarketing.business.PermissionSummary; +import com.dotmarketing.business.Permissionable; +import com.dotmarketing.business.RelatedPermissionableGroup; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.portlets.folders.business.FolderAPI; +import com.dotmarketing.portlets.folders.model.Folder; +import com.dotmarketing.portlets.htmlpageasset.model.IHTMLPage; +import com.dotmarketing.portlets.links.model.Link; +import com.dotmarketing.util.Logger; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import org.apache.velocity.tools.view.tools.ViewRenderTool; + +import com.liferay.portal.model.User; + +public class NavResult implements Iterable, Permissionable, Serializable { + + + private static final long serialVersionUID = 1L; + private long languageId; + public long getLanguageId() { + return languageId; + } + + private String title; + private String href; + private int order; + private String codeLink; + private String parent; + private String type; + private String permissionId; + private String target; + private boolean showOnMenu; + + private String hostId; + private String folderId; + private List childrenFolderIds; + private List children; + private User sysuser = null; + + + public NavResult(NavResult navResult) { + this(navResult.getParentStr(), navResult.getHostId(), navResult.getFolderId(), navResult.getLanguageId()); + } + + public String getFolderId() { + return folderId; + } + + public String getParentStr() { + return this.parent; + } + + public NavResult(String parent, String hostId, String folderId, Long languageId) { + this.hostId = hostId; + this.folderId = folderId; + this.parent = parent; + this.languageId = languageId; + + + title = href = ""; + order = 0; + + try { + sysuser = APILocator.getUserAPI() + .getSystemUser(); + } catch (DotDataException e) { + Logger.warn(this, e.getMessage(), e); + } + + } + + + + public NavResult(String parent, String host, Long languageId) { + this(parent, host, null, languageId); + } + + public String getTitle() throws Exception { + if (title.startsWith("$text.")) { + ViewRenderTool render = new ViewRenderTool(); + render.setVelocityEngine(VelocityUtil.getEngine()); + return render.eval(title); + } else { + return title; + } + } + + public String getHostId() { + return hostId; + } + + public void setHostId(String hostId) { + this.hostId = hostId; + } + + public void setTitle(String title) { + this.title = title; + } + + + public String getHref() { + return href; + } + + public boolean isShowOnMenu() { + return showOnMenu; + } + + public void setShowOnMenu(boolean showOnMenu) { + this.showOnMenu = showOnMenu; + } + + public void setHref(String href) { + this.href = href; + + } + + public boolean isCodeLink() { + return this.codeLink != null; + } + + + public String getCodeLink() { + return codeLink; + } + + public void setCodeLink(String codeLink) { + this.codeLink = codeLink; + } + + + + public int getOrder() { + return order; + } + + public void setOrder(int order) { + this.order = order; + } + + + + + public void setChildren(List children) { + this.children = children; + } + + public boolean isFolder() { + return folderId != null; + } + + public List getChildren() throws Exception { + if (children == null && hostId != null && folderId != null) { + // lazy loadinge children + Host host = APILocator.getHostAPI() + .find(hostId, sysuser, true); + Folder folder = APILocator.getFolderAPI() + .find(folderId, sysuser, true); + Identifier ident = APILocator.getIdentifierAPI() + .find(folder); + NavResult lazyMe = new NavTool().getNav(host, ident.getPath(), languageId, sysuser); + + children = lazyMe.getChildren(); + childrenFolderIds = lazyMe.getChildrenFolderIds(); + } + if (children != null) { + ArrayList list = new ArrayList(); + for (NavResult nn : children) { + if (nn.isFolder()) { + // for folders we avoid returning the same instance + // it could be changed elsewhere and we need it to + // load its children lazily + NavResult ff = new NavResult(folderId, nn.hostId, nn.folderId, nn.languageId); + ff.setTitle(nn.getTitle()); + ff.setHref(nn.getHref()); + ff.setOrder(nn.getOrder()); + ff.setType(nn.getType()); + ff.setPermissionId(nn.getPermissionId()); + ff.setShowOnMenu(nn.isShowOnMenu()); + list.add(ff); + } else { + list.add(nn); + } + } + return list; + } else { + return new ArrayList(); + } + } + + public String getParentPath() throws DotDataException, DotSecurityException { + if (parent == null) + return null; // no parent! I'm the root folder + if (parent.equals(FolderAPI.SYSTEM_FOLDER)) + return "/"; + Folder folder = APILocator.getFolderAPI() + .find(parent, sysuser, true); + Identifier ident = APILocator.getIdentifierAPI() + .find(folder); + return ident.getURI(); + } + + public NavResult getParent() throws DotDataException, DotSecurityException { + String path = getParentPath(); + if (path != null) { + NavResult lazyMe = new NavTool().getNav(APILocator.getHostAPI() + .find(hostId, sysuser, true), path, languageId, sysuser); + + return lazyMe; + } else + return null; + } + + public String toString() { + if (!isCodeLink()) { + String titleToShow; + try { + titleToShow = getTitle(); + } catch (Exception e) { + titleToShow = title; + } + return "" + titleToShow + ""; + } else { + return getCodeLink(); + } + } + + public List getChildrenFolderIds() { + return childrenFolderIds != null ? childrenFolderIds : new ArrayList(); + } + + public void setChildrenFolderIds(List childrenFolderIds) { + this.childrenFolderIds = childrenFolderIds; + } + + @Override + public Iterator iterator() { + try { + List childs= getChildren(); + List ret = new ArrayList<>(); + for(NavResult child : childs) { + ret.add(child); + } + return ret.iterator(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getTarget() { + if (type.equals("link")) + return target; + else + return "_self"; + } + + public void setTarget(String target) { + + this.target = target; + } + + public String getPermissionId() { + return permissionId; + } + + public void setPermissionId(String permissionId) { + this.permissionId = permissionId; + } + + + /// Permissionable methods /// + + @Override + public String getOwner() { + return sysuser.getUserId(); + } + + @Override + public void setOwner(String owner) {} + + @Override + public List acceptedPermissions() { + return Arrays.asList(new PermissionSummary[] {new PermissionSummary("READ", "READ", PermissionAPI.PERMISSION_READ)}); + } + + @Override + public List permissionDependencies(int requiredPermission) { + return null; + } + + @Override + public Permissionable getParentPermissionable() throws DotDataException { + try { + if (type.equals("htmlpage")) { + Identifier ident = APILocator.getIdentifierAPI() + .find(permissionId); + if (Identifier.ASSET_TYPE_CONTENTLET.equalsIgnoreCase(ident.getAssetType())) + return APILocator.getContentletAPI() + .findContentletByIdentifier(permissionId, true, APILocator.getLanguageAPI() + .getDefaultLanguage() + .getId(), sysuser, false) + .getParentPermissionable(); + } + if (type.equals("folder")) + return APILocator.getFolderAPI() + .find(folderId, sysuser, false) + .getParentPermissionable(); + if (type.equals("link")) + return APILocator.getMenuLinkAPI() + .findWorkingLinkById(permissionId, sysuser, false) + .getParentPermissionable(); + if (type.equals("file")) { + Identifier ident = APILocator.getIdentifierAPI() + .find(permissionId); + if (Identifier.ASSET_TYPE_CONTENTLET.equalsIgnoreCase(ident.getAssetType())) + return APILocator.getContentletAPI() + .findContentletByIdentifier(permissionId, true, APILocator.getLanguageAPI() + .getDefaultLanguage() + .getId(), sysuser, false) + .getParentPermissionable(); + } + return null; + } catch (DotSecurityException e) { + throw new RuntimeException(e); + } + } + + @Override + public String getPermissionType() { + return parent != null ? Folder.class.getCanonicalName() : Host.class.getCanonicalName(); + } + + @Override + public boolean isParentPermissionable() { + return isFolder(); + } + + public String getEnclosingPermissionClassName() { + if (type.equals("htmlpage")) + return IHTMLPage.class.getCanonicalName(); + if (type.equals("link")) + return Link.class.getCanonicalName(); + if (type.equals("folder")) + return Folder.class.getCanonicalName(); + throw new IllegalStateException("unknow internal type " + type); // we shouldn't reach this + // point + } + + + +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavResultHydrated.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavResultHydrated.java new file mode 100644 index 000000000000..f89572cc101f --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavResultHydrated.java @@ -0,0 +1,183 @@ +package com.dotcms.rendering.velocity.viewtools.navigation; + +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.PermissionAPI; +import com.dotmarketing.business.web.WebAPILocator; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.util.Config; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.UtilMethods; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.velocity.tools.view.context.ViewContext; + +import com.liferay.portal.model.User; + +public final class NavResultHydrated extends NavResult{ + + /** + * + */ + private static final long serialVersionUID = 1L; + final NavResult navResult; + final transient ViewContext context; + + public NavResultHydrated(final NavResult navResult, final ViewContext context) { + super(navResult); + this.navResult = navResult; + this.context = context; + + } + + + + public boolean isActive() { + if (context != null && UtilMethods.isSet(navResult.getHref())) { + HttpServletRequest req = (HttpServletRequest) context.getRequest(); + if (req != null) { + // We exclude the page name from the Request URI so we can check if page's parent + // object is the real active object + String reqURI = req.getRequestURI(); + String parentPath = reqURI.substring(0, reqURI.lastIndexOf("/")); + if (!parentPath.endsWith("/")) + // Adding a slash at the end of the path, so it avoids false positives + // when two or more paths from the same level starts with the same name + parentPath = parentPath + "/"; + // If the current item is a folder, we check if it's part of current URI + + // System.err.println(href + " : " + reqURI); + if (isFolder() && !navResult.getHref() + .endsWith("/")) { + String tempHref = navResult.getHref() + "/"; + return parentPath.startsWith(tempHref); + } else { + // If it's a page, we check instead if it's the current URI + return !isCodeLink() && navResult.getHref() + .equalsIgnoreCase(reqURI); + } + } + } + return false; + } + @Override + public String getCodeLink() { + if (navResult.getCodeLink() != null && (navResult.getCodeLink() + .contains("$") + || navResult.getCodeLink() + .contains("#"))) { + return UtilMethods.evaluateVelocity(navResult.getCodeLink(), context.getVelocityContext()); + } else { + return navResult.getCodeLink(); + } + } + @Override + public String getTitle() throws Exception { + return navResult.getTitle(); + } + + @Override + public String getHostId() { + return navResult.getHostId(); + } + + + public String getHref() { + return navResult.getHref(); + } + + @Override + public boolean isShowOnMenu() { + return navResult.isShowOnMenu(); + } + + @Override + public boolean isCodeLink() { + return navResult.isCodeLink(); + } + + @Override + public int getOrder() { + return navResult.getOrder(); + } + + + @Override + public boolean isFolder() { + return navResult.isFolder(); + } + + @Override + public List getChildren() throws Exception { + + + List list = navResult.getChildren().stream().map(result -> new NavResultHydrated(result, this.context)).collect(Collectors.toList()); + + + + if (Config.getBooleanProperty("ENABLE_NAV_PERMISSION_CHECK", false)) { + // now filtering permissions + List allow = new ArrayList(list.size()); + + HttpServletRequest req = (HttpServletRequest) context.getRequest(); + User currentUser = WebAPILocator.getUserWebAPI() + .getLoggedInUser(req); + if (currentUser == null) + currentUser = APILocator.getUserAPI() + .getAnonymousUser(); + for (NavResult nv : list) { + try { + if (APILocator.getPermissionAPI() + .doesUserHavePermission(nv, PermissionAPI.PERMISSION_READ, currentUser)) { + allow.add(nv); + } + } catch (Exception ex) { + Logger.error(this, ex.getMessage(), ex); + } + } + return allow; + } + return list; + } + + + public String getParentPath() throws DotDataException, DotSecurityException { + return navResult.getParentPath(); + } + + + + public NavResult getParent() throws DotDataException, DotSecurityException { + return navResult.getParent(); + } + + + + public List getChildrenFolderIds() { + return navResult.getChildrenFolderIds(); + } + + + public String getType() { + return navResult.getType(); + } + + + + public String getTarget() { + return navResult.getTarget(); + } + + + public String getOwner() { + return navResult.getOwner(); + } + + + +} diff --git a/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavTool.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavTool.java new file mode 100644 index 000000000000..fbbad630e90d --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavTool.java @@ -0,0 +1,301 @@ +package com.dotcms.rendering.velocity.viewtools.navigation; + +import com.dotcms.rendering.velocity.viewtools.LanguageWebAPI; + +import com.dotmarketing.beans.Host; +import com.dotmarketing.beans.Identifier; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.CacheLocator; +import com.dotmarketing.business.web.WebAPILocator; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.portlets.fileassets.business.IFileAsset; +import com.dotmarketing.portlets.folders.business.FolderAPI; +import com.dotmarketing.portlets.folders.model.Folder; +import com.dotmarketing.portlets.htmlpageasset.model.IHTMLPage; +import com.dotmarketing.portlets.links.model.Link; +import com.dotmarketing.portlets.links.model.Link.LinkType; +import com.dotmarketing.util.Logger; +import com.dotmarketing.util.RegEX; +import com.dotmarketing.util.RegExMatch; +import com.dotmarketing.util.UtilMethods; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.velocity.tools.view.context.ViewContext; +import org.apache.velocity.tools.view.tools.ViewTool; + +import com.liferay.portal.model.User; + +public class NavTool implements ViewTool { + + private Host currenthost = null; + private static User systemUser = null; + private HttpServletRequest request = null; + private long currentLanguage = 0; + private ViewContext context; + static { + + try { + systemUser = APILocator.getUserAPI() + .getSystemUser(); + } catch (DotDataException e) { + Logger.error(NavTool.class, e.getMessage(), e); + } + } + + @Override + public void init(Object initData) { + context = (ViewContext) initData; + try { + this.request = context.getRequest(); + this.currenthost = WebAPILocator.getHostWebAPI() + .getCurrentHost(context.getRequest()); + this.currentLanguage = WebAPILocator.getLanguageWebAPI() + .getLanguage(this.request) + .getId(); + } catch (Exception e) { + Logger.warn(this, e.getMessage(), e); + } + } + + protected NavResult getNav(Host host, String path) throws DotDataException, DotSecurityException { + return getNav(host, path, this.currentLanguage, this.systemUser); + } + + protected NavResultHydrated getNav(Host host, String path, long languageId, User systemUserParam) + throws DotDataException, DotSecurityException { + + if (path != null && path.contains(".")) { + path = path.substring(0, path.lastIndexOf("/")); + } + + Folder folder = !path.equals("/") ? APILocator.getFolderAPI() + .findFolderByPath(path, host, systemUserParam, true) + : APILocator.getFolderAPI() + .findSystemFolder(); + if (folder == null || !UtilMethods.isSet(folder.getIdentifier())) { + return null; + } + NavResult result = CacheLocator.getNavToolCache() + .getNav(host.getIdentifier(), folder.getInode(), languageId); + if (result != null) { + + return new NavResultHydrated(result, this.context); + } else { + String parentId; + if (!folder.getInode() + .equals(FolderAPI.SYSTEM_FOLDER)) { + Identifier ident = APILocator.getIdentifierAPI() + .find(folder); + parentId = ident.getParentPath() + .equals("/") ? FolderAPI.SYSTEM_FOLDER + : APILocator.getFolderAPI() + .findFolderByPath(ident.getParentPath(), host, systemUserParam, false) + .getInode(); + } else { + parentId = null; + } + result = new NavResult(parentId, host.getIdentifier(), folder.getInode(), languageId); + + Identifier ident = APILocator.getIdentifierAPI() + .find(folder); + result.setHref(ident.getURI()); + result.setTitle(folder.getTitle()); + result.setOrder(folder.getSortOrder()); + result.setType("folder"); + result.setPermissionId(folder.getPermissionId()); + List children = new ArrayList(); + List folderIds = new ArrayList(); + result.setChildren(children); + result.setChildrenFolderIds(folderIds); + result.setShowOnMenu(folder.isShowOnMenu()); + + List menuItems; + if (path.equals("/")) + menuItems = APILocator.getFolderAPI() + .findSubFolders(host, true); + else + menuItems = APILocator.getFolderAPI() + .findMenuItems(folder, systemUserParam, true); + + for (Object item : menuItems) { + if (item instanceof Folder) { + Folder itemFolder = (Folder) item; + ident = APILocator.getIdentifierAPI() + .find(itemFolder); + NavResult nav = new NavResult(folder.getInode(), host.getIdentifier(), itemFolder.getInode(), languageId); + + nav.setTitle(itemFolder.getTitle()); + nav.setHref(ident.getURI()); + nav.setOrder(itemFolder.getSortOrder()); + nav.setType("folder"); + nav.setPermissionId(itemFolder.getPermissionId()); + nav.setShowOnMenu(itemFolder.isShowOnMenu()); + + // it will load lazily its children + folderIds.add(itemFolder.getInode()); + nav = new NavResultHydrated(nav, this.context); + children.add(nav); + } else if (item instanceof IHTMLPage) { + IHTMLPage itemPage = (IHTMLPage) item; + + if (itemPage.getLanguageId() == languageId || LanguageWebAPI.canDefaultPageToDefaultLanguage()) { + final String httpProtocol = "http://"; + final String httpsProtocol = "https://"; + + ident = APILocator.getIdentifierAPI() + .find(itemPage); + + String redirectUri = itemPage.getRedirect(); + NavResult nav = new NavResult(folder.getInode(), host.getIdentifier(), languageId); + + nav.setTitle(itemPage.getTitle()); + if (UtilMethods.isSet(redirectUri) && !redirectUri.startsWith("/")) { + if (redirectUri.startsWith(httpsProtocol) || redirectUri.startsWith(httpProtocol)) { + nav.setHref(redirectUri); + } else { + if (itemPage.isHttpsRequired()) + nav.setHref(httpsProtocol + redirectUri); + else + nav.setHref(httpProtocol + redirectUri); + } + + } else { + nav.setHref(ident.getURI()); + } + nav.setOrder(itemPage.getMenuOrder()); + nav.setType("htmlpage"); + nav.setPermissionId(itemPage.getPermissionId()); + nav.setShowOnMenu(itemPage.isShowOnMenu()); + nav = new NavResultHydrated(nav, this.context); + children.add(nav); + } + } else if (item instanceof Link) { + Link itemLink = (Link) item; + NavResult nav = new NavResult(folder.getInode(), host.getIdentifier(), languageId); + + if (itemLink.getLinkType() + .equals(LinkType.CODE.toString()) && LinkType.CODE.toString() != null) { + nav.setCodeLink(itemLink.getLinkCode()); + } else { + nav.setHref(itemLink.getWorkingURL()); + } + nav.setTitle(itemLink.getTitle()); + nav.setOrder(itemLink.getSortOrder()); + nav.setType("link"); + nav.setTarget(itemLink.getTarget()); + nav.setPermissionId(itemLink.getPermissionId()); + nav.setShowOnMenu(itemLink.isShowOnMenu()); + nav = new NavResultHydrated(nav, this.context); + children.add(nav); + } else if (item instanceof IFileAsset) { + IFileAsset itemFile = (IFileAsset) item; + + if (itemFile.getLanguageId() == languageId || LanguageWebAPI.canDefaultFileToDefaultLanguage()) { + ident = APILocator.getIdentifierAPI() + .find(itemFile.getPermissionId()); + NavResult nav = new NavResult(folder.getInode(), host.getIdentifier(), languageId); + + nav.setTitle(itemFile.getFriendlyName()); + nav.setHref(ident.getURI()); + nav.setOrder(itemFile.getMenuOrder()); + nav.setType("file"); + nav.setPermissionId(itemFile.getPermissionId()); + nav.setShowOnMenu(itemFile.isShowOnMenu()); + nav = new NavResultHydrated(nav, this.context); + children.add(nav); + } + } + } + + CacheLocator.getNavToolCache() + .putNav(host.getIdentifier(), folder.getInode(), result, languageId); + + return new NavResultHydrated(result, this.context); + } + } + + /** + * Pass the level of the nav you wish to retrieve, based on the current path, level 0 being the + * root + * + * @param level + * @return + * @throws DotDataException + * @throws DotSecurityException + */ + public NavResult getNav(int level) throws DotDataException, DotSecurityException { + if (level < 1) + return getNav("/"); + + + String reqPath = getNav().getHref(); + + String[] levels = reqPath.split("/"); + + + if (level + 1 > levels.length) + return null; + + StringBuffer sw = new StringBuffer(); + + for (int i = 1; i <= level; i++) { + sw.append("/"); + sw.append(levels[i]); + } + String path = sw.toString(); + + return getNav(path); + } + + public NavResult getNav() throws DotDataException, DotSecurityException { + return getNav((String) request.getAttribute("javax.servlet.forward.request_uri")); + } + + public NavResult getNav(String path) throws DotDataException, DotSecurityException { + + Host host = getHostFromPath(path); + + if (host == null) + host = currenthost; + + return getNav(host, path); + } + + public NavResult getNav(String path, long languageId) throws DotDataException, DotSecurityException { + + Host host = getHostFromPath(path); + + if (host == null) + host = currenthost; + + return getNav(host, path, languageId, systemUser); + } + + private Host getHostFromPath(String path) throws DotDataException, DotSecurityException { + if (path.startsWith("//")) { + List find = RegEX.find(path, "^//(\\w+)/(.+)"); + if (find.size() == 1) { + String hostname = find.get(0) + .getGroups() + .get(0) + .getMatch(); + path = "/" + find.get(0) + .getGroups() + .get(1) + .getMatch(); + return APILocator.getHostAPI() + .findByName(hostname, systemUser, false); + } + } + + return null; + } + + + +} diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/navigation/NavToolCache.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavToolCache.java similarity index 89% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/navigation/NavToolCache.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavToolCache.java index 191be0a6a57f..59dffa4fe4e5 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/navigation/NavToolCache.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavToolCache.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools.navigation; +package com.dotcms.rendering.velocity.viewtools.navigation; import com.dotmarketing.business.Cachable; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/navigation/NavToolCacheImpl.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavToolCacheImpl.java similarity index 98% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/navigation/NavToolCacheImpl.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavToolCacheImpl.java index 7231c4d567d0..e06671a0d922 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/navigation/NavToolCacheImpl.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/navigation/NavToolCacheImpl.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools.navigation; +package com.dotcms.rendering.velocity.viewtools.navigation; import java.util.LinkedList; import java.util.List; diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/util/ClassUtils.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/util/ClassUtils.java similarity index 96% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/util/ClassUtils.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/util/ClassUtils.java index 84be32bff39a..ee67b0a7e011 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/util/ClassUtils.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/util/ClassUtils.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools.util; +package com.dotcms.rendering.velocity.viewtools.util; /* * Licensed to the Apache Software Foundation (ASF) under one diff --git a/dotCMS/src/main/java/com/dotmarketing/viewtools/util/ConversionUtils.java b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/util/ConversionUtils.java similarity index 96% rename from dotCMS/src/main/java/com/dotmarketing/viewtools/util/ConversionUtils.java rename to dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/util/ConversionUtils.java index 4aa2d7627c0c..4f4d92a1bf6f 100644 --- a/dotCMS/src/main/java/com/dotmarketing/viewtools/util/ConversionUtils.java +++ b/dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/util/ConversionUtils.java @@ -1,4 +1,4 @@ -package com.dotmarketing.viewtools.util; +package com.dotcms.rendering.velocity.viewtools.util; /* * Licensed to the Apache Software Foundation (ASF) under one diff --git a/dotCMS/src/main/java/com/dotcms/rest/ContentResource.java b/dotCMS/src/main/java/com/dotcms/rest/ContentResource.java index acdefc82e0be..dce724afa4da 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/ContentResource.java +++ b/dotCMS/src/main/java/com/dotcms/rest/ContentResource.java @@ -66,7 +66,7 @@ import com.dotmarketing.portlets.structure.model.Relationship; import com.dotmarketing.portlets.workflows.model.WorkflowAction; import com.dotmarketing.util.*; -import com.dotmarketing.viewtools.content.util.ContentUtils; +import com.dotcms.rendering.velocity.viewtools.content.util.ContentUtils; import com.liferay.portal.model.User; import static com.dotmarketing.util.NumberUtil.*; diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/container/ContainerResource.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/container/ContainerResource.java index a99e41377f8e..22a99aa84d4c 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/container/ContainerResource.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/container/ContainerResource.java @@ -1,41 +1,73 @@ package com.dotcms.rest.api.v1.container; -import com.dotcms.contenttype.model.type.ContentType; + +import com.dotcms.contenttype.model.type.BaseContentType; +import com.dotcms.rendering.velocity.services.ContainerLoader; +import com.dotcms.rendering.velocity.services.VelocityType; import com.dotcms.repackage.com.google.common.annotations.VisibleForTesting; -import com.dotcms.repackage.javax.ws.rs.*; +import com.dotcms.repackage.javax.ws.rs.Consumes; +import com.dotcms.repackage.javax.ws.rs.DELETE; +import com.dotcms.repackage.javax.ws.rs.DefaultValue; +import com.dotcms.repackage.javax.ws.rs.GET; +import com.dotcms.repackage.javax.ws.rs.POST; +import com.dotcms.repackage.javax.ws.rs.Path; +import com.dotcms.repackage.javax.ws.rs.PathParam; +import com.dotcms.repackage.javax.ws.rs.Produces; +import com.dotcms.repackage.javax.ws.rs.QueryParam; import com.dotcms.repackage.javax.ws.rs.core.Context; import com.dotcms.repackage.javax.ws.rs.core.MediaType; import com.dotcms.repackage.javax.ws.rs.core.Response; -import com.dotcms.repackage.org.apache.commons.lang.StringUtils; +import com.dotcms.repackage.org.apache.commons.beanutils.BeanUtils; import com.dotcms.repackage.org.glassfish.jersey.server.JSONP; import com.dotcms.rest.InitDataObject; -import com.dotcms.rest.ResponseEntityView; import com.dotcms.rest.WebResource; +import com.dotcms.rest.WidgetResource; import com.dotcms.rest.annotation.NoCache; -import com.dotcms.rest.api.v1.site.SiteHelper; import com.dotcms.rest.exception.mapper.ExceptionMapperUtil; -import com.dotcms.util.I18NUtil; import com.dotcms.util.PaginationUtil; import com.dotcms.util.pagination.ContainerPaginator; import com.dotcms.util.pagination.OrderDirection; -import com.dotcms.util.pagination.SitePaginator; -import com.dotmarketing.beans.Host; +import com.dotcms.uuid.shorty.ShortType; +import com.dotcms.uuid.shorty.ShortyId; + +import com.dotmarketing.beans.ContainerStructure; +import com.dotmarketing.beans.MultiTree; import com.dotmarketing.business.APILocator; -import com.dotmarketing.business.UserAPI; +import com.dotmarketing.business.PermissionLevel; +import com.dotmarketing.business.web.WebAPILocator; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.factories.MultiTreeFactory; +import com.dotmarketing.portlets.containers.model.Container; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.languagesmanager.model.Language; import com.dotmarketing.util.Logger; -import com.dotmarketing.util.UtilMethods; -import com.dotmarketing.util.WebKeys; -import com.liferay.portal.model.User; +import com.dotmarketing.util.PageMode; +import com.dotmarketing.util.VelocityUtil; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; +import java.io.File; +import java.io.IOException; import java.io.Serializable; +import java.io.StringWriter; +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; import java.util.Map; -import static com.dotcms.util.CollectionsUtils.map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.io.IOUtils; +import org.apache.velocity.exception.MethodInvocationException; +import org.apache.velocity.exception.ParseErrorException; +import org.apache.velocity.exception.ResourceNotFoundException; + +import com.beust.jcommander.internal.Maps; +import com.google.common.collect.Lists; +import com.liferay.portal.model.User; /** - * This resource provides all the different end-points associated to information - * and actions that the front-end can perform on the {@link com.dotmarketing.portlets.containers.model.Container}. + * This resource provides all the different end-points associated to information and actions that + * the front-end can perform on the {@link com.dotmarketing.portlets.containers.model.Container}. * */ @Path("/v1/containers") @@ -46,39 +78,36 @@ public class ContainerResource implements Serializable { private final PaginationUtil paginationUtil; private final WebResource webResource; + + public ContainerResource() { - this(new WebResource(), - new PaginationUtil(new ContainerPaginator())); + this(new WebResource(), new PaginationUtil(new ContainerPaginator())); } @VisibleForTesting - public ContainerResource(final WebResource webResource, - final PaginationUtil paginationUtil) { + public ContainerResource(final WebResource webResource, final PaginationUtil paginationUtil) { this.webResource = webResource; this.paginationUtil = paginationUtil; } /** - * Return a list of {@link com.dotmarketing.portlets.containers.model.Container}, entity response syntax:. + * Return a list of {@link com.dotmarketing.portlets.containers.model.Container}, entity + * response syntax:. * - * - * { - * contentTypes: array of Container - * total: total number of Containers - * } - * + * { contentTypes: array of Container total: total number of Containers } * - * Url sintax: api/v1/container?filter=filter-string&page=page-number&per_page=per-page&ordeby=order-field-name&direction=order-direction&host=host-id + * Url sintax: + * api/v1/container?filter=filter-string&page=page-number&per_page=per-page&ordeby=order-field-name&direction=order-direction&host=host-id * * where: * *

    - *
  • filter-string: just return Container who content this pattern into its title
  • - *
  • page: page to return
  • - *
  • per_page: limit of items to return
  • - *
  • ordeby: field to order by
  • - *
  • direction: asc for upward order and desc for downward order
  • - *
  • host: filter by host's id
  • + *
  • filter-string: just return Container who content this pattern into its title
  • + *
  • page: page to return
  • + *
  • per_page: limit of items to return
  • + *
  • ordeby: field to order by
  • + *
  • direction: asc for upward order and desc for downward order
  • + *
  • host: filter by host's id
  • *
* * Url example: v1/container?filter=test&page=2&orderby=title @@ -92,24 +121,308 @@ public ContainerResource(final WebResource webResource, @Consumes(MediaType.APPLICATION_JSON) @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public final Response getContainers(@Context final HttpServletRequest request, - @QueryParam(PaginationUtil.FILTER) final String filter, - @QueryParam(PaginationUtil.PAGE) final int page, - @QueryParam(PaginationUtil.PER_PAGE) final int perPage, - @DefaultValue("title") @QueryParam(PaginationUtil.ORDER_BY) final String orderBy, - @DefaultValue("ASC") @QueryParam(PaginationUtil.DIRECTION) final String direction, - @QueryParam(ContainerPaginator.HOST_PARAMETER_ID) final String hostId) { + @QueryParam(PaginationUtil.FILTER) final String filter, @QueryParam(PaginationUtil.PAGE) final int page, + @QueryParam(PaginationUtil.PER_PAGE) final int perPage, + @DefaultValue("title") @QueryParam(PaginationUtil.ORDER_BY) final String orderBy, + @DefaultValue("ASC") @QueryParam(PaginationUtil.DIRECTION) final String direction, + @QueryParam(ContainerPaginator.HOST_PARAMETER_ID) final String hostId) { final InitDataObject initData = webResource.init(null, true, request, true, null); final User user = initData.getUser(); try { - final Map extraParams = map(ContainerPaginator.HOST_PARAMETER_ID, hostId); - return this.paginationUtil.getPage(request, user, filter, page, perPage, orderBy, - OrderDirection.valueOf(direction), extraParams); + final Map extraParams = Maps.newHashMap(); + extraParams.put(ContainerPaginator.HOST_PARAMETER_ID, (Object) hostId); + return this.paginationUtil.getPage(request, user, filter, page, perPage, orderBy, OrderDirection.valueOf(direction), + extraParams); } catch (Exception e) { Logger.error(this, e.getMessage(), e); return ExceptionMapperUtil.createResponse(e, Response.Status.INTERNAL_SERVER_ERROR); } } -} \ No newline at end of file + + @GET + @JSONP + @NoCache + @Consumes(MediaType.APPLICATION_JSON) + @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) + @Path("/{containerId}/uuid/{uuid}/content/{contentletId}") + public final Response containerContent(@Context final HttpServletRequest req, @Context final HttpServletResponse res, + @PathParam("containerId") final String containerId, @PathParam("contentletId") final String contentletId, + @PathParam("uuid") final String uuid) throws DotDataException, DotSecurityException, ParseErrorException, + MethodInvocationException, ResourceNotFoundException, IOException, IllegalAccessException, InstantiationException, + InvocationTargetException, NoSuchMethodException { + + final InitDataObject initData = webResource.init(true, req, true); + final User user = initData.getUser(); + PageMode mode = PageMode.get(req); + Language landId = WebAPILocator.getLanguageWebAPI() + .getLanguage(req); + + + + + PageMode.setPageMode(req, PageMode.EDIT_MODE); + + + + + + ShortyId contentShorty = APILocator.getShortyAPI() + .getShorty(contentletId) + .orElseGet(() -> { + throw new ResourceNotFoundException("Can't find contentlet:" + contentletId); + }); + + + + final Contentlet contentlet = (contentShorty.type == ShortType.IDENTIFIER) ? APILocator.getContentletAPI() + .findContentletByIdentifier(contentShorty.longId, mode.showLive, landId.getId(), user, mode.respectAnonPerms) + : APILocator.getContentletAPI() + .find(contentShorty.longId, user, mode.respectAnonPerms); + + if (contentlet.getContentType() + .baseType() == BaseContentType.WIDGET) { + Map response = new HashMap<>(); + response.put("render", WidgetResource.parseWidget(req, res, contentlet)); + + return Response.ok(response) + .build(); + + + } + + ShortyId containerShorty = APILocator.getShortyAPI() + .getShorty(containerId) + .orElseGet(() -> { + throw new ResourceNotFoundException("Can't find Container:" + containerId); + }); + + Container container = (containerShorty.type != ShortType.IDENTIFIER) + ? APILocator.getContainerAPI() + .find(containerId, user, mode.showLive) + : (mode.showLive) ? (Container) APILocator.getVersionableAPI() + .findLiveVersion(containerShorty.longId, user, mode.respectAnonPerms) + : (Container) APILocator.getVersionableAPI() + .findWorkingVersion(containerShorty.longId, user, mode.respectAnonPerms); + + + + org.apache.velocity.context.Context context = VelocityUtil.getWebContext(req, res); + + + context.put(ContainerLoader.SHOW_PRE_POST_LOOP, false); + context.put("contentletList" + container.getIdentifier() + uuid, Lists.newArrayList(contentlet.getIdentifier())); + StringWriter out = new StringWriter(); + + + + + VelocityUtil.getEngine() + .mergeTemplate(mode.name() + File.separator + container.getIdentifier() + "/" + uuid + "." + + VelocityType.CONTAINER.fileExtension, context, out); + + Map response = new HashMap<>(); + response.put("render", out.toString()); + + return Response.ok(response) + .build(); + + } + + + + @POST + @JSONP + @NoCache + @Consumes(MediaType.APPLICATION_JSON) + @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) + @Path("add/{containerId}/content/{contentletId}/uid/{uid}/order/{order}") + public final Response addContentToContainer(@Context final HttpServletRequest req, @Context final HttpServletResponse res, + @PathParam("containerId") final String containerId, @PathParam("contentletId") final String contentletId, + @QueryParam("order") final int order, @PathParam("uid") final String uid) throws DotDataException, + DotSecurityException, ParseErrorException, MethodInvocationException, ResourceNotFoundException, IOException, + IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { + + + final InitDataObject initData = webResource.init(true, req, true); + final User user = initData.getUser(); + final PageMode mode = PageMode.get(req); + final Language id = WebAPILocator.getLanguageWebAPI() + .getLanguage(req); + + ShortyId contentShorty = APILocator.getShortyAPI() + .getShorty(contentletId) + .orElseGet(() -> { + throw new ResourceNotFoundException("Can't find contentlet:" + contentletId); + }); + final Contentlet contentlet = (contentShorty.subType == ShortType.CONTENTLET) ? APILocator.getContentletAPI() + .find(contentShorty.longId, user, !mode.showLive) + : APILocator.getContentletAPI() + .findContentletByIdentifier(contentShorty.longId, mode.showLive, id.getId(), user, mode.isAdmin); + + + + ShortyId containerShorty = APILocator.getShortyAPI() + .getShorty(containerId) + .orElseGet(() -> { + throw new ResourceNotFoundException("Can't find Container:" + containerId); + }); + Container container = (containerShorty.subType == ShortType.CONTAINER) ? APILocator.getContainerAPI() + .find(containerId, user, mode.isAdmin) + : (mode.showLive) ? (Container) APILocator.getVersionableAPI() + .findLiveVersion(containerShorty.longId, user, !mode.isAdmin) + : (Container) APILocator.getVersionableAPI() + .findWorkingVersion(containerShorty.longId, user, !mode.isAdmin); + + + APILocator.getPermissionAPI() + .checkPermission(contentlet, PermissionLevel.READ, user); + APILocator.getPermissionAPI() + .checkPermission(container, PermissionLevel.EDIT, user); + + + + MultiTree mt = new MultiTree().setContainer(containerId) + .setContentlet(contentletId) + .setRelationType(uid) + .setTreeOrder(order); + + MultiTreeFactory.saveMultiTree(mt); + + + return Response.ok("ok") + .build(); + } + + + @DELETE + @JSONP + @NoCache + @Consumes(MediaType.APPLICATION_JSON) + @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) + @Path("delete/{containerId}/content/{contentletId}/uid/{uid}") + public final Response removeContentletFromContainer(@Context final HttpServletRequest req, + @Context final HttpServletResponse res, @PathParam("containerId") final String containerId, + @PathParam("contentletId") final String contentletId, @QueryParam("order") final long order, + @PathParam("uid") final String uid) throws DotDataException, DotSecurityException, ParseErrorException, + MethodInvocationException, ResourceNotFoundException, IOException, IllegalAccessException, InstantiationException, + InvocationTargetException, NoSuchMethodException { + + final InitDataObject initData = webResource.init(true, req, true); + final User user = initData.getUser(); + final PageMode mode = PageMode.get(req); + + + final Language id = WebAPILocator.getLanguageWebAPI() + .getLanguage(req); + + ShortyId contentShorty = APILocator.getShortyAPI() + .getShorty(contentletId) + .orElseGet(() -> { + throw new ResourceNotFoundException("Can't find contentlet:" + contentletId); + }); + final Contentlet contentlet = (contentShorty.subType == ShortType.CONTENTLET) ? APILocator.getContentletAPI() + .find(contentShorty.longId, user, !mode.isAdmin) + : APILocator.getContentletAPI() + .findContentletByIdentifier(contentShorty.longId, mode.showLive, id.getId(), user, !mode.isAdmin); + + + + ShortyId containerShorty = APILocator.getShortyAPI() + .getShorty(containerId) + .orElseGet(() -> { + throw new ResourceNotFoundException("Can't find Container:" + containerId); + }); + Container container = (containerShorty.subType == ShortType.CONTAINER) ? APILocator.getContainerAPI() + .find(containerId, user, !mode.isAdmin) + : (mode.showLive) ? (Container) APILocator.getVersionableAPI() + .findLiveVersion(containerShorty.longId, user, !mode.isAdmin) + : (Container) APILocator.getVersionableAPI() + .findWorkingVersion(containerShorty.longId, user, !mode.isAdmin); + + + APILocator.getPermissionAPI() + .checkPermission(contentlet, PermissionLevel.READ, user); + APILocator.getPermissionAPI() + .checkPermission(container, PermissionLevel.EDIT, user); + + MultiTree mt = new MultiTree().setContainer(containerId) + .setContentlet(contentletId) + .setRelationType(uid); + + + MultiTreeFactory.deleteMultiTree(mt); + + return Response.ok("ok") + .build(); + } + + + + @Path("/containerContent/{params:.*}") + public final Response containerContents(@Context final HttpServletRequest req, @Context final HttpServletResponse res, + @QueryParam("containerId") final String containerId, @QueryParam("contentInode") final String contentInode) + throws DotDataException, DotSecurityException, ParseErrorException, MethodInvocationException, + ResourceNotFoundException, IOException { + + final InitDataObject initData = webResource.init(true, req, true); + final User user = initData.getUser(); + + Language id = WebAPILocator.getLanguageWebAPI() + .getLanguage(req); + + PageMode mode = PageMode.get(req); + + Container container = APILocator.getContainerAPI() + .find(containerId, user, !mode.isAdmin); + + org.apache.velocity.context.Context context = VelocityUtil.getWebContext(req, res); + Contentlet contentlet = APILocator.getContentletAPI() + .find(contentInode, user, !mode.isAdmin); + ContainerStructure cStruct = APILocator.getContainerAPI() + .getContainerStructures(container) + .stream() + .filter(cs -> contentlet.getStructureInode() + .equals(cs.getStructureId())) + .findFirst() + .orElse(null); + + StringWriter in = new StringWriter(); + StringWriter out = new StringWriter(); + in.append("#set ($contentletList") + .append(container.getIdentifier()) + .append(" = [") + .append(contentlet.getIdentifier()) + .append("] )") + .append("#set ($totalSize") + .append(container.getIdentifier()) + .append("=") + .append("1") + .append(")") + .append("#parseContainer(\"") + .append(container.getIdentifier()) + .append("\")"); + + + + VelocityUtil.getEngine() + .evaluate(context, out, this.getClass() + .getName(), IOUtils.toInputStream(in.toString())); + + Map response = new HashMap<>(); + response.put("render", out.toString()); + + final Response.ResponseBuilder responseBuilder = Response.ok(response); + + + + return responseBuilder.build(); + + } + + + +} + diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/container/ContainerResourceHelper.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/container/ContainerResourceHelper.java new file mode 100644 index 000000000000..db4b931c82ae --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/container/ContainerResourceHelper.java @@ -0,0 +1,14 @@ +package com.dotcms.rest.api.v1.container; + +import java.io.Serializable; + + +public class ContainerResourceHelper implements Serializable { + + + + + + + +} diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/content/ContentRelationshipsHelper.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/content/ContentRelationshipsHelper.java index 3a6aafa494b2..331a87ed2ae1 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/content/ContentRelationshipsHelper.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/content/ContentRelationshipsHelper.java @@ -12,7 +12,7 @@ import com.dotmarketing.util.json.JSONArray; import com.dotmarketing.util.json.JSONException; import com.dotmarketing.util.json.JSONObject; -import com.dotmarketing.viewtools.content.util.ContentUtils; +import com.dotcms.rendering.velocity.viewtools.content.util.ContentUtils; import com.liferay.portal.model.User; import javax.servlet.http.HttpServletRequest; diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/ContainerView.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/ContainerView.java index d98def544bcb..4b3be8d50e69 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/ContainerView.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/ContainerView.java @@ -16,7 +16,7 @@ * @version 4.2 * @since Oct 6, 2017 */ -public class ContainerView implements Serializable { +class ContainerView implements Serializable { private static final long serialVersionUID = 1572918359580445566L; diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/ContentletMixIn.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/ContentletMixIn.java index d9c8f93eaf37..bf057d16672a 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/ContentletMixIn.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/ContentletMixIn.java @@ -11,7 +11,7 @@ * @version 4.2 * @since Oct 9, 2017 */ -public abstract class ContentletMixIn { +abstract class ContentletMixIn { @JsonIgnore public abstract Permissionable getParentPermissionable(); diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/JsonMapper.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/JsonMapper.java index 80e1170184c2..7c7b6536c7d2 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/JsonMapper.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/JsonMapper.java @@ -13,7 +13,7 @@ * @version 4.2 * @since Oct 9, 2017 */ -public class JsonMapper { +class JsonMapper { private JsonMapper() { diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageForm.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageForm.java index c651a56dc18d..ef02851bb9b3 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageForm.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageForm.java @@ -16,7 +16,7 @@ * {@link PageResource}'s form */ @JsonDeserialize(builder = PageForm.Builder.class) -public class PageForm { +class PageForm { private String themeId; private String title; diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageResource.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageResource.java index 8c8b2fb1f053..9e2eab3628ab 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageResource.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageResource.java @@ -17,7 +17,10 @@ import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.templates.model.Template; import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; + import com.fasterxml.jackson.core.JsonProcessingException; +import com.google.common.collect.ImmutableMap; import com.liferay.portal.model.User; import javax.servlet.http.HttpServletRequest; @@ -135,7 +138,7 @@ public Response loadJson(@Context final HttpServletRequest request, @Context fin @GET @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) @Path("/render/{uri: .*}") - public Response renderPage(@Context final HttpServletRequest request, @Context final + public Response renderPageObject(@Context final HttpServletRequest request, @Context final HttpServletResponse response, @PathParam("uri") final String uri, @QueryParam("live") @DefaultValue("true") final boolean live) { // Force authentication final InitDataObject auth = webResource.init(false, request, true); @@ -172,7 +175,49 @@ public Response renderPage(@Context final HttpServletRequest request, @Context f } return res; } + + + @NoCache + @GET + @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) + @Path("/renderHTML/{uri: .*}") + public Response renderHTMLOnly(@Context final HttpServletRequest request, @Context final + HttpServletResponse response, @PathParam("uri") final String uri, @QueryParam("mode") @DefaultValue("LIVE_ADMIN") String modeStr) { + // Force authentication + final InitDataObject auth = webResource.init(false, request, true); + final User user = auth.getUser(); + Response res = null; + + PageMode mode = PageMode.get(modeStr); + PageMode.setPageMode(request, mode); + try { + final String html = this.pageResourceHelper.getPageRendered(request, response, user, uri, mode); + final Response.ResponseBuilder responseBuilder = Response.ok(ImmutableMap.of("render",html)); + responseBuilder.header("Access-Control-Expose-Headers", "Authorization"); + responseBuilder.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, " + + "Content-Type, " + "Accept, Authorization"); + res = responseBuilder.build(); + } catch (JsonProcessingException e) { + final String errorMsg = "An error occurred when generating the JSON response (" + e.getMessage() + ")"; + Logger.error(this, e.getMessage(), e); + res = ExceptionMapperUtil.createResponse(null, errorMsg); + } catch (DotSecurityException e) { + PageMode.setPageMode(request, PageMode.ADMIN_MODE); + final String errorMsg = "The user does not have the required permissions (" + e.getMessage() + ")"; + Logger.error(this, errorMsg, e); + res = ExceptionMapperUtil.createResponse(e, Response.Status.UNAUTHORIZED); + } catch (DotDataException e) { + final String errorMsg = "An error occurred when accessing the page information (" + e.getMessage() + ")"; + Logger.error(this, e.getMessage(), e); + res = ExceptionMapperUtil.createResponse(null, errorMsg); + } catch (Exception e) { + final String errorMsg = "An internal error occurred (" + e.getMessage() + ")"; + Logger.error(this, errorMsg, e); + res = ExceptionMapperUtil.createResponse(e, Response.Status.INTERNAL_SERVER_ERROR); + } + return res; + } /** * Save a template and link it with a page, If the page already has a anonymous template linked then it is updated, * otherwise a new template is created and the old link template remains unchanged diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageResourceHelper.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageResourceHelper.java index 861eb07e05fe..e68d52a47f99 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageResourceHelper.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageResourceHelper.java @@ -6,6 +6,7 @@ import com.dotmarketing.beans.ContainerStructure; import com.dotmarketing.beans.Host; import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.PermissionLevel; import com.dotmarketing.business.VersionableAPI; import com.dotmarketing.business.web.HostWebAPI; import com.dotmarketing.business.web.WebAPILocator; @@ -24,17 +25,23 @@ import com.dotmarketing.portlets.templates.business.TemplateAPI; import com.dotmarketing.portlets.templates.design.bean.TemplateLayout; import com.dotmarketing.portlets.templates.model.Template; +import com.dotmarketing.util.PageMode; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.VelocityUtil; +import com.dotmarketing.util.WebKeys; import com.dotmarketing.util.json.JSONException; import com.dotmarketing.util.json.JSONObject; -import com.dotmarketing.viewtools.DotTemplateTool; + +import com.dotcms.rendering.velocity.services.VelocityType; +import com.dotcms.rendering.velocity.viewtools.DotTemplateTool; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectWriter; import com.liferay.portal.PortalException; import com.liferay.portal.SystemException; import com.liferay.portal.model.User; import org.apache.velocity.context.Context; +import org.apache.velocity.exception.ParseErrorException; +import org.apache.velocity.exception.ResourceNotFoundException; import javax.rmi.CORBA.Util; import javax.servlet.http.HttpServletRequest; @@ -70,7 +77,6 @@ public class PageResourceHelper implements Serializable { private final LanguageAPI langAPI = APILocator.getLanguageAPI(); private static final boolean RESPECT_FE_ROLES = Boolean.TRUE; - private static final boolean RESPECT_ANON_PERMISSIONS = Boolean.TRUE; /** * Private constructor @@ -111,7 +117,8 @@ public static PageResourceHelper getInstance() { public PageView getPageMetadata(final HttpServletRequest request, final HttpServletResponse response, final User user, final String uri, boolean live) throws DotSecurityException, DotDataException { - return getPageMetadata(request, response, user, uri, false, live); + + return getPageMetadata(request, response, user, uri, false, PageMode.get(request)); } /** @@ -131,9 +138,37 @@ public PageView getPageMetadata(final HttpServletRequest request, final HttpServ public PageView getPageMetadataRendered(final HttpServletRequest request, final HttpServletResponse response, final User user, final String uri, boolean live) throws DotSecurityException, DotDataException { - return getPageMetadata(request, response, user, uri, true, live); + return getPageMetadata(request, response, user, uri, true, PageMode.get(request)); + } + + + public String getPageRendered(final HttpServletRequest request, final + HttpServletResponse response, final User user, final String uri, PageMode mode) throws ResourceNotFoundException, ParseErrorException, DotRuntimeException, Exception { + + final Context velocityContext = VelocityUtil.getWebContext(request, response); + + final String siteName = null == request.getParameter(Host.HOST_VELOCITY_VAR_NAME) ? + request.getServerName() : request.getParameter(Host.HOST_VELOCITY_VAR_NAME); + final Host site = this.hostWebAPI.resolveHostName(siteName, user, RESPECT_FE_ROLES); + + final String pageUri = (uri.length()>0 && '/' == uri.charAt(0)) ? uri : ("/" + uri); + final HTMLPageAsset page = (HTMLPageAsset) this.htmlPageAssetAPI.getPageByPath(pageUri, + site, this.languageAPI.getDefaultLanguage().getId(), mode.respectAnonPerms); + + if(mode.isAdmin ) { + APILocator.getPermissionAPI().checkPermission(page, PermissionLevel.READ, user); + } + + + + + return VelocityUtil.mergeTemplate("/" + mode.name() + "/" + page + .getIdentifier() + "_" + page.getLanguageId() + "." + VelocityType.HTMLPAGE.fileExtension, + velocityContext); } + + /** * @param request The {@link HttpServletRequest} object. * @param response The {@link HttpServletResponse} object. @@ -147,7 +182,7 @@ public PageView getPageMetadataRendered(final HttpServletRequest request, final * @throws DotDataException An error occurred when accessing the data source. */ private PageView getPageMetadata(final HttpServletRequest request, final HttpServletResponse - response, final User user, final String uri, final boolean isRendered, boolean live) throws + response, final User user, final String uri, final boolean isRendered, PageMode mode) throws DotSecurityException, DotDataException { final Context velocityContext = VelocityUtil.getWebContext(request, response); @@ -155,25 +190,32 @@ private PageView getPageMetadata(final HttpServletRequest request, final HttpSer request.getServerName() : request.getParameter(Host.HOST_VELOCITY_VAR_NAME); final Host site = this.hostWebAPI.resolveHostName(siteName, user, RESPECT_FE_ROLES); - final String pageUri = ('/' == uri.charAt(0)) ? uri : ("/" + uri); + final String pageUri = (uri.length()>0 && '/' == uri.charAt(0)) ? uri : ("/" + uri); final HTMLPageAsset page = (HTMLPageAsset) this.htmlPageAssetAPI.getPageByPath(pageUri, - site, this.languageAPI.getDefaultLanguage().getId(), false); + site, this.languageAPI.getDefaultLanguage().getId(), mode.showLive); + + + if (isRendered) { try { - page.setProperty("rendered", VelocityUtil.mergeTemplate("/live/" + page - .getIdentifier() + "_" + page.getLanguageId() + ".dotpage", - velocityContext)); + page.setProperty("rendered", getPageRendered(request, response, user, uri, mode)); } catch (Exception e) { throw new DotDataException(String.format("Page '%s' could not be rendered via " + "Velocity.", pageUri), e); } } - Template template = live ? (Template) this.versionableAPI.findLiveVersion(page.getTemplateId(), user, RESPECT_ANON_PERMISSIONS) : - (Template) this.versionableAPI.findWorkingVersion(page.getTemplateId(), user, RESPECT_ANON_PERMISSIONS); + Template template = mode.showLive ? (Template) this.versionableAPI.findLiveVersion(page.getTemplateId(), user, mode.respectAnonPerms) : + (Template) this.versionableAPI.findWorkingVersion(page.getTemplateId(), user, mode.respectAnonPerms); final List templateContainers = this.templateAPI.getContainersInTemplate (template, user, RESPECT_FE_ROLES); + + templateContainers.addAll(APILocator.getContainerAPI().getContainersOnPage(page)); + + + + final Map mappedContainers = new LinkedHashMap<>(); for (final Container container : templateContainers) { final List containerStructures = this.containerAPI diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageView.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageView.java index c1742a6a0615..e4464d938ea4 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageView.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PageView.java @@ -24,7 +24,7 @@ * @version 4.2 * @since Oct 6, 2017 */ -public class PageView implements Serializable { +class PageView implements Serializable { private static final long serialVersionUID = 1642131505258302751L; diff --git a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PermissionableMixIn.java b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PermissionableMixIn.java index 25965d7303c7..02b1e018cee4 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PermissionableMixIn.java +++ b/dotCMS/src/main/java/com/dotcms/rest/api/v1/page/PermissionableMixIn.java @@ -10,7 +10,7 @@ * @version 4.2 * @since Oct 9, 2017 */ -public abstract class PermissionableMixIn { +abstract class PermissionableMixIn { @JsonIgnore abstract Permissionable getParentPermissionable(); diff --git a/dotCMS/src/main/java/com/dotcms/rest/elasticsearch/ESContentResourcePortlet.java b/dotCMS/src/main/java/com/dotcms/rest/elasticsearch/ESContentResourcePortlet.java index 82c60718b1ea..2982b201df77 100644 --- a/dotCMS/src/main/java/com/dotcms/rest/elasticsearch/ESContentResourcePortlet.java +++ b/dotCMS/src/main/java/com/dotcms/rest/elasticsearch/ESContentResourcePortlet.java @@ -16,6 +16,8 @@ import com.dotmarketing.portlets.contentlet.business.ContentletAPI; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; + import com.liferay.portal.model.User; import javax.servlet.http.HttpServletRequest; @@ -38,13 +40,7 @@ public Response search(@Context HttpServletRequest request, @Context HttpServlet User user = initData.getUser(); ResourceResponse responseResource = new ResourceResponse(initData.getParamsMap()); - boolean live = true; - boolean ADMIN_MODE = (session.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null); - boolean PREVIEW_MODE = ((session.getAttribute(com.dotmarketing.util.WebKeys.PREVIEW_MODE_SESSION) != null) && ADMIN_MODE); - boolean EDIT_MODE = ((session.getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) != null) && ADMIN_MODE); - if (EDIT_MODE || PREVIEW_MODE) { - live = false; - } + PageMode mode = PageMode.get(request); JSONObject esQuery; try { @@ -55,7 +51,7 @@ public Response search(@Context HttpServletRequest request, @Context HttpServlet } try { - ESSearchResults esresult = esapi.esSearch(esQuery.toString(), live, user, live); + ESSearchResults esresult = esapi.esSearch(esQuery.toString(), mode.showLive, user, mode.showLive); JSONObject json = new JSONObject(); JSONArray jsonCons = new JSONArray(); @@ -117,13 +113,7 @@ public Response searchRaw(@Context HttpServletRequest request) { HttpSession session = request.getSession(); - boolean live = true; - boolean ADMIN_MODE = (session.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null); - boolean PREVIEW_MODE = ((session.getAttribute(com.dotmarketing.util.WebKeys.PREVIEW_MODE_SESSION) != null) && ADMIN_MODE); - boolean EDIT_MODE = ((session.getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) != null) && ADMIN_MODE); - if (EDIT_MODE || PREVIEW_MODE) { - live = false; - } + PageMode mode = PageMode.get(request); ResourceResponse responseResource = new ResourceResponse(initData.getParamsMap()); @@ -131,7 +121,7 @@ public Response searchRaw(@Context HttpServletRequest request) { try { String esQuery = IOUtils.toString(request.getInputStream()); - return responseResource.response(esapi.esSearchRaw(esQuery, live, user, live).toString()); + return responseResource.response(esapi.esSearchRaw(esQuery, mode.showLive, user, mode.showLive).toString()); } catch (Exception e) { Logger.error(this.getClass(), "Error processing :" + e.getMessage(), e); diff --git a/dotCMS/src/main/java/com/dotcms/spring/web/DotView.java b/dotCMS/src/main/java/com/dotcms/spring/web/DotView.java index fad77836b5e0..c93823d35108 100644 --- a/dotCMS/src/main/java/com/dotcms/spring/web/DotView.java +++ b/dotCMS/src/main/java/com/dotcms/spring/web/DotView.java @@ -2,7 +2,6 @@ import com.dotmarketing.filters.Constants; import com.dotmarketing.util.VelocityUtil; -import com.dotmarketing.velocity.VelocityServlet; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -36,14 +35,12 @@ public void render(Map map, HttpServletRequest request, HttpServletRe ctx.put(x, map.get(x)); } - // add the context to the request.attr - // where it will be picked up and used by the VelocityServlet - request.setAttribute(VelocityServlet.VELOCITY_CONTEXT, ctx); + // override the page path request.setAttribute(Constants.CMS_FILTER_URI_OVERRIDE, pagePath); - request.getRequestDispatcher("/servlets/VelocityServlet").forward(request, response); + request.getRequestDispatcher("/servlets/VelocityLiveServlet").forward(request, response); } else { pagePath = pagePath.replaceFirst("redirect:", ""); diff --git a/dotCMS/src/main/java/com/dotcms/translate/GoogleTranslationService.java b/dotCMS/src/main/java/com/dotcms/translate/GoogleTranslationService.java index cbd32d8765e7..fba3f8b93dbb 100644 --- a/dotCMS/src/main/java/com/dotcms/translate/GoogleTranslationService.java +++ b/dotCMS/src/main/java/com/dotcms/translate/GoogleTranslationService.java @@ -11,7 +11,7 @@ import com.dotmarketing.util.Logger; import com.dotmarketing.util.json.JSONArray; import com.dotmarketing.util.json.JSONObject; -import com.dotmarketing.viewtools.JSONTool; +import com.dotcms.rendering.velocity.viewtools.JSONTool; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; diff --git a/dotCMS/src/main/java/com/dotcms/webdav/FileContentService.java b/dotCMS/src/main/java/com/dotcms/webdav/FileContentService.java new file mode 100644 index 000000000000..76bd6116233f --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/webdav/FileContentService.java @@ -0,0 +1,35 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ + +package com.dotcms.webdav; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +/** + * Abstraction for storing and retrieving + * + * @author brad + */ +public interface FileContentService { + void setFileContent(File file, InputStream in) throws FileNotFoundException, IOException; + InputStream getFileContent(File file) throws FileNotFoundException; +} diff --git a/dotCMS/src/main/java/com/dotcms/webdav/FileSystemResourceFactory.java b/dotCMS/src/main/java/com/dotcms/webdav/FileSystemResourceFactory.java new file mode 100644 index 000000000000..ec7f39db1f76 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/webdav/FileSystemResourceFactory.java @@ -0,0 +1,264 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional information regarding + * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. You may obtain a + * copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package com.dotcms.webdav; + +import java.io.File; + +import com.dotcms.repackage.com.bradmcevoy.common.Path; +import com.dotcms.repackage.com.bradmcevoy.http.Resource; +import com.dotcms.repackage.com.bradmcevoy.http.ResourceFactory; +import com.dotcms.repackage.com.bradmcevoy.http.SecurityManager; +import com.dotcms.repackage.com.ettrema.http.fs.LockManager; +import com.dotcms.repackage.com.ettrema.http.fs.NullSecurityManager; +import com.dotmarketing.util.Logger; + + +/** + * A resource factory which provides access to files in a file system. + * + * Using this with milton is equivalent to using the dav servlet in tomcat + * + */ +public final class FileSystemResourceFactory implements ResourceFactory { + + + private FileContentService contentService; + File root; + SecurityManager securityManager; + LockManager lockManager; + Long maxAgeSeconds; + String contextPath; + boolean allowDirectoryBrowsing; + String defaultPage; + boolean digestAllowed = true; + private String ssoPrefix; + + /** + * Creates and (optionally) initialises the factory. This looks for a properties file + * FileSystemResourceFactory.properties in the classpath If one is found it uses the root and + * realm properties to initialise + * + * If not found the factory is initialised with the defaults root: user.home system property + * realm: milton-fs-test + * + * These initialised values are not final, and may be changed through the setters or init method + * + * To be honest its pretty naf configuring like this, but i don't want to force people to use + * spring or any other particular configuration tool + * + */ + public FileSystemResourceFactory() { + Logger.info(FileSystemResourceFactory.class, "setting default configuration..."); + String sRoot = System.getProperty("user.home"); + SecurityManager sm = new NullSecurityManager(); + contentService = new SimpleFileContentService(); + setLockManager(new FsMemoryLockManager()); + init(sRoot, sm); + } + + protected void init(String sRoot, SecurityManager securityManager) { + setRoot(new File(sRoot + "/git/webdav")); + setSecurityManager(securityManager); + setContextPath("/webdav/live"); + } + + /** + * + * @param root - the root folder of the filesystem to expose. This must include the context path. + * Eg, if you've deployed to webdav-fs, root must contain a folder called webdav-fs + * @param securityManager + */ + public FileSystemResourceFactory(File root, SecurityManager securityManager) { + setRoot(root); + setSecurityManager(securityManager); + } + + /** + * + * @param root - the root folder of the filesystem to expose. called webdav-fs + * @param securityManager + * @param contextPath - this is the leading part of URL's to ignore. For example if you're + * application is deployed to http://localhost:8080/webdav-fs, the context path should be + * webdav-fs + */ + public FileSystemResourceFactory(File root, SecurityManager securityManager, String contextPath) { + setRoot(root); + setSecurityManager(securityManager); + setContextPath(contextPath); + } + + public File getRoot() { + return root; + } + + public final void setRoot(File root) { + Logger.info(FileSystemResourceFactory.class, "root: " + root.getAbsolutePath()); + this.root = root; + if (!root.exists()) { + Logger.info(FileSystemResourceFactory.class, "Root folder does not exist: " + root.getAbsolutePath()); + } + if (!root.isDirectory()) { + Logger.info(FileSystemResourceFactory.class, "Root exists but is not a directory: " + root.getAbsolutePath()); + } + } + + @Override + public Resource getResource(String host, String url) { + Logger.info(FileSystemResourceFactory.class, "getResource: host: " + host + " - url:" + url); + url = stripContext(url); + File requested = resolvePath(root, url); + return resolveFile(host, requested); + } + + + public FsResource resolveFile(String host, File file) { + FsResource r; + if (!file.exists()) { + Logger.info(FileSystemResourceFactory.class, "file not found: " + file.getAbsolutePath()); + return null; + } else if (file.isDirectory()) { + r = new FsDirectoryResource(host, this, file, contentService); + } else { + r = new FsFileResource(host, this, file, contentService); + } + if (r != null) { + r.ssoPrefix = ssoPrefix; + } + return r; + } + + public File resolvePath(File root, String url) { + Path path = Path.path(url); + File f = root; + for (String s : path.getParts()) { + f = new File(f, s); + } + return f; + } + + public String getRealm(String host) { + return securityManager.getRealm(host); + } + + /** + * + * @return - the caching time for files + */ + public Long maxAgeSeconds(FsResource resource) { + return maxAgeSeconds; + } + + public void setSecurityManager(SecurityManager securityManager) { + if (securityManager != null) { + Logger.info(FileSystemResourceFactory.class, "securityManager: " + securityManager.getClass()); + } else { + Logger.info(FileSystemResourceFactory.class, "Setting null FsSecurityManager. This WILL cause null pointer exceptions"); + } + this.securityManager = securityManager; + } + + public SecurityManager getSecurityManager() { + return securityManager; + } + + public void setMaxAgeSeconds(Long maxAgeSeconds) { + this.maxAgeSeconds = maxAgeSeconds; + } + + public Long getMaxAgeSeconds() { + return maxAgeSeconds; + } + + public LockManager getLockManager() { + return lockManager; + } + + public void setLockManager(LockManager lockManager) { + this.lockManager = lockManager; + } + + public void setContextPath(String contextPath) { + this.contextPath = contextPath; + } + + public String getContextPath() { + return contextPath; + } + + /** + * Whether to generate an index page. + * + * @return + */ + public boolean isAllowDirectoryBrowsing() { + return allowDirectoryBrowsing; + } + + public void setAllowDirectoryBrowsing(boolean allowDirectoryBrowsing) { + this.allowDirectoryBrowsing = allowDirectoryBrowsing; + } + + /** + * if provided GET requests to a folder will redirect to a page of this name within the folder + * + * @return - E.g. index.html + */ + public String getDefaultPage() { + return defaultPage; + } + + public void setDefaultPage(String defaultPage) { + this.defaultPage = defaultPage; + } + + private String stripContext(String url) { + if (this.contextPath != null && contextPath.length() > 0) { + url = url.replaceFirst(contextPath, ""); + Logger.info(FileSystemResourceFactory.class, "stripped context: " + url); + return url; + } else { + return url; + } + } + + boolean isDigestAllowed() { + boolean b = digestAllowed && securityManager != null && securityManager.isDigestAllowed(); + + Logger.info(FileSystemResourceFactory.class, "isDigestAllowed: " + b); + + return b; + } + + public void setDigestAllowed(boolean digestAllowed) { + this.digestAllowed = digestAllowed; + } + + public void setSsoPrefix(String ssoPrefix) { + this.ssoPrefix = ssoPrefix; + } + + public String getSsoPrefix() { + return ssoPrefix; + } + + public FileContentService getContentService() { + return contentService; + } + + public void setContentService(FileContentService contentService) { + this.contentService = contentService; + } +} diff --git a/dotCMS/src/main/java/com/dotcms/webdav/FsDirectoryResource.java b/dotCMS/src/main/java/com/dotcms/webdav/FsDirectoryResource.java new file mode 100644 index 000000000000..a75ca4eb7f8b --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/webdav/FsDirectoryResource.java @@ -0,0 +1,263 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ + +package com.dotcms.webdav; + +import com.dotcms.repackage.com.bradmcevoy.http.*; +import com.dotcms.repackage.com.bradmcevoy.http.exceptions.NotAuthorizedException; +import com.dotmarketing.util.Logger; + + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; + +/** + * Represents a directory in a physical file system. + * + */ +public class FsDirectoryResource extends FsResource implements MakeCollectionableResource, PutableResource, CopyableResource, DeletableResource, MoveableResource, PropFindableResource, LockingCollectionResource, GetableResource { + + + + private final FileContentService contentService; + + public FsDirectoryResource(String host, FileSystemResourceFactory factory, File dir, FileContentService contentService) { + super(host, factory, dir); + this.contentService = contentService; + if (!dir.exists()) { + throw new IllegalArgumentException("Directory does not exist: " + dir.getAbsolutePath()); + } + if (!dir.isDirectory()) { + throw new IllegalArgumentException("Is not a directory: " + dir.getAbsolutePath()); + } + } + + @Override + public CollectionResource createCollection(String name) { + File fnew = new File(file, name); + boolean ok = fnew.mkdir(); + if (!ok) { + throw new RuntimeException("Failed to create: " + fnew.getAbsolutePath()); + } + return new FsDirectoryResource(host, factory, fnew, contentService); + } + + @Override + public Resource child(String name) { + File fchild = new File(file, name); + return factory.resolveFile(this.host, fchild); + + } + + @Override + public List getChildren() { + ArrayList list = new ArrayList(); + File[] files = this.file.listFiles(); + if (files != null) { + for (File fchild : files) { + FsResource res = factory.resolveFile(this.host, fchild); + if (res != null) { + list.add(res); + } else { + Logger.info(FileSystemResourceFactory.class,"Couldnt resolve file " + fchild.getAbsolutePath()); + } + } + } + return list; + } + + /** + * Will redirect if a default page has been specified on the factory + * + * @param request + * @return + */ + @Override + public String checkRedirect(Request request) { + if (factory.getDefaultPage() != null) { + return request.getAbsoluteUrl() + "/" + factory.getDefaultPage(); + } else { + return null; + } + } + + @Override + public Resource createNew(String name, InputStream in, Long length, String contentType) throws IOException { + File dest = new File(this.getFile(), name); + FileOutputStream out = null; + try { + out = new FileOutputStream(dest); + IOUtils.copy(in, out); + } finally { + IOUtils.closeQuietly(out); + } + // todo: ignores contentType + return factory.resolveFile(this.host, dest); + + } + + @Override + protected void doCopy(File dest) { + try { + FileUtils.copyDirectory(this.getFile(), dest); + } catch (IOException ex) { + throw new RuntimeException("Failed to copy to:" + dest.getAbsolutePath(), ex); + } + } + + @Override + public LockToken createAndLock(String name, LockTimeout timeout, LockInfo lockInfo) throws NotAuthorizedException { + File dest = new File(this.getFile(), name); + createEmptyFile(dest); + FsFileResource newRes = new FsFileResource(host, factory, dest, contentService); + LockResult res = newRes.lock(timeout, lockInfo); + return res.getLockToken(); + } + + private void createEmptyFile(File file) { + FileOutputStream fout = null; + try { + fout = new FileOutputStream(file); + } catch (IOException e) { + throw new RuntimeException(e); + } finally { + IOUtils.closeQuietly(fout); + } + } + + /** + * Will generate a listing of the contents of this directory, unless the + * factory's allowDirectoryBrowsing has been set to false. + * + * If so it will just output a message saying that access has been disabled. + * + * @param out + * @param range + * @param params + * @param contentType + * @throws IOException + * @throws NotAuthorizedException + */ + @Override + public void sendContent(OutputStream out, Range range, Map params, String contentType) throws IOException, NotAuthorizedException { + String subpath = getFile().getCanonicalPath().substring(factory.getRoot().getCanonicalPath().length()).replace('\\', '/'); + String uri = subpath; + //String uri = "/" + factory.getContextPath() + subpath; + XmlWriter w = new XmlWriter(out); + w.open("html"); + w.open("head"); + w.writeText("" + + "\n" + + " \n" + + " \n"); + + + + w.close("head"); + w.open("body"); + w.begin("h1").open().writeText(this.getName()).close(); + w.open("table"); + for (Resource r : getChildren()) { + w.open("tr"); + + w.open("td"); + String path = buildHref(uri, r.getName()); + w.begin("a").writeAtt("href", path).open().writeText(r.getName()).close(); + + w.begin("a").writeAtt("href", "#").writeAtt("onclick", "editDocument('" + path + "')").open().writeText("(edit with office)").close(); + + w.close("td"); + + w.begin("td").open().writeText(r.getModifiedDate() + "").close(); + w.close("tr"); + } + w.close("table"); + w.close("body"); + w.close("html"); + w.flush(); + } + + @Override + public Long getMaxAgeSeconds(Auth auth) { + return null; + } + + @Override + public String getContentType(String accepts) { + return "text/html"; + } + + @Override + public Long getContentLength() { + return null; + } + + private String buildHref(String uri, String name) { + /* TODO: Don't know why this has to be the request's absolute URL and the comment + doesn't help either. The HttpManager global variables are no longer available in + sendContent(), as it might be called after the call left HttpManager. + + // hmm, we're ignoring the path passed in uri. Dodgy... + String abUrl = HttpManager.request().getAbsoluteUrl(); + */ + String abUrl = uri; + + if (!abUrl.endsWith("/")) { + abUrl += "/"; + } + Logger.info(FileSystemResourceFactory.class,"url: " + abUrl); + if (ssoPrefix == null) { + return abUrl + name; + } else { + // This is to match up with the prefix set on SimpleSSOSessionProvider in MyCompanyDavServlet + String s = insertSsoPrefix(abUrl, ssoPrefix); + return s += name; + } + } + + public static String insertSsoPrefix(String abUrl, String prefix) { + // need to insert the ssoPrefix immediately after the host and port + int pos = abUrl.indexOf("/", 8); + String s = abUrl.substring(0, pos) + "/" + prefix; + s += abUrl.substring(pos); + return s; + } +} diff --git a/dotCMS/src/main/java/com/dotcms/webdav/FsFileResource.java b/dotCMS/src/main/java/com/dotcms/webdav/FsFileResource.java new file mode 100644 index 000000000000..7bd8636120a3 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/webdav/FsFileResource.java @@ -0,0 +1,133 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ + +package com.dotcms.webdav; + +import com.dotcms.repackage.com.bradmcevoy.common.ContentTypeUtils; +import com.dotcms.repackage.com.bradmcevoy.http.Auth; +import com.dotcms.repackage.com.bradmcevoy.http.CopyableResource; +import com.dotcms.repackage.com.bradmcevoy.http.DeletableResource; +import com.dotcms.repackage.com.bradmcevoy.http.GetableResource; +import com.dotcms.repackage.com.bradmcevoy.http.MoveableResource; +import com.dotcms.repackage.com.bradmcevoy.http.PropFindableResource; +import com.dotcms.repackage.com.bradmcevoy.http.PropPatchableResource; +import com.dotcms.repackage.com.bradmcevoy.http.Range; +import com.dotcms.repackage.com.bradmcevoy.http.Request; +import com.dotcms.repackage.com.bradmcevoy.http.entity.PartialEntity; +import com.dotcms.repackage.com.bradmcevoy.http.exceptions.NotFoundException; +import com.dotcms.repackage.com.bradmcevoy.http.webdav.PropPatchHandler.Fields; +import com.dotcms.repackage.com.bradmcevoy.io.ReadingException; +import com.dotcms.repackage.com.bradmcevoy.io.WritingException; +import com.dotcms.webdav.FileContentService; + + +import java.io.*; +import java.util.Map; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + */ +public class FsFileResource extends FsResource implements CopyableResource, DeletableResource, GetableResource, MoveableResource, PropFindableResource, PropPatchableResource { + + private static final Logger log = LoggerFactory.getLogger(FsFileResource.class); + + private final FileContentService contentService; + + /** + * + * @param host - the requested host. E.g. www.mycompany.com + * @param factory + * @param file + */ + public FsFileResource(String host, FileSystemResourceFactory factory, File file, FileContentService contentService) { + super(host, factory, file); + this.contentService = contentService; + } + + @Override + public Long getContentLength() { + return file.length(); + } + + @Override + public String getContentType(String preferredList) { + String mime = ContentTypeUtils.findContentTypes(this.file); + String s = ContentTypeUtils.findAcceptableContentType(mime, preferredList); + if (log.isTraceEnabled()) { + log.trace("getContentType: preferred: {} mime: {} selected: {}", new Object[]{preferredList, mime, s}); + } + return s; + } + + @Override + public String checkRedirect(Request arg0) { + return null; + } + + @Override + public void sendContent(OutputStream out, Range range, Map params, String contentType) throws IOException, NotFoundException { + try (InputStream in = contentService.getFileContent(file)){ + if (range != null) { + log.debug("sendContent: ranged content: " + file.getAbsolutePath()); + PartialEntity.writeRange(in, range, out); + } else { + log.debug("sendContent: send whole file " + file.getAbsolutePath()); + IOUtils.copy(in, out); + } + out.flush(); + } catch (FileNotFoundException e) { + throw new NotFoundException("Couldnt locate content"); + } catch (ReadingException e) { + throw new IOException(e); + } catch (WritingException e) { + throw new IOException(e); + } + } + + /** + * @{@inheritDoc} + */ + @Override + public Long getMaxAgeSeconds(Auth auth) { + return factory.maxAgeSeconds(this); + } + + /** + * @{@inheritDoc} + */ + @Override + protected void doCopy(File dest) { + try { + FileUtils.copyFile(file, dest); + } catch (IOException ex) { + throw new RuntimeException("Failed doing copy to: " + dest.getAbsolutePath(), ex); + } + } + + @Deprecated + @Override + public void setProperties(Fields fields) { + // MIL-50 + // not implemented. Just to keep MS Office sweet + } +} diff --git a/dotCMS/src/main/java/com/dotcms/webdav/FsMemoryLockManager.java b/dotCMS/src/main/java/com/dotcms/webdav/FsMemoryLockManager.java new file mode 100644 index 000000000000..581bb9f94273 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/webdav/FsMemoryLockManager.java @@ -0,0 +1,141 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ + +package com.dotcms.webdav; + +import com.dotcms.repackage.com.bradmcevoy.http.*; +import com.dotcms.repackage.com.bradmcevoy.http.exceptions.NotAuthorizedException; +import com.dotcms.repackage.com.ettrema.http.fs.LockManager; +import com.dotmarketing.util.Logger; + +import java.io.File; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + + +/** + * + */ +public class FsMemoryLockManager implements LockManager { + + + /** + * maps current locks by the file associated with the resource + */ + Map locksByFile; + Map locksByToken; + + public FsMemoryLockManager() { + locksByFile = new HashMap(); + locksByToken = new HashMap(); + } + + @Override + public synchronized LockResult lock( LockTimeout timeout, LockInfo lockInfo, LockableResource r ) { + FsResource resource = (FsResource) r; + LockToken currentLock = currentLock( resource ); + if( currentLock != null ) { + return LockResult.failed( LockResult.FailureReason.ALREADY_LOCKED ); + } + + LockToken newToken = new LockToken( UUID.randomUUID().toString(), lockInfo, timeout ); + CurrentLock newLock = new CurrentLock( resource.getFile(), newToken, lockInfo.lockedByUser ); + locksByFile.put( resource.getFile(), newLock ); + locksByToken.put( newToken.tokenId, newLock ); + return LockResult.success( newToken ); + } + + @Override + public synchronized LockResult refresh( String tokenId, LockableResource resource ) { + CurrentLock curLock = locksByToken.get( tokenId ); + if( curLock == null ) { + Logger.info(FileSystemResourceFactory.class, "can't refresh because no lock"); + return LockResult.failed( LockResult.FailureReason.PRECONDITION_FAILED ); + } else { + curLock.token.setFrom( new Date() ); + return LockResult.success( curLock.token ); + } + } + + @Override + public synchronized void unlock( String tokenId, LockableResource r ) throws NotAuthorizedException { + FsResource resource = (FsResource) r; + LockToken lockToken = currentLock( resource ); + if( lockToken == null ) { + Logger.info(FileSystemResourceFactory.class, "not locked" ); + return; + } + if( lockToken.tokenId.equals( tokenId ) ) { + removeLock( lockToken ); + } else { + throw new NotAuthorizedException( resource ); + } + } + + private LockToken currentLock( FsResource resource ) { + CurrentLock curLock = locksByFile.get( resource.getFile() ); + if( curLock == null ) return null; + LockToken token = curLock.token; + if( token.isExpired() ) { + removeLock( token ); + return null; + } else { + return token; + } + } + + private void removeLock( LockToken token ) { + Logger.info(FileSystemResourceFactory.class, "removeLock: " + token.tokenId ); + CurrentLock currentLock = locksByToken.get( token.tokenId ); + if( currentLock != null ) { + locksByFile.remove( currentLock.file ); + locksByToken.remove( currentLock.token.tokenId ); + } else { + Logger.info(FileSystemResourceFactory.class,"couldnt find lock: " + token.tokenId ); + } + } + + @Override + public LockToken getCurrentToken( LockableResource r ) { + FsResource resource = (FsResource) r; + CurrentLock lock = locksByFile.get( resource.getFile() ); + if( lock == null ) return null; + LockToken token = new LockToken(); + token.info = new LockInfo( LockInfo.LockScope.EXCLUSIVE, LockInfo.LockType.WRITE, lock.lockedByUser, LockInfo.LockDepth.ZERO ); + token.info.lockedByUser = lock.lockedByUser; + token.timeout = lock.token.timeout; + token.tokenId = lock.token.tokenId; + return token; + } + + class CurrentLock { + + final File file; + final LockToken token; + final String lockedByUser; + + public CurrentLock( File file, LockToken token, String lockedByUser ) { + this.file = file; + this.token = token; + this.lockedByUser = lockedByUser; + } + } +} diff --git a/dotCMS/src/main/java/com/dotcms/webdav/FsResource.java b/dotCMS/src/main/java/com/dotcms/webdav/FsResource.java new file mode 100644 index 000000000000..63898f411521 --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/webdav/FsResource.java @@ -0,0 +1,162 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ + +package com.dotcms.webdav; + +import com.dotcms.repackage.com.bradmcevoy.http.Auth; +import com.dotcms.repackage.com.bradmcevoy.http.CollectionResource; +import com.dotcms.repackage.com.bradmcevoy.http.CopyableResource; +import com.dotcms.repackage.com.bradmcevoy.http.DigestResource; +import com.dotcms.repackage.com.bradmcevoy.http.LockInfo; +import com.dotcms.repackage.com.bradmcevoy.http.LockResult; +import com.dotcms.repackage.com.bradmcevoy.http.LockTimeout; +import com.dotcms.repackage.com.bradmcevoy.http.LockToken; +import com.dotcms.repackage.com.bradmcevoy.http.LockableResource; +import com.dotcms.repackage.com.bradmcevoy.http.MoveableResource; +import com.dotcms.repackage.com.bradmcevoy.http.Request; +import com.dotcms.repackage.com.bradmcevoy.http.Request.Method; +import com.dotcms.repackage.com.bradmcevoy.http.Resource; +import com.dotcms.repackage.com.bradmcevoy.http.exceptions.NotAuthorizedException; +import com.dotcms.repackage.com.bradmcevoy.http.http11.auth.DigestResponse; +import com.dotmarketing.util.Logger; + + +import java.io.File; +import java.util.Date; + + +/** + * + */ +public abstract class FsResource implements Resource, MoveableResource, CopyableResource, LockableResource, DigestResource { + + + File file; + final FileSystemResourceFactory factory; + final String host; + String ssoPrefix; + + protected abstract void doCopy(File dest); + + public FsResource(String host, FileSystemResourceFactory factory, File file) { + this.host = host; + this.file = file; + this.factory = factory; + } + + public File getFile() { + return file; + } + + public String getUniqueId() { + String s = file.lastModified() + "_" + file.length() + "_" + file.getAbsolutePath(); + return s.hashCode() + ""; + } + + public String getName() { + return file.getName(); + } + + public Object authenticate(String user, String password) { + return factory.getSecurityManager().authenticate(user, password); + } + + public Object authenticate(DigestResponse digestRequest) { + return factory.getSecurityManager().authenticate(digestRequest); + } + + public boolean isDigestAllowed() { + return factory.isDigestAllowed(); + } + + public boolean authorise(Request request, Method method, Auth auth) { + boolean b = factory.getSecurityManager().authorise(request, method, auth, this); + Logger.info(FileSystemResourceFactory.class,"authorise: result=" + b); + + return b; + } + + public String getRealm() { + return factory.getRealm(this.host); + } + + public Date getModifiedDate() { + return new Date(file.lastModified()); + } + + public Date getCreateDate() { + return null; + } + + public int compareTo(Resource o) { + return this.getName().compareTo(o.getName()); + } + + public void moveTo(CollectionResource newParent, String newName) { + if (newParent instanceof FsDirectoryResource) { + FsDirectoryResource newFsParent = (FsDirectoryResource) newParent; + File dest = new File(newFsParent.getFile(), newName); + boolean ok = this.file.renameTo(dest); + if (!ok) { + throw new RuntimeException("Failed to move to: " + dest.getAbsolutePath()); + } + this.file = dest; + } else { + throw new RuntimeException("Destination is an unknown type. Must be a FsDirectoryResource, is a: " + newParent.getClass()); + } + } + + public void copyTo(CollectionResource newParent, String newName) { + if (newParent instanceof FsDirectoryResource) { + FsDirectoryResource newFsParent = (FsDirectoryResource) newParent; + File dest = new File(newFsParent.getFile(), newName); + doCopy(dest); + } else { + throw new RuntimeException("Destination is an unknown type. Must be a FsDirectoryResource, is a: " + newParent.getClass()); + } + } + + public void delete() { + boolean ok = file.delete(); + if (!ok) { + throw new RuntimeException("Failed to delete"); + } + } + + public LockResult lock(LockTimeout timeout, LockInfo lockInfo) throws NotAuthorizedException { + return factory.getLockManager().lock(timeout, lockInfo, this); + } + + public LockResult refreshLock(String token) throws NotAuthorizedException { + return factory.getLockManager().refresh(token, this); + } + + public void unlock(String tokenId) throws NotAuthorizedException { + factory.getLockManager().unlock(tokenId, this); + } + + public LockToken getCurrentLock() { + if (factory.getLockManager() != null) { + return factory.getLockManager().getCurrentToken(this); + } else { + Logger.info(FileSystemResourceFactory.class,"getCurrentLock called, but no lock manager: file: " + file.getAbsolutePath()); + return null; + } + } +} diff --git a/dotCMS/src/main/java/com/dotcms/webdav/SimpleFileContentService.java b/dotCMS/src/main/java/com/dotcms/webdav/SimpleFileContentService.java new file mode 100644 index 000000000000..e8972b3f8e4c --- /dev/null +++ b/dotCMS/src/main/java/com/dotcms/webdav/SimpleFileContentService.java @@ -0,0 +1,49 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ + +package com.dotcms.webdav; + +import java.io.*; +import org.apache.commons.io.IOUtils; + + + +/** + * + * @author brad + */ +public class SimpleFileContentService implements FileContentService { + + @Override + public void setFileContent(File file, InputStream in) throws FileNotFoundException, IOException { + FileOutputStream out = null; + try { + out = new FileOutputStream(file); + IOUtils.copy(in, out); + } finally { + IOUtils.closeQuietly(out); + } + } + + @Override + public InputStream getFileContent(File file) throws FileNotFoundException { + FileInputStream fin = new FileInputStream(file); + return fin; + } +} diff --git a/dotCMS/src/main/java/com/dotmarketing/beans/Inode.java b/dotCMS/src/main/java/com/dotmarketing/beans/Inode.java index 8ce3d885b77f..ac7eac04da2a 100644 --- a/dotCMS/src/main/java/com/dotmarketing/beans/Inode.java +++ b/dotCMS/src/main/java/com/dotmarketing/beans/Inode.java @@ -518,19 +518,7 @@ public boolean hasChildren() { */ public boolean hasParents() { - HibernateUtil dh = new HibernateUtil(); - String query = "select count(*) from " + Inode.class.getName() - + " inode where inode.inode in (select tree.parent from " - + Tree.class.getName() + " tree where tree.child = " - + this.inode + ")"; - List results = new ArrayList(); - try { - dh.setQuery(query); - results = dh.list(); - } catch (DotHibernateException e) { - Logger.error(this.getClass(), e.getMessage(), e); - } - return ((Integer) results.get(0)).intValue() > 0; + return TreeFactory.getTreesByChild(this.inode).size()>0; } public boolean equals(Object other) { diff --git a/dotCMS/src/main/java/com/dotmarketing/beans/MultiTree.java b/dotCMS/src/main/java/com/dotmarketing/beans/MultiTree.java index 3e20585d1c0b..d7a4c0d081c8 100644 --- a/dotCMS/src/main/java/com/dotmarketing/beans/MultiTree.java +++ b/dotCMS/src/main/java/com/dotmarketing/beans/MultiTree.java @@ -1,20 +1,22 @@ package com.dotmarketing.beans; -import java.io.Serializable; - import com.dotcms.repackage.org.apache.commons.lang.builder.EqualsBuilder; import com.dotcms.repackage.org.apache.commons.lang.builder.HashCodeBuilder; import com.dotcms.repackage.org.apache.commons.lang.builder.ToStringBuilder; +import java.io.Serializable; + /** * - * @author maria + * @author maria */ public class MultiTree implements Serializable { private static final long serialVersionUID = 1L; - /** identifier field */ + public static final String LEGACY_RELATION_TYPE = "LEGACY_RELATION_TYPE"; + + /** identifier field */ private String parent1; /** identifier field */ @@ -30,52 +32,66 @@ public class MultiTree implements Serializable { private int treeOrder; /** full constructor */ - - public MultiTree(String parent1, String parent2, String child, java.lang.String relationType, int treeOrder) { - - this.parent1 = parent1; - this.parent2 = parent2; + public MultiTree(String htmlPage, String container, String child, String relationType, int treeOrder) { + this.parent1 = htmlPage; + this.parent2 = container; this.child = child; - this.relationType = relationType; - this.treeOrder = treeOrder; + this.relationType = (relationType == null) ? LEGACY_RELATION_TYPE : relationType; + this.treeOrder = (treeOrder < 0) ? 0 : treeOrder; } /** default constructor */ public MultiTree() { - - this.parent1 = ""; - this.parent2 = ""; - this.child = ""; + this(null, null, null, LEGACY_RELATION_TYPE, 0); } /** minimal constructor */ - public MultiTree(String parent1, String parent2, String child) { - this.parent1 = parent1; - this.parent2 = parent2; - this.child = child; + public MultiTree(String htmlPage, String container, String child) { + this(htmlPage, container, child, LEGACY_RELATION_TYPE, 0); } + /** + * + * {@link #getContentlet()} + */ + @Deprecated public String getChild() { + return getContentlet(); + } + + public String getContentlet() { return this.child; } - public void setChild(String child) { - this.child = child; + + @Deprecated + public MultiTree setChild(String child) { + return setContentlet(child); } + public java.lang.String getRelationType() { return this.relationType; } - public void setRelationType(java.lang.String relationType) { - this.relationType = relationType; + public MultiTree setContentlet(String contentlet) { + this.child = contentlet; + return new MultiTree(this.parent1, this.parent2, contentlet, this.relationType, this.treeOrder); } + + public MultiTree setRelationType(java.lang.String relationType) { + this.relationType = (relationType == null) ? LEGACY_RELATION_TYPE : relationType; + return new MultiTree(this.parent1, this.parent2, this.child, relationType, this.treeOrder); + } + public int getTreeOrder() { return this.treeOrder; } - public void setTreeOrder(int treeOrder) { + public MultiTree setTreeOrder(int treeOrder) { + treeOrder = (treeOrder < 0) ? 0 : treeOrder; this.treeOrder = treeOrder; + return new MultiTree(this.parent1, this.parent2, this.child, this.relationType, treeOrder); } public String toString() { @@ -83,44 +99,99 @@ public String toString() { } public boolean equals(Object other) { - if ( !(other instanceof MultiTree) ) return false; + if (!(other instanceof MultiTree)) + return false; MultiTree castOther = (MultiTree) other; - return new EqualsBuilder() - .append(this.parent1, castOther.parent1) + return new EqualsBuilder().append(this.parent1, castOther.parent1) .append(this.parent2, castOther.parent2) .append(this.child, castOther.child) + .append(this.relationType, castOther.relationType) + .isEquals(); + } + + public boolean equalsWithOrder(Object other) { + if (!(other instanceof MultiTree)) + return false; + MultiTree castOther = (MultiTree) other; + return new EqualsBuilder().append(this.parent1, castOther.parent1) + .append(this.parent2, castOther.parent2) + .append(this.child, castOther.child) + .append(this.relationType, castOther.relationType) + .append(this.treeOrder, castOther.treeOrder) .isEquals(); } - public int hashCode() { - return new HashCodeBuilder() - .append(parent1) + return new HashCodeBuilder().append(parent1) .append(parent2) .append(child) .toHashCode(); } - /** - * @return Returns the parent1. - */ - public String getParent1() { - return parent1; - } - /** - * @param parent1 The parent1 to set. - */ - public void setParent1(String parent1) { - this.parent1 = parent1; - } - /** - * @return Returns the parent2. - */ - public String getParent2() { - return parent2; - } - /** - * @param parent2 The parent2 to set. - */ - public void setParent2(String parent2) { - this.parent2 = parent2; - } -} \ No newline at end of file + + /** + * + * {@link #getHtmlPage()} + */ + @Deprecated + public String getParent1() { + return parent1; + } + + /** + * + * {@link #getContainer()} + */ + @Deprecated + public String getParent2() { + return parent2; + } + + /** + * @return Returns the htmlPage. + */ + public String getHtmlPage() { + return parent1; + } + + /** + * + * {@link #setHtmlPage(String)} + */ + @Deprecated + public MultiTree setParent1(String htmlPage) { + return setHtmlPage(htmlPage); + } + + /** + * + * {@link #setContainer(String)} + */ + @Deprecated + public MultiTree setParent2(String container) { + return setContainer(container); + } + + /** + * @param htmlPage The htmlPage to set. + */ + public MultiTree setHtmlPage(String htmlPage) { + return new MultiTree(htmlPage, this.parent2, this.child, this.relationType, this.treeOrder); + } + + /** + * @return Returns the container. + */ + public String getContainer() { + return parent2; + } + + /** + * @param container The container to set. + */ + public MultiTree setContainer(String container) { + this.parent2 = container; + return new MultiTree(this.parent1, container, this.child, this.relationType, this.treeOrder); + } + + + +} diff --git a/dotCMS/src/main/java/com/dotmarketing/beans/TemplateContainers.java b/dotCMS/src/main/java/com/dotmarketing/beans/TemplateContainers.java deleted file mode 100644 index 861d3bf5f43b..000000000000 --- a/dotCMS/src/main/java/com/dotmarketing/beans/TemplateContainers.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.dotmarketing.beans; - -public class TemplateContainers { - - private String id; - - private String templateId; - - private String containerId; - - public TemplateContainers(){ - } - - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - public String getTemplateId() { - return templateId; - } - public void setTemplateId(String templateId) { - this.templateId = templateId; - } - public String getContainerId() { - return containerId; - } - public void setContainerId(String containerId) { - this.containerId = containerId; - } -} diff --git a/dotCMS/src/main/java/com/dotmarketing/business/BaseWebAssetAPI.java b/dotCMS/src/main/java/com/dotmarketing/business/BaseWebAssetAPI.java index 40d6a78f8c58..40a54d07bd81 100644 --- a/dotCMS/src/main/java/com/dotmarketing/business/BaseWebAssetAPI.java +++ b/dotCMS/src/main/java/com/dotmarketing/business/BaseWebAssetAPI.java @@ -4,7 +4,10 @@ package com.dotmarketing.business; import com.dotcms.business.WrapInTransaction; +import com.dotcms.rendering.velocity.services.ContainerLoader; +import com.dotcms.rendering.velocity.services.TemplateLoader; import com.dotcms.repackage.com.google.common.collect.Lists; + import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.Inode; @@ -23,12 +26,9 @@ import com.dotmarketing.portlets.containers.model.Container; import com.dotmarketing.portlets.folders.model.Folder; import com.dotmarketing.portlets.templates.model.Template; -import com.dotmarketing.services.ContainerServices; -import com.dotmarketing.services.TemplateServices; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; -import com.liferay.portal.model.User; import java.util.ArrayList; import java.util.Calendar; @@ -37,6 +37,8 @@ import java.util.Map; import java.util.UUID; +import com.liferay.portal.model.User; + /** * @author jtesser * All methods in the BaseWebAssetAPI should be protected or private. The BaseWebAssetAPI is intended to be extended by other APIs for WebAsset Objects. @@ -283,13 +285,13 @@ public static boolean deleteAsset(WebAsset currWebAsset) throws DotSecurityExcep dc.addParam(currWebAsset.getIdentifier()); dc.loadResult(); - ContainerServices.unpublishContainerFile((Container)currWebAsset); + new ContainerLoader().invalidate((Container)currWebAsset); CacheLocator.getContainerCache().remove(currWebAsset.getInode()); } else if(currWebAsset instanceof Template) { - TemplateServices.unpublishTemplateFile((Template)currWebAsset); - APILocator.getTemplateAPI().associateContainers(new ArrayList(), (Template)currWebAsset); + new TemplateLoader().invalidate((Template)currWebAsset); + CacheLocator.getTemplateCache().remove(currWebAsset.getInode()); } @@ -317,7 +319,7 @@ else if(currWebAsset instanceof Template) List multiTrees = new ArrayList(); if (currWebAsset instanceof Container) { - multiTrees = MultiTreeFactory.getMultiTree(identifier); + multiTrees = MultiTreeFactory.getMultiTrees(identifier); } if(UtilMethods.isSet(multiTrees)) { diff --git a/dotCMS/src/main/java/com/dotmarketing/business/CacheLocator.java b/dotCMS/src/main/java/com/dotmarketing/business/CacheLocator.java index 152fc3a67978..7c9b7478443e 100644 --- a/dotCMS/src/main/java/com/dotmarketing/business/CacheLocator.java +++ b/dotCMS/src/main/java/com/dotmarketing/business/CacheLocator.java @@ -17,6 +17,10 @@ import com.dotcms.publisher.assets.business.PushedAssetsCacheImpl; import com.dotcms.publisher.endpoint.business.PublishingEndPointCache; import com.dotcms.publisher.endpoint.business.PublishingEndPointCacheImpl; +import com.dotcms.rendering.velocity.services.DotResourceCache; +import com.dotcms.rendering.velocity.viewtools.navigation.NavToolCache; +import com.dotcms.rendering.velocity.viewtools.navigation.NavToolCacheImpl; + import com.dotmarketing.business.cache.provider.CacheProviderStats; import com.dotmarketing.business.cache.transport.CacheTransport; import com.dotmarketing.cache.ContentTypeCache; @@ -64,9 +68,7 @@ import com.dotmarketing.util.Config; import com.dotmarketing.util.Logger; import com.dotmarketing.util.WebKeys; -import com.dotmarketing.velocity.DotResourceCache; -import com.dotmarketing.viewtools.navigation.NavToolCache; -import com.dotmarketing.viewtools.navigation.NavToolCacheImpl; + import java.util.List; import java.util.Set; @@ -193,10 +195,10 @@ public static ContentletCache getContentletCache() { return (ContentletCache)getInstance(CacheIndex.Contentlet); } - public static DotResourceCache getVeloctyResourceCache(){ - return (DotResourceCache)getInstance(CacheIndex.Velocity); - } + public static DotResourceCache getVeloctyResourceCache(){ + return (DotResourceCache)getInstance(CacheIndex.Velocity2); + } public static LogMapperCache getLogMapperCache () { return ( LogMapperCache ) getInstance( CacheIndex.LogMapper ); } @@ -276,8 +278,9 @@ public static IndiciesCache getIndiciesCache() { return (IndiciesCache)getInstance(CacheIndex.Indicies); } + public static NavToolCache getNavToolCache() { - return (NavToolCache)getInstance(CacheIndex.NavTool); + return (NavToolCache) getInstance(CacheIndex.NavTool); } public static PublishingEndPointCache getPublishingEndPointCache() { @@ -420,6 +423,8 @@ enum CacheIndex VanityURLCache("Vanity URL Cache"), ContentTypeCache("Legacy Content Type Cache"), ContentTypeCache2("New Content Type Cache"), + Velocity2("Velocity2"), + NavTool2("Navigation Tool2"), KeyValueCache("Key/Value Cache"); Cachable create() { @@ -431,7 +436,7 @@ Cachable create() { case TagInode: return new TagInodeCacheImpl(); case Role: return new RoleCacheImpl(); case Contentlet: return new ContentletCacheImpl(); - case Velocity : return new DotResourceCache(); + case Velocity2 : return new DotResourceCache(); case Relationship: return new RelationshipCacheImpl(); case LogMapper: return new LogMapperCacheImpl(); case Plugin : return new PluginCacheImpl(); @@ -453,7 +458,7 @@ Cachable create() { case FolderCache : return new FolderCacheImpl(); case WorkflowCache : return new WorkflowCacheImpl(); case Indicies: return new IndiciesCacheImpl(); - case NavTool: return new NavToolCacheImpl(); + case NavTool: return new NavToolCacheImpl(); case PublishingEndPoint: return new PublishingEndPointCacheImpl(); case PushedAssets: return new PushedAssetsCacheImpl(); case CSSCache: return new CSSCacheImpl(); diff --git a/dotCMS/src/main/java/com/dotmarketing/business/IdentifierFactoryImpl.java b/dotCMS/src/main/java/com/dotmarketing/business/IdentifierFactoryImpl.java index 13857ebeb2c5..14744dbeb3fa 100644 --- a/dotCMS/src/main/java/com/dotmarketing/business/IdentifierFactoryImpl.java +++ b/dotCMS/src/main/java/com/dotmarketing/business/IdentifierFactoryImpl.java @@ -64,8 +64,10 @@ protected List findByURIPattern(final String assetType, String uri, dc.addParam(assetType); + return TransformerLocator.createIdentifierTransformer(dc.loadObjectResults()).asList(); + } @Override @@ -154,9 +156,11 @@ protected Identifier findByURI(final String siteId, String uri) throws DotDataEx List results = null; + results = TransformerLocator.createIdentifierTransformer(dc.loadObjectResults()).asList(); + if (results != null && !results.isEmpty()){ identifier = results.get(0); } @@ -182,6 +186,7 @@ protected List findByParentPath(final String siteId, String parent_p dc.addParam(parent_path); dc.addParam(siteId); + return TransformerLocator.createIdentifierTransformer(dc.loadObjectResults()).asList(); } @@ -198,9 +203,11 @@ protected Identifier loadFromDb(String identifier) throws DotDataException, DotS List results = null; + results = TransformerLocator.createIdentifierTransformer(dc.loadObjectResults()).asList(); + return (results != null && !results.isEmpty())?results.get(0):null; } @@ -380,7 +387,6 @@ protected List loadAllIdentifiers() throws DotDataException { DotConnect dc = new DotConnect(); dc.setSQL("select * from identifier"); - return TransformerLocator.createIdentifierTransformer(dc.loadObjectResults()).asList(); } diff --git a/dotCMS/src/main/java/com/dotmarketing/business/PermissionBitFactoryImpl.java b/dotCMS/src/main/java/com/dotmarketing/business/PermissionBitFactoryImpl.java index 1e7f4dde4146..d87a35722073 100644 --- a/dotCMS/src/main/java/com/dotmarketing/business/PermissionBitFactoryImpl.java +++ b/dotCMS/src/main/java/com/dotmarketing/business/PermissionBitFactoryImpl.java @@ -7,6 +7,8 @@ import com.dotcms.contenttype.model.type.BaseContentType; import com.dotcms.contenttype.model.type.ContentType; import com.dotcms.contenttype.transform.contenttype.StructureTransformer; +import com.dotcms.rendering.velocity.viewtools.navigation.NavResult; + import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.Inode; @@ -44,7 +46,7 @@ import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; -import com.dotmarketing.viewtools.navigation.NavResult; + import com.liferay.portal.model.User; import java.lang.reflect.Field; import java.util.ArrayList; diff --git a/dotCMS/src/main/java/com/dotmarketing/business/cache/provider/redis/RedisProvider.java b/dotCMS/src/main/java/com/dotmarketing/business/cache/provider/redis/RedisProvider.java index f2e9ba951540..ccf2efc78a2d 100644 --- a/dotCMS/src/main/java/com/dotmarketing/business/cache/provider/redis/RedisProvider.java +++ b/dotCMS/src/main/java/com/dotmarketing/business/cache/provider/redis/RedisProvider.java @@ -7,7 +7,7 @@ import com.dotmarketing.util.Config; import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; -import com.dotmarketing.velocity.DotResourceCache; + import redis.clients.jedis.*; import java.io.*; diff --git a/dotCMS/src/main/java/com/dotmarketing/business/web/HostWebAPI.java b/dotCMS/src/main/java/com/dotmarketing/business/web/HostWebAPI.java index 44d2ff5861dd..804582af7ec3 100644 --- a/dotCMS/src/main/java/com/dotmarketing/business/web/HostWebAPI.java +++ b/dotCMS/src/main/java/com/dotmarketing/business/web/HostWebAPI.java @@ -28,5 +28,7 @@ public interface HostWebAPI extends HostAPI { public Host getCurrentHost(HttpServletRequest req) throws DotDataException, DotSecurityException, PortalException, SystemException; public Host getHost(HttpServletRequest request); + + public Host getCurrentHostNoThrow(HttpServletRequest request); } diff --git a/dotCMS/src/main/java/com/dotmarketing/business/web/HostWebAPIImpl.java b/dotCMS/src/main/java/com/dotmarketing/business/web/HostWebAPIImpl.java index 1d472dc68c0f..7ed7857fd121 100644 --- a/dotCMS/src/main/java/com/dotmarketing/business/web/HostWebAPIImpl.java +++ b/dotCMS/src/main/java/com/dotmarketing/business/web/HostWebAPIImpl.java @@ -12,8 +12,10 @@ import com.dotmarketing.beans.Host; import com.dotmarketing.business.DotStateException; import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotRuntimeException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.contentlet.business.HostAPIImpl; +import com.dotmarketing.util.PageMode; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; import com.liferay.portal.PortalException; @@ -56,21 +58,14 @@ public Host getCurrentHost(HttpServletRequest request) throws DotDataException, UserWebAPI userWebAPI = WebAPILocator.getUserWebAPI(); User systemUser = userWebAPI.getSystemUser(); boolean respectFrontendRoles = !userWebAPI.isLoggedToBackend(request); - boolean adminMode = false; - boolean previewMode = false; - boolean editMode = false; - - if(session != null) { - adminMode = (session.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null); - previewMode = (session.getAttribute(com.dotmarketing.util.WebKeys.PREVIEW_MODE_SESSION) != null && adminMode); - editMode = (session.getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) != null && adminMode); - } + + PageMode mode = PageMode.get(request); String pageHostId = request.getParameter("host_id"); - if(pageHostId != null && (editMode || previewMode)) { - host = find(pageHostId, systemUser, respectFrontendRoles); + if(pageHostId != null && !mode.showLive) { + host = find(pageHostId, systemUser, respectFrontendRoles); } else { - if(session != null && adminMode && session.getAttribute(WebKeys.CURRENT_HOST) != null) { + if(session != null && mode.isAdmin && session.getAttribute(WebKeys.CURRENT_HOST) != null) { host = (Host) session.getAttribute(WebKeys.CURRENT_HOST); } else if(request.getAttribute(WebKeys.CURRENT_HOST) != null) { host = (Host) request.getAttribute(WebKeys.CURRENT_HOST); @@ -83,10 +78,19 @@ public Host getCurrentHost(HttpServletRequest request) throws DotDataException, } request.setAttribute(WebKeys.CURRENT_HOST, host); - if(session != null && adminMode) { + if(session != null && mode.isAdmin) { session.setAttribute(WebKeys.CURRENT_HOST, host); } return host; } - + + @Override + public Host getCurrentHostNoThrow(HttpServletRequest request) { + try { + return getCurrentHost(request); + } + catch(Exception e) { + throw new DotRuntimeException(e); + } + } } diff --git a/dotCMS/src/main/java/com/dotmarketing/business/web/LanguageWebAPIImpl.java b/dotCMS/src/main/java/com/dotmarketing/business/web/LanguageWebAPIImpl.java index e2284bf86dfa..ce0170d3799a 100644 --- a/dotCMS/src/main/java/com/dotmarketing/business/web/LanguageWebAPIImpl.java +++ b/dotCMS/src/main/java/com/dotmarketing/business/web/LanguageWebAPIImpl.java @@ -12,6 +12,7 @@ import com.dotmarketing.portlets.languagesmanager.business.LanguageAPI; import com.dotmarketing.portlets.languagesmanager.model.Language; import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; import com.liferay.portal.struts.MultiMessageResources; @@ -134,7 +135,8 @@ public Language getLanguage(HttpServletRequest httpRequest) { //only set in session if we are not in a timemachine if(sessionOpt.getAttribute("tm_lang")==null){ sessionOpt.setAttribute(WebKeys.HTMLPAGE_LANGUAGE, String.valueOf(future.getId())); - boolean ADMIN_MODE = (sessionOpt.getAttribute(WebKeys.ADMIN_MODE_SESSION) != null); + boolean ADMIN_MODE = PageMode.get(httpRequest).isAdmin; + if (ADMIN_MODE == false || httpRequest.getParameter("leftMenu") == null) { sessionOpt.setAttribute(WebKeys.Globals_FRONTEND_LOCALE_KEY, locale); httpRequest.setAttribute(WebKeys.Globals_FRONTEND_LOCALE_KEY, locale); diff --git a/dotCMS/src/main/java/com/dotmarketing/cache/LegacyContentTypeCacheImpl.java b/dotCMS/src/main/java/com/dotmarketing/cache/LegacyContentTypeCacheImpl.java index 2a444984c6f0..e79a3f28cb54 100644 --- a/dotCMS/src/main/java/com/dotmarketing/cache/LegacyContentTypeCacheImpl.java +++ b/dotCMS/src/main/java/com/dotmarketing/cache/LegacyContentTypeCacheImpl.java @@ -5,6 +5,7 @@ import com.dotcms.contenttype.model.type.ContentType; import com.dotcms.contenttype.transform.contenttype.StructureTransformer; +import com.dotcms.rendering.velocity.services.ContentTypeLoader; import com.dotcms.repackage.com.google.common.collect.ImmutableMap; import com.dotcms.repackage.jersey.repackaged.com.google.common.collect.ImmutableList; import com.dotmarketing.business.APILocator; @@ -130,6 +131,7 @@ public boolean hasStructureByInode(String inode) { public void remove(Structure st) { + new ContentTypeLoader().invalidate(st); ContentType type = new StructureTransformer(st).from(); super.remove(type); } diff --git a/dotCMS/src/main/java/com/dotmarketing/cms/comment/action/CommentsAction.java b/dotCMS/src/main/java/com/dotmarketing/cms/comment/action/CommentsAction.java index e34405c3e318..f794941cf407 100644 --- a/dotCMS/src/main/java/com/dotmarketing/cms/comment/action/CommentsAction.java +++ b/dotCMS/src/main/java/com/dotmarketing/cms/comment/action/CommentsAction.java @@ -52,7 +52,7 @@ import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.VelocityUtil; import com.dotmarketing.util.WebKeys; -import com.dotmarketing.viewtools.CommentsWebAPI; +import com.dotcms.rendering.velocity.viewtools.CommentsWebAPI; import com.liferay.portal.model.Company; import com.liferay.portal.model.User; import com.liferay.util.Html; diff --git a/dotCMS/src/main/java/com/dotmarketing/cms/urlmap/filters/URLMapFilter.java b/dotCMS/src/main/java/com/dotmarketing/cms/urlmap/filters/URLMapFilter.java index 4874815cf176..4f03df03e067 100644 --- a/dotCMS/src/main/java/com/dotmarketing/cms/urlmap/filters/URLMapFilter.java +++ b/dotCMS/src/main/java/com/dotmarketing/cms/urlmap/filters/URLMapFilter.java @@ -35,6 +35,7 @@ import com.dotmarketing.tag.model.Tag; import com.dotmarketing.util.Config; import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; import com.dotmarketing.util.RegEX; import com.dotmarketing.util.RegExMatch; import com.dotmarketing.util.TagUtil; @@ -142,12 +143,8 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) return; } if (RegEX.contains(url, mastRegEx)) { - boolean ADMIN_MODE = (optSession != null - && optSession.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) - != null); - boolean EDIT_MODE = ((optSession != null - && optSession.getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) - != null) && ADMIN_MODE); + boolean ADMIN_MODE = PageMode.get(request) .isAdmin; + boolean EDIT_MODE = PageMode.get(request) == PageMode.EDIT_MODE; Structure structure = null; diff --git a/dotCMS/src/main/java/com/dotmarketing/db/test/DataSourcesForTesting.java b/dotCMS/src/main/java/com/dotmarketing/db/test/DataSourcesForTesting.java index 1931ff680b8e..41ae5bc35971 100644 --- a/dotCMS/src/main/java/com/dotmarketing/db/test/DataSourcesForTesting.java +++ b/dotCMS/src/main/java/com/dotmarketing/db/test/DataSourcesForTesting.java @@ -12,7 +12,7 @@ import com.dotcms.repackage.org.apache.commons.dbcp.BasicDataSource; import com.dotmarketing.business.DotStateException; -import com.dotmarketing.viewtools.XmlTool; +import com.dotcms.rendering.velocity.viewtools.XmlTool; import com.liferay.util.FileUtil; public class DataSourcesForTesting { diff --git a/dotCMS/src/main/java/com/dotmarketing/factories/DBTreeTransformer.java b/dotCMS/src/main/java/com/dotmarketing/factories/DBTreeTransformer.java new file mode 100644 index 000000000000..3c2583359757 --- /dev/null +++ b/dotCMS/src/main/java/com/dotmarketing/factories/DBTreeTransformer.java @@ -0,0 +1,52 @@ +package com.dotmarketing.factories; + +import com.dotmarketing.beans.Tree; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import com.google.common.collect.Lists; + + +public class DBTreeTransformer{ + + private final List trees; + + public DBTreeTransformer (List>list ){ + this.trees = list + .stream() + .map(row -> toTree(row)) + .collect(Collectors.toList()); + + } + + public Tree tree() { + return trees.stream().findFirst().orElse(null); + + } + public List trees() { + return trees; + + } + + + + public DBTreeTransformer (Map map){ + this.trees = Lists.newArrayList(toTree(map)); + + + } + + private Tree toTree (Map map){ + + Tree tree=new Tree(); + tree.setParent((String)map.getOrDefault("parent", null)); + tree.setChild((String)map.getOrDefault("child", null)); + tree.setRelationType((String)map.getOrDefault("relation_type", null)); + tree.setTreeOrder((Integer)map.getOrDefault("tree_order", 0)); + + return tree; + } + +} \ No newline at end of file diff --git a/dotCMS/src/main/java/com/dotmarketing/factories/EmailFactory.java b/dotCMS/src/main/java/com/dotmarketing/factories/EmailFactory.java index cb96dbe0006a..c8b0d506a311 100644 --- a/dotCMS/src/main/java/com/dotmarketing/factories/EmailFactory.java +++ b/dotCMS/src/main/java/com/dotmarketing/factories/EmailFactory.java @@ -24,6 +24,7 @@ import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; import com.dotmarketing.util.Mailer; +import com.dotmarketing.util.PageMode; import com.dotmarketing.util.Parameter; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.VelocityUtil; @@ -226,7 +227,7 @@ public static boolean sendForgotPassword(User user, String newPassword, String h try { String message = ""; try { - Template t = UtilMethods.getVelocityTemplate("live/"+ idInode+ languageStr + "."+ Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION")); + Template t = UtilMethods.getVelocityTemplate( PageMode.LIVE.name() +"/"+ idInode+ languageStr + "."+ Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION")); t.merge(context, writer); Logger .debug(EmailFactory.class, "writer:" @@ -587,7 +588,7 @@ public static Map buildEmail(String templatePath, Host host, Map try { if(InodeUtils.isSet(idInode)) { - t = UtilMethods.getVelocityTemplate("live/"+ idInode + languageStr + "."+ Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION")); + t = UtilMethods.getVelocityTemplate(PageMode.LIVE.name() +File.separator+ idInode + languageStr + "."+ Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION")); } else { t = UtilMethods.getVelocityTemplate(templatePath); } diff --git a/dotCMS/src/main/java/com/dotmarketing/factories/MultiTreeAPI.java b/dotCMS/src/main/java/com/dotmarketing/factories/MultiTreeAPI.java new file mode 100644 index 000000000000..eca795473dd4 --- /dev/null +++ b/dotCMS/src/main/java/com/dotmarketing/factories/MultiTreeAPI.java @@ -0,0 +1,84 @@ +package com.dotmarketing.factories; + +import com.dotmarketing.beans.MultiTree; +import com.dotmarketing.business.APILocator; +import com.dotmarketing.business.DotStateException; +import com.dotmarketing.business.VersionableAPI; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.portlets.containers.model.Container; +import com.dotmarketing.portlets.contentlet.business.ContentletAPI; +import com.dotmarketing.portlets.contentlet.model.Contentlet; +import com.dotmarketing.portlets.htmlpageasset.model.HTMLPageAsset; +import com.dotmarketing.portlets.htmlpageasset.model.IHTMLPage; +import com.dotmarketing.portlets.templates.model.Template; +import com.dotmarketing.util.Logger; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.Table; +import com.liferay.portal.model.User; + +public class MultiTreeAPI { + + VersionableAPI vers = APILocator.getVersionableAPI(); + ContentletAPI conAPI = APILocator.getContentletAPI(); + User sys = APILocator.systemUser(); + + + + public Table> getPageMultiTrees(final IHTMLPage page, final boolean liveMode) throws DotDataException, DotSecurityException { + + Table> pageContents = HashBasedTable.create(); + List multis = MultiTreeFactory.getMultiTrees(page.getIdentifier()); + for (MultiTree t : multis) { + Container container = (liveMode) ? (Container) vers.findLiveVersion(t.getContainer(), sys, false) + : (Container) vers.findWorkingVersion(t.getContainer(), sys, false); + if(container==null && ! liveMode) { + // MultiTreeFactory.deleteMultiTree(t); + continue; + } + Contentlet contentlet = null; + try { + contentlet = conAPI.findContentletByIdentifier(t.getContentlet(), liveMode, -1, sys, false); + }catch(Exception e){ + Logger.warn(this.getClass(), "invalid contentlet on multitree:" + t); + } + if(contentlet==null ) { + // MultiTreeFactory.deleteMultiTree(t); + continue; + }; + Set myContents = pageContents.contains(t.getContainer(), t.getRelationType()) + ? pageContents.get(t.getContainer(), t.getRelationType()) + : new LinkedHashSet<>(); + if(myContents.size()< container.getMaxContentlets()) { + myContents.add(t.getContentlet()); + } + else { + // MultiTreeFactory.deleteMultiTree(t); + } + + pageContents.put(t.getContainer(), t.getRelationType(), myContents); + + } + + return pageContents; + } + + + + + + + + + + + + + +} diff --git a/dotCMS/src/main/java/com/dotmarketing/factories/MultiTreeFactory.java b/dotCMS/src/main/java/com/dotmarketing/factories/MultiTreeFactory.java index 25cd0a4efda1..6666956ace98 100644 --- a/dotCMS/src/main/java/com/dotmarketing/factories/MultiTreeFactory.java +++ b/dotCMS/src/main/java/com/dotmarketing/factories/MultiTreeFactory.java @@ -1,26 +1,15 @@ package com.dotmarketing.factories; -import com.dotmarketing.util.UtilMethods; -import com.dotcms.util.transform.DBTransformer; -import com.dotcms.util.transform.TransformerLocator; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; + +import com.dotcms.business.WrapInTransaction; +import com.dotcms.rendering.velocity.services.PageLoader; import com.dotmarketing.beans.Identifier; -import com.dotmarketing.beans.Inode; import com.dotmarketing.beans.MultiTree; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.DotStateException; import com.dotmarketing.common.db.DotConnect; -import com.dotmarketing.db.HibernateUtil; import com.dotmarketing.exception.DotDataException; -import com.dotmarketing.exception.DotHibernateException; import com.dotmarketing.exception.DotRuntimeException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.containers.model.Container; @@ -28,756 +17,348 @@ import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.contentlet.model.ContentletVersionInfo; import com.dotmarketing.portlets.htmlpageasset.model.IHTMLPage; -import com.dotmarketing.services.PageServices; -import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; + +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + import com.google.common.collect.Lists; -import org.jetbrains.annotations.NotNull; /** - * This class provides utility routines to interact with the Multi-Tree - * structures in the system. A Multi-Tree represents the relationship between a - * Legacy or Content Page, a container, and a contentlet. + * This class provides utility routines to interact with the Multi-Tree structures in the system. A + * Multi-Tree represents the relationship between a Legacy or Content Page, a container, and a + * contentlet. *

- * Therefore, the content of a page can be described as the sum of several - * Multi-Tree records which represent each piece of information contained in it. + * Therefore, the content of a page can be described as the sum of several Multi-Tree records which + * represent each piece of information contained in it. *

* * @author will */ public class MultiTreeFactory { - - private static final String DELETE_MULTITREE_ERROR_MSG = "Deleting MultiTree Object failed:"; - private static final String SAVE_MULTITREE_ERROR_MSG = "Saving MultiTree Object failed:"; - //MultiTree fields - private static final String CHILD = "child"; - private static final String PARENT1 = "parent1"; - private static final String PARENT2 = "parent2"; - private static final String RELATION_TYPE = "relation_type"; - private static final String TREE_ORDER = "tree_order"; - public static void deleteMultiTree(Object o1, Object o2, Object o3) { - Inode inode1 = (Inode) o1; - Inode inode2 = (Inode) o2; - Inode inode3 = (Inode) o3; - try { + final static String DELETE_SQL = "delete from multi_tree where parent1=? and parent2=? and child=? and relation_type = ?"; + final static String SELECT_SQL = + "select * from multi_tree where parent1 = ? and parent2 = ? and child = ? and relation_type = ?"; + final static String INSERT_SQL = + "insert into multi_tree (parent1, parent2, child, relation_type, tree_order ) values (?,?,?,?,?) "; - DotConnect db = new DotConnect(); - db.setSQL("delete from multi_tree where parent1 =? and parent2 = ? and child = ? "); - db.addParam(inode1.getInode()); - db.addParam(inode2.getInode()); - db.addParam(inode3.getInode()); - db.getResult(); + final static String SELECT_BY_ONE_PARENT = "select * from multi_tree where parent1 = ? or parent2 = ? "; + final static String SELECT_BY_TWO_PARENTS = "select * from multi_tree where parent1 = ? and parent2 = ? order by tree_order"; + final static String SELECT_ALL = "select * from multi_tree "; + final static String SELECT_BY_CHILD = "select * from multi_tree where child = ? order by parent1, parent2, relation_type "; + final static String SELECT_BY_PARENTS_AND_RELATIONS = + " select * from multi_tree where parent1 = ? and parent2 = ? and relation_type = ? order by tree_order"; - updateHTMLPageVersionTS(inode1.getInode()); - refreshPageInCache(inode1.getInode()); - - } - catch (Exception e) { - throw new DotRuntimeException(e.getMessage()); - } - - } + public static void deleteMultiTree(final MultiTree mTree) throws DotDataException { + _dbDelete(mTree); + updateHTMLPageVersionTS(mTree.getHtmlPage()); + refreshPageInCache(mTree.getHtmlPage()); + } + public static void deleteMultiTree(final List mTree) throws DotDataException { + for(MultiTree tree : mTree) { + deleteMultiTree(tree); + } + } + + public static void deleteMultiTreeByParent(String pageOrContainer) throws DotDataException { + deleteMultiTree(getMultiTrees(pageOrContainer)); + } + + public static void deleteMultiTreeByChild(String contentIdentifier) throws DotDataException { + deleteMultiTree(getMultiTreesByChild(contentIdentifier)); + } /** - * Just invoking deleteMultiTreeByParent1 with null language. - * @throws DotSecurityException + * Deletes multi-tree relationship given a MultiTree object. It also updates the version_ts of + * all versions of the htmlpage passed in (multiTree.parent1) + * + * @param multiTree + * @throws DotDataException + * @throws DotSecurityException * - * @see MultiTreeFactory#deleteMultiTreeByParent1(Identifier parent, Long - * languageId) */ - public static void deleteMultiTreeByParent1(Contentlet contentlet) throws DotDataException, DotSecurityException { - Identifier identifier = new Identifier(); - identifier.setId(contentlet.getIdentifier()); + private static void _dbDelete(final MultiTree mTree) throws DotDataException { + + DotConnect db = new DotConnect().setSQL(DELETE_SQL) + .addParam(mTree.getHtmlPage()) + .addParam(mTree.getContainer()) + .addParam(mTree.getContentlet()) + .addParam(mTree.getRelationType()); + db.loadResult(); - deleteMultiTreeByParent1(identifier, contentlet.getLanguageId()); } - /** - * Just invoking deleteMultiTreeByParent1 with null language. - * @throws DotSecurityException - * - * @see MultiTreeFactory#deleteMultiTreeByParent1(Identifier parent, Long - * languageId) - */ - public static void deleteMultiTreeByParent1(Identifier parent) throws DotDataException, DotSecurityException { - deleteMultiTreeByParent1(parent, null); + + + public static MultiTree getMultiTree(Identifier htmlPage, Identifier container, Identifier childContent, String relationType) + throws DotDataException { + return getMultiTree(htmlPage.getId(), container.getId(), childContent.getId(), relationType); } - /** - * Just invoking deleteMultiTreeByParent1 and create an identifier method - * with the contentlet identifier id - * @throws DotSecurityException - * - * @see MultiTreeFactory#deleteMultiTreeByParent1(Identifier parent, Long - * languageId) - */ - public static void deleteMultiTreeByParent1(Contentlet contentlet, Long languageId) - throws DotDataException, DotSecurityException { - Identifier identifier = new Identifier(); - identifier.setId(contentlet.getIdentifier()); - deleteMultiTreeByParent1(identifier, languageId); + public static MultiTree getMultiTree(String htmlPage, String container, String childContent, String relationType) + throws DotDataException { + + DotConnect db = new DotConnect().setSQL(SELECT_SQL) + .addParam(htmlPage) + .addParam(container) + .addParam(childContent) + .addParam(relationType); + db.loadResult(); + + return dbToMultiTree(db.loadObjectResults()).stream() + .findFirst() + .orElse(null); + } - /** - * Deletes multi-tree relationships by identifier and language. - *

- * This method will remove all rows where parent1 equals to identifier - * parameter where the identifier has same language as languageId parameter. - *

- *

- * NOTE: This delete assumes that we are only using identifiers in - * multi-tree table - *

- * - * @param parent - * identifier - * @param languageId - * (optional parameter) if null it will delete all rows where - * parent1 equals identifier same as - * {@link #deleteMultiTreeFromContentletPage(String)}; otherwise - * it will search for those identifiers that match with the - * language and delete them from multi-tree table - * @throws DotDataException - * @throws DotSecurityException - * - * @see MultiTreeFactory#updateHTMLPageVersionTS(String) - * @see MultiTreeFactory#refreshPageInCache(String) - */ - public static void deleteMultiTreeByParent1(Identifier parent, Long languageId) - throws DotDataException, DotSecurityException { - DotConnect db = new DotConnect(); + public static java.util.List getMultiTrees(Identifier parent) throws DotDataException { + return getMultiTrees(parent.getId()); + } + + public static java.util.List getMultiTrees(Identifier htmlPage, Identifier container) throws DotDataException { + return getMultiTrees(htmlPage.getId(), container.getId()); + } + public static java.util.List getMultiTrees(String parentInode) throws DotDataException { + + DotConnect db = new DotConnect().setSQL(SELECT_BY_ONE_PARENT) + .addParam(parentInode) + .addParam(parentInode); + + return dbToMultiTree(db.loadObjectResults()); + + } + + public static java.util.List getAllMultiTrees() { try { - if (languageId == null) { - db.executeStatement("DELETE FROM multi_tree WHERE parent1 = '" + parent.getId() - + "';"); - updateHTMLPageVersionTS(parent.getId()); - refreshPageInCache(parent.getId()); - return; - } + DotConnect db = new DotConnect().setSQL(SELECT_ALL); + + return dbToMultiTree(db.loadObjectResults()); - // -- Query example -- - // DELETE FROM multi_tree m - // WHERE m.parent1 = '6c2a7d84-a16d-4c12-8830-9d203c3dcc4c' AND - // m.child IN (SELECT c.identifier FROM multi_tree AS m1 - // INNER JOIN contentlet_version_info AS c - // ON m1.child = c.identifier - // WHERE m1.parent1 = '6c2a7d84-a16d-4c12-8830-9d203c3dcc4c' AND - // c.lang = 2); - // -- End of query example -- - StringBuilder query = new StringBuilder("DELETE FROM multi_tree m WHERE ") - .append("m.parent1 = '").append(parent.getId()).append("' ") - .append("AND m.child IN (SELECT c.identifier FROM multi_tree AS m1 ") - .append("INNER JOIN contentlet_version_info AS c ON m1.child = c.identifier ") - .append("WHERE m1.parent1 = '").append(parent.getId()).append("' ") - .append("AND c.lang = ").append(languageId).append(");"); - - db.executeStatement(query.toString()); - - updateHTMLPageVersionTS(parent.getId()); - refreshPageInCache(parent.getId()); - - } catch (SQLException e) { - throw new DotDataException(DELETE_MULTITREE_ERROR_MSG, e); - } catch (DotContentletStateException e) { - throw new DotContentletStateException(DELETE_MULTITREE_ERROR_MSG, e); - } catch (DotSecurityException e) { - throw new DotSecurityException(DELETE_MULTITREE_ERROR_MSG, e); + } catch (Exception e) { + Logger.error(MultiTreeFactory.class, "getMultiTree failed:" + e, e); + throw new DotRuntimeException(e.toString()); } } - + + public static java.util.List getMultiTrees(String htmlPage, String container, String relationType) { + try { + + DotConnect db = new DotConnect().setSQL(SELECT_BY_PARENTS_AND_RELATIONS) + .addParam(htmlPage) + .addParam(container) + .addParam(relationType); + return dbToMultiTree(db.loadObjectResults()); + } catch (Exception e) { + Logger.error(MultiTreeFactory.class, "getMultiTree failed:" + e, e); + throw new DotRuntimeException(e.toString()); + } + } + + public static java.util.List getMultiTrees(IHTMLPage htmlPage, Container container) throws DotDataException { + return getMultiTrees(htmlPage.getIdentifier(), container.getIdentifier()); + } + + + public static java.util.List getMultiTrees(String htmlPage, String container) throws DotDataException { + + DotConnect db = new DotConnect().setSQL(SELECT_BY_TWO_PARENTS) + .addParam(htmlPage) + .addParam(container); + return dbToMultiTree(db.loadObjectResults()); + + } + + public static java.util.List getMultiTrees(IHTMLPage htmlPage, Container container, String relationType) { + return getMultiTrees(htmlPage.getIdentifier(), container.getIdentifier(), relationType); + } + + + public static java.util.List getContainerMultiTrees(String containerIdentifier) throws DotDataException { + return getMultiTrees(containerIdentifier); + } + + + public static java.util.List getMultiTreesByChild(String contentIdentifier) throws DotDataException { + + DotConnect db = new DotConnect().setSQL(SELECT_BY_CHILD) + .addParam(contentIdentifier); + + return dbToMultiTree(db.loadObjectResults()); + + } + + + + @WrapInTransaction + public static void saveMultiTree(MultiTree mTree) throws DotDataException { + + _reorder(mTree); + updateHTMLPageVersionTS(mTree.getHtmlPage()); + refreshPageInCache(mTree.getHtmlPage()); + + } + /** - * Deletes multi-tree relationship given a MultiTree object. - * It also updates the version_ts of all versions of the htmlpage passed in (multiTree.parent1) - * - * @param multiTree + * Saves a multi-tree + *
    + *
  1. The identifier of the Content Page.
  2. + *
  3. The identifier of the container in the page.
  4. + *
  5. The identifier of the contentlet itself.
  6. + *
  7. The type of content relation.
  8. + *
  9. The order in which this construct is added to the database.
  10. + *
+ * + * @param o - The multi-tree structure. * @throws DotDataException - * @throws DotSecurityException - * + * @throws DotSecurityException */ - public static void deleteMultiTree(MultiTree multiTree) throws DotDataException, DotSecurityException { - try { - String id = multiTree.getParent1(); - HibernateUtil.delete(multiTree); - updateHTMLPageVersionTS(id); - refreshPageInCache(id); - return; - } catch (DotHibernateException e) { - Logger.error(MultiTreeFactory.class, DELETE_MULTITREE_ERROR_MSG + e, e); - throw new DotRuntimeException(e.getMessage()); - } catch (DotStateException e) { - Logger.error(MultiTreeFactory.class, DELETE_MULTITREE_ERROR_MSG + e, e); - throw new DotStateException(e.getMessage()); - } catch (DotDataException e) { - Logger.error(MultiTreeFactory.class, DELETE_MULTITREE_ERROR_MSG + e, e); - throw new DotDataException(e.getMessage()); - } catch (DotSecurityException e) { - Logger.error(MultiTreeFactory.class, DELETE_MULTITREE_ERROR_MSG + e, e); - throw new DotSecurityException(e.getMessage()); - } - } - - public static boolean existsMultiTree(Object o1, Object o2, Object o3) { - Inode inode1 = (Inode) o1; - Inode inode2 = (Inode) o2; - Inode inode3 = (Inode) o3; - - try { - - DotConnect db = new DotConnect(); - db.setSQL("select count(*) mycount from multi_tree where parent1 =? and parent2 = ? and child = ? "); - db.addParam(inode1.getInode()); - db.addParam(inode2.getInode()); - db.addParam(inode3.getInode()); - - int count = db.getInt("mycount"); - - return (count > 0); - } - catch (Exception e) { - throw new DotRuntimeException(e.getMessage()); - } - } - - public static MultiTree getMultiTree(Identifier parent1, Identifier parent2, Identifier child) { - try { - HibernateUtil dh = new HibernateUtil(MultiTree.class); - dh.setQuery("from multi_tree in class com.dotmarketing.beans.MultiTree where parent1 = ? and parent2 = ? and child = ?"); - dh.setParam(parent1.getInode()); - dh.setParam(parent2.getInode()); - dh.setParam(child.getInode()); - - return (MultiTree) dh.load(); - } catch (Exception e) { - Logger.warn(MultiTreeFactory.class, "getMultiTree failed:" + e, e); - } - return new MultiTree(); - } - - @SuppressWarnings("unchecked") - public static java.util.List getMultiTree(Inode parent) { - try { - HibernateUtil dh = new HibernateUtil(MultiTree.class); - dh.setQuery("from multi_tree in class com.dotmarketing.beans.MultiTree where parent1 = ? or parent2 = ? "); - dh.setParam(parent.getInode()); - dh.setParam(parent.getInode()); - - return dh.list(); - - } catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getMultiTree failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - } - - public static java.util.List getMultiTree(Identifier parent) { - try { - HibernateUtil dh = new HibernateUtil(MultiTree.class); - dh.setQuery("from multi_tree in class com.dotmarketing.beans.MultiTree where parent1 = ? or parent2 = ? "); - dh.setParam(parent.getInode()); - dh.setParam(parent.getInode()); - - return dh.list(); - - } catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getMultiTree failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - } - - @SuppressWarnings("unchecked") - public static java.util.List getMultiTree(String parentInode) { - try { - HibernateUtil dh = new HibernateUtil(MultiTree.class); - dh.setQuery("from multi_tree in class com.dotmarketing.beans.MultiTree where parent1 = ? or parent2 = ? "); - dh.setParam(parentInode); - dh.setParam(parentInode); - - return dh.list(); - - } catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getMultiTree failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - } - @SuppressWarnings("unchecked") - public static java.util.List getMultiTree(IHTMLPage htmlPage, Container container) { - try { - HibernateUtil dh = new HibernateUtil(MultiTree.class); - dh.setQuery("from multi_tree in class com.dotmarketing.beans.MultiTree where parent1 = ? and parent2 = ? "); - dh.setParam(htmlPage.getIdentifier()); - dh.setParam(container.getIdentifier()); - - return dh.list(); - - } catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getMultiTree failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - } - /** - * Get the multi_tree by both parents given a containerId - * - * @author Graziano Aliberti - Engineering Ingegneria Informatica S.p.a - * - * Jun 26, 2013 - 12:34:29 PM - */ - @SuppressWarnings("unchecked") - public static java.util.List getContainerMultiTree(String containerIdentifier) { - try { - HibernateUtil dh = new HibernateUtil(MultiTree.class); - dh.setQuery("from multi_tree in class com.dotmarketing.beans.MultiTree where parent1 = ? or parent2 = ? or child = ?"); - dh.setParam(containerIdentifier); - dh.setParam(containerIdentifier); - dh.setParam(containerIdentifier); - - return dh.list(); - - } catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getContainerMultiTree failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - } - - /** - * Get a list of MultiTree for Contentlets using a specific Structure and specific Container - * @param containerIdentifier - * @param structureIdentifier - * @return List of MultiTree - */ - public static List getContainerStructureMultiTree(String containerIdentifier, String structureInode) { - try { - DotConnect dc = new DotConnect(); - StringBuilder query = new StringBuilder(); - query.append("SELECT mt.* FROM multi_tree mt JOIN contentlet c ON c.identifier = mt.child "); - query.append("WHERE mt.parent2 = ? AND c.structure_inode = ? "); - - dc.setSQL(query.toString()); - dc.addParam(containerIdentifier); - dc.addParam(structureInode); - - List ret = new ArrayList<>(); - List> results = dc.loadResults(); - if(results != null && !results.isEmpty()){ - for (Map map : results) { - ret.add(getMultiTreeFields(map)); - } - } - - return ret; - - } catch (DotDataException e) { - Logger.error(MultiTreeFactory.class, "getContainerStructureMultiTree failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - } - - @NotNull - private static MultiTree getMultiTreeFields(Map map) { - MultiTree mt = new MultiTree(); - mt.setChild(map.get(CHILD)); - mt.setParent1(map.get(PARENT1)); - mt.setParent2(map.get(PARENT2)); - if (UtilMethods.isSet(map.get(RELATION_TYPE))) { - mt.setRelationType(map.get(RELATION_TYPE)); - } - if (UtilMethods.isSet(map.get(TREE_ORDER))) { - mt.setTreeOrder(Integer.parseInt(map.get(TREE_ORDER))); - } - return mt; - } - - @SuppressWarnings("unchecked") - public static java.util.List getMultiTreeByChild(String contentIdentifier) { - try { - HibernateUtil dh = new HibernateUtil(MultiTree.class); - dh.setQuery("from multi_tree in class com.dotmarketing.beans.MultiTree where child = ? "); - dh.setParam(contentIdentifier); - - return dh.list(); - - } catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getMultiTreeByChild failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - } - - /** - * Saves a multi-tree construct using the default language in the system. A - * muti-tree is usually composed of the following five parts: - *
    - *
  1. The identifier of the Content Page.
  2. - *
  3. The identifier of the container in the page.
  4. - *
  5. The identifier of the contentlet itself.
  6. - *
  7. The type of content relation.
  8. - *
  9. The order in which this construct is added to the database.
  10. - *
- * - * @param o - * - The multi-tree structure. - * @throws DotSecurityException - */ - public static void saveMultiTree(MultiTree o) throws DotSecurityException { - saveMultiTree(o, APILocator.getLanguageAPI().getDefaultLanguage() - .getId()); - } - - /** - * Saves a Multi-Tree construct using a passed in language id in the system. A - * Muti-Tree is usually composed of the following five parts: - *
    - *
  1. The identifier of the Content Page.
  2. - *
  3. The identifier of the container in the page.
  4. - *
  5. The identifier of the contentlet itself.
  6. - *
  7. The type of content relation.
  8. - *
  9. The order in which this construct is added to the database.
  10. - *
- * - * @param o - * - The Multi-Tree structure. - * @param languageId - * - The language Id of the content page this contentlet will be - * associated to. - * @throws DotSecurityException - */ - public static void saveMultiTree(MultiTree o, long languageId) throws DotSecurityException { - if(!InodeUtils.isSet(o.getChild()) | !InodeUtils.isSet(o.getParent1()) || !InodeUtils.isSet(o.getParent2())) throw new DotRuntimeException("Make sure your Multitree is set!"); - try { - String id = o.getParent1(); - HibernateUtil.saveOrUpdate(o); - updateHTMLPageVersionTS(id); - refreshPageInCache(id); - } catch (DotHibernateException e) { - Logger.error(MultiTreeFactory.class, SAVE_MULTITREE_ERROR_MSG + e, e); - throw new DotRuntimeException(e.getMessage()); - } catch (DotStateException e) { - Logger.error(MultiTreeFactory.class, SAVE_MULTITREE_ERROR_MSG + e, e); - throw new DotRuntimeException(e.getMessage()); - } catch (DotDataException e) { - Logger.error(MultiTreeFactory.class, SAVE_MULTITREE_ERROR_MSG + e, e); - throw new DotRuntimeException(e.getMessage()); - } catch (DotSecurityException e) { - Logger.error(MultiTreeFactory.class, SAVE_MULTITREE_ERROR_MSG + e, e); - throw new DotSecurityException(e.getMessage()); + @WrapInTransaction + public static void saveMultiTrees(List mTrees) throws DotDataException { + if (mTrees == null || mTrees.isEmpty()) + throw new DotDataException("empty list passed in"); + int i = 0; + for (MultiTree tree : mTrees) { + _dbUpsert(tree.setTreeOrder(i++)); } - } - - public static java.util.List getChildrenClass(Inode p1, Inode p2, Class c) { - - try { - String tableName = ((Inode) c.newInstance()).getType(); - HibernateUtil dh = new HibernateUtil(c); - - String sql = "SELECT {" + tableName + ".*} from " + tableName + " " + tableName + ", multi_tree multi_tree, inode "+ tableName +"_1_ where multi_tree.parent1 = ? and multi_tree.parent2 = ? and multi_tree.child = " + tableName + ".inode and " + tableName + "_1_.inode = " + tableName + ".inode order by multi_tree.tree_order"; - Logger.debug(MultiTreeFactory.class, "getChildrenClass\n " + sql+ "\n"); - dh.setSQLQuery(sql); - Logger.debug(MultiTreeFactory.class, "inode p1: " + p1.getInode() + "\n"); - Logger.debug(MultiTreeFactory.class, "inode p2: " + p2.getInode() + "\n"); - - dh.setParam(p1.getInode()); - dh.setParam(p2.getInode()); - - return dh.list(); - } - catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getChildrenClass failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - } - - public static java.util.List getChildrenClass(Identifier p1, Identifier p2, Class c) { - - try { - String tableName = ""; - StringBuilder sql = new StringBuilder(); - - if(c.getName().contains("Identifier")){ - tableName = "identifier"; - }else{ - tableName = ((Inode) c.newInstance()).getType(); - } - DotConnect dc = new DotConnect(); - - if(tableName.equalsIgnoreCase("identifier")){ - sql.append("SELECT "); - sql.append(tableName); - sql.append(".* from "); - sql.append(tableName); - sql.append(", multi_tree multi_tree ") - .append(" where multi_tree.parent1 = ? and multi_tree.parent2 = ? and multi_tree.child = "); - sql.append(tableName); - sql.append(".id order by multi_tree.tree_order"); - }else { - sql.append("SELECT "); - sql.append(tableName); - sql.append(".* from "); - sql.append(tableName); - sql.append(", multi_tree multi_tree, inode "); - sql.append(tableName); - sql.append("_1_ where multi_tree.parent1 = ? and multi_tree.parent2 = ? and multi_tree.child = "); - sql.append(tableName); - sql.append(".inode and "); - sql.append(tableName); - sql.append("_1_.inode = "); - sql.append(tableName); - sql.append(".inode order by multi_tree.tree_order"); - } - - Logger.debug(MultiTreeFactory.class, "getChildrenClass\n " + sql+ "\n"); - - dc.setSQL(sql.toString()); - - Logger.debug(MultiTreeFactory.class, "inode p1: " + p1.getId() + "\n"); - Logger.debug(MultiTreeFactory.class, "inode p2: " + p2.getId() + "\n"); - - dc.addParam(p1.getId()); - dc.addParam(p2.getId()); - - DBTransformer transformer = TransformerLocator - .createDBTransformer(dc.loadObjectResults(), c); - - if (transformer != null){ - return transformer.asList(); - } - } - catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getChildrenClass failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - - return Collections.emptyList(); - } - - public static java.util.List getChildrenClass(Inode p1, Inode p2, Class c, String orderBy) { - try { - String tableName = ((Inode) c.newInstance()).getType(); - HibernateUtil dh = new HibernateUtil(c); - - String sql = "SELECT {" + tableName + ".*} from " + tableName + " " + tableName + ", multi_tree multi_tree, inode "+ tableName +"_1_ where multi_tree.parent1 = ? and multi_tree.parent2 = ? and multi_tree.child = " + tableName + ".inode and " + tableName + "_1_.inode = " + tableName + ".inode order by " + orderBy; - Logger.debug(MultiTreeFactory.class, "hibernateUtilSQL:getChildrenClass\n " + sql+ "\n"); - dh.setSQLQuery(sql); - Logger.debug(MultiTreeFactory.class, "inode p1: " + p1.getInode() + "\n"); - Logger.debug(MultiTreeFactory.class, "inode p2: " + p2.getInode() + "\n"); - - dh.setParam(p1.getInode()); - dh.setParam(p2.getInode()); - - return dh.list(); - } - catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getChildrenClass failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - } - - public static java.util.List getChildrenClassByCondition(Inode p1, Inode p2, Class c, String condition) { - try { - String tableName = ((Inode) c.newInstance()).getType(); - HibernateUtil dh = new HibernateUtil(c); - - String sql = "SELECT {" + tableName + ".*} from " + tableName + " " + tableName + ", multi_tree multi_tree, inode "+ tableName +"_1_ where multi_tree.parent1 = ? and multi_tree.parent2 = ? and multi_tree.child = " + tableName + ".inode and " + tableName + "_1_.inode = " + tableName + ".inode and " + condition; - Logger.debug(MultiTreeFactory.class, "hibernateUtilSQL:getChildrenClassByCondition\n " + sql); - dh.setSQLQuery(sql); - Logger.debug(MultiTreeFactory.class, "inode p1: " + p1.getInode() + "\n"); - Logger.debug(MultiTreeFactory.class, "inode p2: " + p2.getInode() + "\n"); - - dh.setParam(p1.getInode()); - dh.setParam(p2.getInode()); - - return dh.list(); - } - catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getChildrenClassByCondition failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - - //return new java.util.ArrayList(); - } - - public static java.util.List getChildrenClassByCondition(String p1, String p2, Class c, String condition) { - try { - String tableName = ((Inode) c.newInstance()).getType(); - HibernateUtil dh = new HibernateUtil(c); - - String sql = "SELECT {" + tableName + ".*} from " + tableName + " " + tableName + ", multi_tree multi_tree, inode "+ tableName +"_1_ where multi_tree.parent1 = ? and multi_tree.parent2 = ? and multi_tree.child = " + tableName + ".inode and " + tableName + "_1_.inode = " + tableName + ".inode and " + condition; - Logger.debug(MultiTreeFactory.class, "hibernateUtilSQL:getChildrenClassByCondition\n " + sql); - dh.setSQLQuery(sql); - Logger.debug(MultiTreeFactory.class, "inode p1: " + p1 + "\n"); - Logger.debug(MultiTreeFactory.class, "inode p2: " + p2 + "\n"); - - dh.setParam(p1); - dh.setParam(p2); - - return dh.list(); - } - catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getChildrenClassByCondition failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - } - - public static java.util.List getChildrenClassByConditionAndOrderBy(Inode p1, Inode p2, Class c, String condition, String orderby) { - try { - - String tableName = ((Inode) c.newInstance()).getType(); - HibernateUtil dh = new HibernateUtil(c); - - String sql = "SELECT {" + tableName + ".*} from " + tableName + " " + tableName + ", multi_tree multi_tree, inode "+ tableName +"_1_ where multi_tree.parent1 = ? and multi_tree.parent2 = ? and multi_tree.child = " + tableName + ".inode and " + tableName + "_1_.inode = " + tableName + ".inode and " + condition + " order by " + orderby; - Logger.debug(MultiTreeFactory.class, "hibernateUtilSQL:getChildrenClassByConditionAndOrderBy\n " + sql+ "\n"); - dh.setSQLQuery(sql); - Logger.debug(MultiTreeFactory.class, "inode p1: " + p1.getInode() + "\n"); - Logger.debug(MultiTreeFactory.class, "inode p2: " + p2.getInode() + "\n"); - - dh.setParam(p1.getInode()); - dh.setParam(p2.getInode()); - - return dh.list(); - } - catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getChildrenClassByConditionAndOrderBy failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - - //return new java.util.ArrayList(); - } - - public static java.util.List getChildrenClassByConditionAndOrderBy(String p1, String p2, Class c, String condition, String orderby) { - try { - - String tableName = ((Inode) c.newInstance()).getType(); - HibernateUtil dh = new HibernateUtil(c); - - String sql = "SELECT {" + tableName + ".*} from " + tableName + " " + tableName + ", multi_tree multi_tree, inode "+ tableName +"_1_ where multi_tree.parent1 = ? and multi_tree.parent2 = ? and multi_tree.child = " + tableName + ".inode and " + tableName + "_1_.inode = " + tableName + ".inode and " + condition + " order by " + orderby; - Logger.debug(MultiTreeFactory.class, "hibernateUtilSQL:getChildrenClassByConditionAndOrderBy\n " + sql+ "\n"); - dh.setSQLQuery(sql); - Logger.debug(MultiTreeFactory.class, "inode p1: " + p1 + "\n"); - Logger.debug(MultiTreeFactory.class, "inode p2: " + p2 + "\n"); - - dh.setParam(p1); - dh.setParam(p2); - - return dh.list(); - } - catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getChildrenClassByConditionAndOrderBy failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - } - - public static java.util.List getChildrenClassByOrder(Inode p1, Inode p2, Class c, String order) { - try { - String tableName = ((Inode) c.newInstance()).getType(); - HibernateUtil dh = new HibernateUtil(c); - - String sql = "SELECT {" + tableName + ".*} from " + tableName + " " + tableName + ", multi_tree multi_tree, inode "+ tableName +"_1_ where multi_tree.parent1 = ? and multi_tree.parent2 = ? and multi_tree.child = " + tableName + ".inode and " + tableName + "_1_.inode = " + tableName + ".inode order by " + order; - - Logger.debug(MultiTreeFactory.class, "hibernateUtilSQL:getChildrenClassByOrder\n " + sql); - dh.setSQLQuery(sql); - Logger.debug(MultiTreeFactory.class, "inode p1: " + p1.getInode() + "\n"); - Logger.debug(MultiTreeFactory.class, "inode p2: " + p2.getInode() + "\n"); - Logger.debug(MultiTreeFactory.class, "order: " + order + "\n"); - - dh.setParam(p1.getInode()); - dh.setParam(p2.getInode()); - - return dh.list(); - } - catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getChildrenClassByOrder failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - } - - - public static java.util.List getParentsOfClassByCondition(Inode p, Class c, String condition) { - try { - String tableName = ((Inode) c.newInstance()).getType(); - HibernateUtil dh = new HibernateUtil(c); - - String sql = "SELECT {" + tableName + ".*} from " + tableName + " " + tableName + ", multi_tree multi_tree, inode "+ tableName +"_1_ where multi_tree.child = ? and (multi_tree.parent1 = " + tableName + ".inode or multi_tree.parent2 = " + tableName + ".inode) and " + tableName + "_1_.inode = " + tableName + ".inode and " + condition; - Logger.debug(MultiTreeFactory.class, "hibernateUtilSQL:getParentsOfClassByCondition\n " + sql); - Logger.debug(MultiTreeFactory.class, "inode: " + p.getInode() + "\n"); - Logger.debug(MultiTreeFactory.class, "condition: " + condition + "\n"); - dh.setSQLQuery(sql); - dh.setParam(p.getInode()); - - return dh.list(); - } - catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getParentsOfClassByCondition failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - } - - public static java.util.List getParentsOfClass(Inode p, Class c) { - try { - - String tableName = ((Inode) c.newInstance()).getType(); - HibernateUtil dh = new HibernateUtil(c); - String sql = "SELECT {" + tableName + ".*} from " + tableName + " " + tableName + ", multi_tree multi_tree, inode "+ tableName +"_1_ where multi_tree.child = ? and (multi_tree.parent1 = " + tableName + ".inode or multi_tree.parent2 = " + tableName + ".inode) and " + tableName + "_1_.inode = " + tableName + ".inode "; - Logger.debug(MultiTreeFactory.class, "hibernateUtilSQL:getParentOfClass:\n " + sql+ "\n"); - dh.setSQLQuery(sql); - dh.setParam(p.getInode()); - Logger.debug(MultiTreeFactory.class, "inode: " + p.getInode() + "\n"); - return dh.list(); - } - catch (Exception e) { - Logger.error(MultiTreeFactory.class, "getParentsOfClass failed:" + e, e); - throw new DotRuntimeException(e.toString()); - } - } - + + MultiTree mTree = mTrees.get(0); + updateHTMLPageVersionTS(mTree.getHtmlPage()); + refreshPageInCache(mTree.getHtmlPage()); + + } + + + + private static void _dbUpsert(final MultiTree mtree) throws DotDataException { + + _dbDelete(mtree); + _dbInsert(mtree); + + } + + private static void _reorder(final MultiTree tree) throws DotDataException { + + List trees = getMultiTrees(tree.getHtmlPage(), tree.getContainer(), tree.getRelationType()); + trees = trees.stream() + .filter(rowTree -> !rowTree.equals(tree)) + .collect(Collectors.toList()); + int maxOrder = (tree.getTreeOrder() > trees.size()) ? trees.size() : tree.getTreeOrder(); + trees.add(maxOrder, tree); + + saveMultiTrees(trees); + + } + + + + private static void _dbInsert(final MultiTree o) throws DotDataException { + new DotConnect().setSQL(INSERT_SQL) + .addParam(o.getHtmlPage()) + .addParam(o.getContainer()) + .addParam(o.getContentlet()) + .addParam(o.getRelationType()) + .addParam(o.getTreeOrder()) + .loadResult(); + } + + + + + + + + /** - * Update the version_ts of all versions of the HTML Page with the given id. - * If a MultiTree Object has been added or deleted from this page, - * its version_ts value needs to be updated so it can be included - * in future Push Publishing tasks + * Update the version_ts of all versions of the HTML Page with the given id. If a MultiTree + * Object has been added or deleted from this page, its version_ts value needs to be updated so + * it can be included in future Push Publishing tasks * - * @param id The HTMLPage Identifier to pass in + * @param id The HTMLPage Identifier to pass in * @throws DotContentletStateException - * @throws DotDataException - * @throws DotSecurityException - * + * @throws DotDataException + * @throws DotSecurityException + * */ - private static void updateHTMLPageVersionTS(String id) throws DotDataException, DotSecurityException { - List infos = APILocator.getVersionableAPI().findContentletVersionInfos(id); - for (ContentletVersionInfo versionInfo : infos) { - if(versionInfo!=null) { - versionInfo.setVersionTs(new Date()); - APILocator.getVersionableAPI().saveContentletVersionInfo(versionInfo); - } - } - } - + private static void updateHTMLPageVersionTS(final String id) throws DotDataException { + List infos = APILocator.getVersionableAPI() + .findContentletVersionInfos(id); + for (ContentletVersionInfo versionInfo : infos) { + if (versionInfo != null) { + versionInfo.setVersionTs(new Date()); + APILocator.getVersionableAPI() + .saveContentletVersionInfo(versionInfo); + } + } + } + /** * Refresh cached objects for all versions of the HTMLPage with the given pageIdentifier. * * @param pageIdentifier The HTMLPage Identifier to pass in * @throws DotContentletStateException - * @throws DotDataException - * @throws DotSecurityException - * + * @throws DotDataException + * */ - private static void refreshPageInCache(String pageIdentifier) throws DotDataException, DotSecurityException { + private static void refreshPageInCache(final String pageIdentifier) throws DotDataException { Set inodes = new HashSet(); - List infos = APILocator.getVersionableAPI().findContentletVersionInfos(pageIdentifier); + List infos = APILocator.getVersionableAPI() + .findContentletVersionInfos(pageIdentifier); for (ContentletVersionInfo versionInfo : infos) { inodes.add(versionInfo.getWorkingInode()); - if(versionInfo.getLiveInode() != null){ - inodes.add(versionInfo.getLiveInode()); + if (versionInfo.getLiveInode() != null) { + inodes.add(versionInfo.getLiveInode()); } } + try { + List contentlets = APILocator.getContentletAPIImpl() + .findContentlets(Lists.newArrayList(inodes)); + for (Contentlet pageContent : contentlets) { + IHTMLPage htmlPage = APILocator.getHTMLPageAssetAPI() + .fromContentlet(pageContent); + new PageLoader().invalidate(htmlPage); + } + } catch (DotStateException | DotSecurityException e) { + Logger.warn(MultiTreeFactory.class, "unable to refresh page cache:" + e.getMessage()); + } + } + + + private static MultiTree dbToMultiTree(Map row) { + final String relationType = (String) row.getOrDefault("relation_type", null); + final String parent1 = (String) row.getOrDefault("parent1", null); + final String parent2 = (String) row.getOrDefault("parent2", null); + final String child = (String) row.getOrDefault("child", null); + final int order = Integer.valueOf((Integer) row.getOrDefault("tree_order", 0)); + return new MultiTree(parent1, parent2, child, relationType, order); + } - List contentlets = APILocator.getContentletAPIImpl().findContentlets(Lists.newArrayList(inodes)); - for (Contentlet pageContent : contentlets) { - IHTMLPage htmlPage = APILocator.getHTMLPageAssetAPI().fromContentlet(pageContent); - PageServices.invalidateAll(htmlPage); - } + public static List dbToMultiTree(List> dbRows) { + return (List) dbRows.stream() + .map(row -> dbToMultiTree(row)) + .collect(Collectors.toList()); } - + + /** + * {link {@link #saveMultiTree(MultiTree)} The multitree does not respect language + * + * @param multiTreeEN + * @param english + * @throws DotDataException + */ + @Deprecated + public static void saveMultiTree(MultiTree multiTree, long lang) throws DotDataException { + saveMultiTree(multiTree); + } + + } diff --git a/dotCMS/src/main/java/com/dotmarketing/factories/PublishFactory.java b/dotCMS/src/main/java/com/dotmarketing/factories/PublishFactory.java index e0a3a5ff1229..de5d0ffbff91 100644 --- a/dotCMS/src/main/java/com/dotmarketing/factories/PublishFactory.java +++ b/dotCMS/src/main/java/com/dotmarketing/factories/PublishFactory.java @@ -1,6 +1,13 @@ package com.dotmarketing.factories; +import static com.dotmarketing.business.PermissionAPI.PERMISSION_PUBLISH; + import com.dotcms.business.CloseDBIfOpened; +import com.dotcms.rendering.velocity.services.ContainerLoader; +import com.dotcms.rendering.velocity.services.ContentletLoader; +import com.dotcms.rendering.velocity.services.PageLoader; +import com.dotcms.rendering.velocity.services.TemplateLoader; + import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.Inode; @@ -24,14 +31,8 @@ import com.dotmarketing.portlets.links.model.Link; import com.dotmarketing.portlets.templates.model.Template; import com.dotmarketing.portlets.workflows.model.WorkflowStep; -import com.dotmarketing.services.ContainerServices; -import com.dotmarketing.services.ContentletServices; -import com.dotmarketing.services.PageServices; -import com.dotmarketing.services.TemplateServices; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; -import com.liferay.portal.model.User; -import com.liferay.portal.util.PortalUtil; import java.util.ArrayList; import java.util.HashSet; @@ -41,7 +42,8 @@ import javax.servlet.http.HttpServletRequest; -import static com.dotmarketing.business.PermissionAPI.PERMISSION_PUBLISH; +import com.liferay.portal.model.User; +import com.liferay.portal.util.PortalUtil; /** * @@ -185,7 +187,7 @@ public static boolean publishAsset(Inode webAsset, User user, boolean respectFro if (webAsset instanceof Container) { //saves to live folder under velocity - ContainerServices.invalidate((Container)webAsset); + new ContainerLoader().invalidate((Container)webAsset); } @@ -211,7 +213,7 @@ public static boolean publishAsset(Inode webAsset, User user, boolean respectFro //Clean-up the cache for this template CacheLocator.getTemplateCache().remove( webAsset.getInode() ); //writes the template to a live directory under velocity folder - TemplateServices.invalidate((Template)webAsset); + new TemplateLoader().invalidate((Template)webAsset); } @@ -274,7 +276,7 @@ public static boolean publishAsset(Inode webAsset, User user, boolean respectFro try { com.dotmarketing.portlets.contentlet.model.Contentlet newFormatContentlet = conAPI.convertFatContentletToContentlet(cont); - ContentletServices.invalidateLive(newFormatContentlet); + new ContentletLoader().invalidate(newFormatContentlet); } catch (DotDataException e) { throw new WebAssetException(e.getMessage(), e); } @@ -322,7 +324,7 @@ public static boolean publishHTMLPage(IHTMLPage htmlPage, List relatedNotPublish if (null != step && !APILocator.getWorkflowAPI().findScheme(step.getSchemeId()).isMandatory() ) { contentletAPI.publish( (Contentlet) asset, user, false ); - ContentletServices.invalidateLive(contentlet); + new ContentletLoader().invalidate(asset); } } catch ( DotSecurityException e ) { //User has no permission to publish the content in the page so we just skip it @@ -335,12 +337,9 @@ public static boolean publishHTMLPage(IHTMLPage htmlPage, List relatedNotPublish } //writes the htmlpage to a live directory under velocity folder - PageServices.invalidateAll(htmlPage); + new PageLoader().invalidate(htmlPage); + APILocator.getContentletAPI().publish( (HTMLPageAsset) htmlPage, user, false ); - if ( htmlPage instanceof HTMLPageAsset ) { - //And finally publish the page - APILocator.getContentletAPI().publish( (HTMLPageAsset) htmlPage, user, false ); - } //Remove from block cache. CacheLocator.getBlockPageCache().remove(htmlPage); diff --git a/dotCMS/src/main/java/com/dotmarketing/factories/TreeFactory.java b/dotCMS/src/main/java/com/dotmarketing/factories/TreeFactory.java index ee8a08b15475..a6715ec44050 100644 --- a/dotCMS/src/main/java/com/dotmarketing/factories/TreeFactory.java +++ b/dotCMS/src/main/java/com/dotmarketing/factories/TreeFactory.java @@ -1,386 +1,363 @@ package com.dotmarketing.factories; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import com.dotcms.repackage.net.sf.hibernate.HibernateException; - import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.Inode; import com.dotmarketing.beans.Tree; import com.dotmarketing.business.DotStateException; import com.dotmarketing.common.db.DotConnect; -import com.dotmarketing.db.HibernateUtil; import com.dotmarketing.exception.DotDataException; -import com.dotmarketing.exception.DotHibernateException; import com.dotmarketing.util.Logger; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + /** * * @author maria */ public class TreeFactory { - private static final String CHILD_RELATION_TYPE = "child"; - - public static Tree getTree(String x) { - try { - return (Tree) new HibernateUtil(Tree.class).load(Long.parseLong(x)); - } catch (Exception e) { - Tree tree = null ; - try { - tree = (Tree) new HibernateUtil(Tree.class).load(x); - } catch (DotHibernateException e1) { - Logger.error(TreeFactory.class, "getTree failed:" + e, e); - } - return tree; - } - } - - public static Tree getTree(Tree object) { - try { - return (Tree) new HibernateUtil(Tree.class).load(Tree.class, object); - } catch (Exception e) { - return new Tree(); - } - } - - public static Tree getTree(Inode parent, Inode child) { - return getTree(parent, child, CHILD_RELATION_TYPE); - } - - public static Tree getTree(String parent, String child) { - return getTree(parent, child, CHILD_RELATION_TYPE); - } - - public static Tree getTree(String parent, String child, String relationType) { - try { - final DotConnect dc = new DotConnect(); - String query = "select * from tree where parent = ? and child = ? "; - if(relationType != null) query += " and relation_type = ?"; - - dc.setSQL(query); - dc.addParam(parent); - dc.addParam(child); - if(relationType != null) { - dc.addParam(relationType); - } - - final List> res = dc.loadObjectResults(); - if(res!=null && !res.isEmpty()) { - final Tree tree = new Tree(); - final Map resultMap = res.get(0); - tree.setChild(resultMap.get("child").toString()); - tree.setParent(resultMap.get("parent").toString()); - tree.setRelationType(resultMap.get("relation_type").toString()); - tree.setTreeOrder(Integer.parseInt(resultMap.get("tree_order").toString())); - return tree; - } - - } catch (DotDataException e) { - Logger.warn(TreeFactory.class, "getTree failed:" + e, e); - } - - return new Tree(); - } - - public static Tree getTree(Inode parent, Inode child, String relationType) { - return getTree(parent.getInode(), child.getInode(), relationType); - } - - public static Tree getTreeByChildAndRelationType(Inode child, String relationType) { - return getTreeByChildAndRelationType(child.getInode(), relationType); - } - - public static Tree getTreeByChildAndRelationType(String child, String relationType) { - try { - HibernateUtil dh = new HibernateUtil(Tree.class); - dh.setQuery("from tree in class com.dotmarketing.beans.Tree where child = ? and relation_type = ?"); - dh.setParam(child); - dh.setParam(relationType); - - return (Tree) dh.load(); - } catch (Exception e) { - Logger.warn(TreeFactory.class, "getTree failed:" + e, e); - } - - return new Tree(); - } - - public static Tree getTreeByParentAndRelationType(Inode parent, String relationType) { - try { - HibernateUtil dh = new HibernateUtil(Tree.class); - dh.setQuery("from tree in class com.dotmarketing.beans.Tree where parent = ? and relation_type = ?"); - dh.setParam(parent.getInode()); - dh.setParam(relationType); - - return (Tree) dh.load(); - } catch (Exception e) { - Logger.warn(TreeFactory.class, "getTree failed:" + e, e); - } - - return new Tree(); - } - - @SuppressWarnings("unchecked") - public static List getTreesByParentAndRelationType(Inode parent, String relationType) { - try { - HibernateUtil dh = new HibernateUtil(Tree.class); - dh - .setQuery("from tree in class com.dotmarketing.beans.Tree where parent = ? and relation_type = ? order by tree_order asc"); - dh.setParam(parent.getInode()); - dh.setParam(relationType); - - return dh.list(); - } catch (Exception e) { - Logger.warn(TreeFactory.class, "getTree failed:" + e, e); - } - - return new ArrayList(); - } - - public static List getTreesByParentAndRelationType(Identifier parent, String relationType) { - try { - HibernateUtil dh = new HibernateUtil(Tree.class); - dh - .setQuery("from tree in class com.dotmarketing.beans.Tree where parent = ? and relation_type = ? order by tree_order asc"); - dh.setParam(parent.getInode()); - dh.setParam(relationType); - return dh.list(); - } catch (Exception e) { - Logger.warn(TreeFactory.class, "getTreesByParentAndRelationType failed:" + e, e); - } - - return new ArrayList(); - } - - @SuppressWarnings("unchecked") - public static List getTreesByChildAndRelationType(Inode child, String relationType) { - try { - HibernateUtil dh = new HibernateUtil(Tree.class); - dh - .setQuery("from tree in class com.dotmarketing.beans.Tree where child = ? and relation_type = ? order by tree_order asc"); - dh.setParam(child.getInode()); - dh.setParam(relationType); - - return dh.list(); - } catch (Exception e) { - Logger.warn(TreeFactory.class, "getTree failed:" + e, e); - } - - return new ArrayList(); - } - - public static List getTreesByChildAndRelationType(Identifier child, String relationType) { - try { - HibernateUtil dh = new HibernateUtil(Tree.class); - dh - .setQuery("from tree in class com.dotmarketing.beans.Tree where child = ? and relation_type = ? order by tree_order asc"); - dh.setParam(child.getInode()); - dh.setParam(relationType); - - return dh.list(); - } catch (Exception e) { - Logger.warn(TreeFactory.class, "getTreesByChildAndRelationType failed:" + e, e); - } - - return new ArrayList(); - } - - @SuppressWarnings("unchecked") - public static List getTreesByRelationType(String relationType) { - try { - HibernateUtil dh = new HibernateUtil(Tree.class); - dh.setQuery("from tree in class com.dotmarketing.beans.Tree where relation_type = ?"); - dh.setParam(relationType); - - return dh.list(); - } catch (Exception e) { - Logger.warn(TreeFactory.class, "getTree failed:" + e, e); - } - - return new ArrayList(); - } - - @SuppressWarnings("unchecked") - public static List getTreesByParent(Inode inode) { - return getTreesByParent(inode.getInode()); - } - - @SuppressWarnings("unchecked") - public static List getTreesByParent(String inode) { - try { - HibernateUtil dh = new HibernateUtil(Tree.class); - dh.setQuery("from tree in class com.dotmarketing.beans.Tree where parent = ?"); - dh.setParam(inode); - - return dh.list(); - } catch (Exception e) { - Logger.warn(TreeFactory.class, "getTree failed:" + e, e); - } - - return new ArrayList(); - } - - public static List getTreesByChild(Inode inode) { - return getTreesByChild(inode.getInode()); - } - - @SuppressWarnings("unchecked") - public static List getTreesByChild(String inode) { - try { - HibernateUtil dh = new HibernateUtil(Tree.class); - dh.setQuery("from tree in class com.dotmarketing.beans.Tree where child = ?"); - dh.setParam(inode); - - return dh.list(); - } catch (Exception e) { - Logger.warn(TreeFactory.class, "getTree failed:" + e, e); - } - - return new ArrayList(); - } - - public static void swapTrees(Inode i1, Inode i2) throws HibernateException { - - List newTrees = new ArrayList(); - - // Removing actual trees and creating the new ones - Iterator it = getTreesByParent(i1).iterator(); - while (it.hasNext()) { - Tree tree = (Tree) it.next(); - newTrees.add(new Tree(i2.getInode(), tree.getChild(), tree.getRelationType(), tree.getTreeOrder())); - deleteTree(tree); - } - - it = getTreesByChild(i1).iterator(); - while (it.hasNext()) { - Tree tree = (Tree) it.next(); - newTrees.add(new Tree(tree.getParent(), i2.getInode(), tree.getRelationType(), tree.getTreeOrder())); - deleteTree(tree); - } - - it = getTreesByParent(i2).iterator(); - while (it.hasNext()) { - Tree tree = (Tree) it.next(); - newTrees.add(new Tree(i1.getInode(), tree.getChild(), tree.getRelationType(), tree.getTreeOrder())); - deleteTree(tree); - } - - it = getTreesByChild(i2).iterator(); - while (it.hasNext()) { - Tree tree = (Tree) it.next(); - newTrees.add(new Tree(tree.getParent(), i1.getInode(), tree.getRelationType(), tree.getTreeOrder())); - deleteTree(tree); - } - - // Saving new trees - it = newTrees.iterator(); - while (it.hasNext()) { - Tree tree = (Tree) it.next(); - saveTree(tree); - } - try { - HibernateUtil.flush(); - HibernateUtil.getSession().refresh(i1); - HibernateUtil.getSession().refresh(i2); - } catch (DotHibernateException e) { - Logger.error(TreeFactory.class,"swapTrees failed:" + e, e); - } - - } - - public static void deleteTree(Tree tree) { - try { - DotConnect dc = new DotConnect(); - dc.setSQL("delete from tree where parent = ? and child = ? and tree.relation_type = ?"); - dc.addParam(tree.getParent()); - dc.addParam(tree.getChild()); - dc.addParam(tree.getRelationType()); - dc.loadResult(); - } catch (DotDataException e) { - throw new DotStateException(e); - } - } - - public static void deleteTreesByParent(Inode parent) { - try { - HibernateUtil.delete("from tree in class com.dotmarketing.beans.Tree where tree.parent = '" + parent.getInode()+"'"); - } catch (DotHibernateException e) { - throw new DotStateException(e); - } - } - - public static void deleteTreesByParentById(final String parentId) throws DotDataException { - DotConnect dc = new DotConnect(); - dc.setSQL("DELETE FROM tree WHERE parent = ?").addParam(parentId).loadResult(); - } - - public static void deleteTreesByParentAndRelationType(Inode parent, String relationType) { - try { - HibernateUtil.delete("from tree in class com.dotmarketing.beans.Tree where tree.parent = '" + parent.getInode() + - "' and tree.relationType = '" + relationType + "'"); - } catch (DotHibernateException e) { - throw new DotStateException(e); - } - } - - public static void deleteTreesByParentAndChildAndRelationType(final String parent, final String child, - final String relationType) { - try { - - DotConnect dc = new DotConnect(); - dc.setSQL("delete from tree where parent = ? and child = ? and tree.relation_type = ?"); - dc.addParam(parent); - dc.addParam(child); - dc.addParam(relationType); - dc.loadResult(); - } catch (DotDataException e) { - throw new DotStateException(e); - } - } - - - public static void deleteTreesByChildAndRelationType(Inode child, String relationType) { - try { - HibernateUtil.delete("from tree in class com.dotmarketing.beans.Tree where tree.child = '" + child.getInode() + - "' and tree.relationType = '" + relationType + "'"); - } catch (DotHibernateException e) { - throw new DotStateException(e); - } - } - - public static void deleteTreesByChild(Inode child) { - try { - HibernateUtil.delete("from tree in class com.dotmarketing.beans.Tree where tree.child = '" + child.getInode()+"'"); - } catch (DotHibernateException e) { - throw new DotStateException(e); - } - } - - public static void deleteTreesByChildId(final String childId) throws DotDataException { - DotConnect dc = new DotConnect(); - dc.setSQL("DELETE FROM tree WHERE child = ?").addParam(childId).loadResult(); - } - - public static void deleteTreesByRelationType(String relationType) { - try { - HibernateUtil - .delete("from tree in class com.dotmarketing.beans.Tree where tree.relationType = '" + relationType + "'"); - } catch (DotHibernateException e) { - throw new DotStateException(e); - } - } - - public static void saveTree(Tree tree) { - try { - HibernateUtil.saveOrUpdate(tree); - } catch (DotHibernateException e) { - throw new DotStateException(e); - } - } - - + + + public static Tree getTree(final Inode parent, final Inode child) { + + return getTree(parent.getInode(), child.getInode()); + } + + public static Tree getTree(final String parent, final String child) { + String relationType = "child"; + return getTree(parent, child, relationType); + + } + + public static Tree getTree(final String parent, final String child, final String relationType) { + try { + DotConnect dc = new DotConnect(); + String query = "select * from tree where parent = ? and child = ? "; + if (relationType != null) + query += " and relation_type = ?"; + dc.setSQL(query); + dc.addParam(parent); + dc.addParam(child); + if (relationType != null) + dc.addParam(relationType); + + return new DBTreeTransformer(dc.loadObjectResults()).tree(); + + + } catch (DotDataException e) { + Logger.warn(TreeFactory.class, "getTree failed:" + e, e); + } + + return new Tree(); + } + + public static Tree getTree(final Tree tree) { + return getTree(tree.getParent(), tree.getChild(), tree.getRelationType()); + } + + public static List getAllTrees(final int limit, final int offset) throws DotDataException { + + DotConnect dc = new DotConnect().setSQL("select * from tree order by parent,child,relation_type ").setMaxRows(limit) + .setStartRow(offset); + + return new DBTreeTransformer(dc.loadObjectResults()).trees(); + + + + } + + + public static Tree getTree(final Inode parent, final Inode child, final String relationType) { + return getTree(parent.getInode(), child.getInode(), relationType); + } + + + + public static List getTreesByParentAndRelationType(Identifier parent, String relationType) { + return getTreesByParentAndRelationType(parent.getId(), relationType); + } + + + public static List getTreesByParentAndRelationType(Inode parent, String relationType) { + return getTreesByParentAndRelationType(parent.getInode(), relationType); + } + + + private static List getTreesByParentAndRelationType(String parent, String relationType) { + try { + DotConnect dc = new DotConnect(); + dc.setSQL("select * from tree where parent = ? and relation_type = ? order by tree_order asc"); + dc.addParam(parent); + dc.addParam(relationType); + + return new DBTreeTransformer(dc.loadObjectResults()).trees(); + } catch (Exception e) { + Logger.warn(TreeFactory.class, "getTree failed:" + e, e); + } + + return new ArrayList(); + } + + + + private static List getTreesByChildAndRelationType(String child, String relationType) { + try { + DotConnect dc = new DotConnect(); + dc.setSQL("select * from tree where child = ? and relation_type = ? order by tree_order asc"); + dc.addParam(child); + dc.addParam(relationType); + + return new DBTreeTransformer(dc.loadObjectResults()).trees(); + } catch (Exception e) { + Logger.warn(TreeFactory.class, "getTree failed:" + e, e); + } + + return new ArrayList(); + } + + + public static List getTreesByChildAndRelationType(Inode child, String relationType) { + return getTreesByChildAndRelationType(child.getInode(), relationType); + } + + public static List getTreesByChildAndRelationType(Identifier child, String relationType) { + return getTreesByChildAndRelationType(child.getId(), relationType); + } + + + public static List getTreesByRelationType(String relationType) { + try { + DotConnect dc = new DotConnect(); + dc.setSQL("select * from tree where relation_type = ?"); + dc.addParam(relationType); + + return new DBTreeTransformer(dc.loadObjectResults()).trees(); + } catch (Exception e) { + Logger.warn(TreeFactory.class, "getTree failed:" + e, e); + } + + return new ArrayList(); + } + + + public static List getTreesByParent(Inode inode) { + return getTreesByParent(inode.getInode()); + } + + + public static List getTreesByParent(String inode) { + try { + DotConnect dc = new DotConnect(); + dc.setSQL("select * from tree where parent = ?"); + dc.addParam(inode); + + return new DBTreeTransformer(dc.loadObjectResults()).trees(); + } catch (Exception e) { + Logger.warn(TreeFactory.class, "getTree failed:" + e, e); + } + + return new ArrayList(); + } + + public static List getTreesByChild(Inode inode) { + return getTreesByChild(inode.getInode()); + } + + + public static List getTreesByChild(String inode) { + try { + DotConnect dc = new DotConnect(); + dc.setSQL("select * from tree where child = ?"); + dc.addParam(inode); + + return new DBTreeTransformer(dc.loadObjectResults()).trees(); + } catch (Exception e) { + Logger.warn(TreeFactory.class, "getTree failed:" + e, e); + } + + return new ArrayList(); + } + + public static void swapTrees(final Inode i1, final Inode i2) throws DotDataException { + + List newTrees = new ArrayList(); + + // Removing actual trees and creating the new ones + Iterator it = getTreesByParent(i1).iterator(); + while (it.hasNext()) { + Tree tree = (Tree) it.next(); + newTrees.add(new Tree(i2.getInode(), tree.getChild(), tree.getRelationType(), tree.getTreeOrder())); + deleteTree(tree); + } + + it = getTreesByChild(i1).iterator(); + while (it.hasNext()) { + Tree tree = (Tree) it.next(); + newTrees.add(new Tree(tree.getParent(), i2.getInode(), tree.getRelationType(), tree.getTreeOrder())); + deleteTree(tree); + } + + it = getTreesByParent(i2).iterator(); + while (it.hasNext()) { + Tree tree = (Tree) it.next(); + newTrees.add(new Tree(i1.getInode(), tree.getChild(), tree.getRelationType(), tree.getTreeOrder())); + deleteTree(tree); + } + + it = getTreesByChild(i2).iterator(); + while (it.hasNext()) { + Tree tree = (Tree) it.next(); + newTrees.add(new Tree(tree.getParent(), i1.getInode(), tree.getRelationType(), tree.getTreeOrder())); + deleteTree(tree); + } + + // Saving new trees + it = newTrees.iterator(); + while (it.hasNext()) { + Tree tree = (Tree) it.next(); + saveTree(tree); + } + } + + public static void deleteTree(Tree tree) { + try { + DotConnect dc = new DotConnect(); + + dc.setSQL("delete from tree where parent = ? and child = ? and relation_type = ?"); + + dc.addParam(tree.getParent()); + dc.addParam(tree.getChild()); + dc.addParam(tree.getRelationType()); + dc.loadResult(); + } catch (DotDataException e) { + + throw new DotStateException(e); + + } + } + + public static void deleteTreesByParent(Inode parent) { + try { + DotConnect dc = new DotConnect(); + dc.setSQL("delete from tree where parent = ?"); + dc.addParam(parent.getInode()); + dc.loadResult(); + } catch (DotDataException e) { + throw new DotStateException(e); + } + } + + public static void deleteTreesByParentById(final String parentId) throws DotDataException { + DotConnect dc = new DotConnect(); + dc.setSQL("DELETE FROM tree WHERE parent = ?").addParam(parentId).loadResult(); + } + + public static void deleteTreesByParentAndRelationType(Inode parent, String relationType) { + try { + DotConnect dc = new DotConnect(); + dc.setSQL("delete from tree where parent = ? and relation_type = ?"); + dc.addParam(parent.getInode()); + dc.addParam(relationType); + dc.loadResult(); + } catch (DotDataException e) { + throw new DotStateException(e); + } + } + + + public static void deleteTreesByParentAndChildAndRelationType(String parent, String child, String relationType) { + try { + + DotConnect dc = new DotConnect(); + dc.setSQL("delete from tree where parent = ? and child = ? and relation_type = ?"); + + dc.addParam(parent); + dc.addParam(child); + dc.addParam(relationType); + dc.loadResult(); + } catch (DotDataException e) { + throw new DotStateException(e); + } + } + + + public static void deleteTreesByChildAndRelationType(Inode child, String relationType) { + try { + DotConnect dc = new DotConnect(); + dc.setSQL("delete from tree where child = ? and relation_type = ?"); + + dc.addParam(child); + dc.addParam(relationType); + dc.loadResult(); + } catch (DotDataException e) { + throw new DotStateException(e); + } + } + + public static void deleteTreesByChild(Inode child) { + try { + DotConnect dc = new DotConnect(); + dc.setSQL("delete from tree where child =?"); + + dc.addParam(child); + + dc.loadResult(); + } catch (DotDataException e) { + throw new DotStateException(e); + } + } + + public static void deleteTreesByChildId(final String childId) throws DotDataException { + DotConnect dc = new DotConnect(); + dc.setSQL("DELETE FROM tree WHERE child = ?").addParam(childId).loadResult(); + } + + public static void deleteTreesByRelationType(String relationType) { + try { + DotConnect dc = new DotConnect(); + dc.setSQL("delete from tree where relation_type = ?"); + dc.addParam(relationType); + dc.loadResult(); + } catch (DotDataException e) { + throw new DotStateException(e); + } + } + + /** + * Does a upsert into the tree table + * + * @param tree + */ + public static void saveTree(Tree tree) { + deleteTree(tree); + insertTree(tree); + } + + /** + * Does an insert into the tree table + * + * @param tree + */ + public static void insertTree(Tree tree) { + DotConnect dc = new DotConnect(); + dc.setSQL("insert into tree (child,parent,relation_type,tree_order) values (?,?,?,?)"); + dc.addParam(tree.getChild()); + dc.addParam(tree.getParent()); + dc.addParam(tree.getRelationType()); + dc.addParam(tree.getTreeOrder()); + try { + dc.loadResult(); + } catch (DotDataException e) { + throw new DotStateException(e); + } + } + + + + + + } + diff --git a/dotCMS/src/main/java/com/dotmarketing/factories/WebAssetFactory.java b/dotCMS/src/main/java/com/dotmarketing/factories/WebAssetFactory.java index 57e6b0c71deb..978841f21649 100644 --- a/dotCMS/src/main/java/com/dotmarketing/factories/WebAssetFactory.java +++ b/dotCMS/src/main/java/com/dotmarketing/factories/WebAssetFactory.java @@ -7,9 +7,12 @@ import com.dotcms.api.system.event.SystemEventsAPI; import com.dotcms.api.system.event.Visibility; import com.dotcms.api.system.event.verifier.ExcludeOwnerVerifierBean; +import com.dotcms.rendering.velocity.services.ContainerLoader; +import com.dotcms.rendering.velocity.services.TemplateLoader; import com.dotcms.repackage.com.google.common.base.Strings; import com.dotcms.util.transform.DBTransformer; import com.dotcms.util.transform.TransformerLocator; + import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.Inode; @@ -47,15 +50,12 @@ import com.dotmarketing.portlets.links.model.Link; import com.dotmarketing.portlets.templates.business.TemplateAPI; import com.dotmarketing.portlets.templates.model.Template; -import com.dotmarketing.services.ContainerServices; -import com.dotmarketing.services.TemplateServices; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; import com.dotmarketing.util.PaginatedArrayList; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; -import com.liferay.portal.model.User; -import com.liferay.portal.struts.ActionException; + import java.util.ArrayList; import java.util.Collections; import java.util.Date; @@ -64,6 +64,9 @@ import java.util.List; import java.util.Map; +import com.liferay.portal.model.User; +import com.liferay.portal.struts.ActionException; + /** * * @author maria, david(2005) @@ -683,10 +686,10 @@ public static boolean unPublishAsset(WebAsset currWebAsset, String userId, Inode if (currWebAsset instanceof Container) { //remove container from the live directory - ContainerServices.unpublishContainerFile((Container)currWebAsset); + new ContainerLoader().invalidate((Container)currWebAsset); } else if (currWebAsset instanceof Template) { //remove template from the live directory - TemplateServices.unpublishTemplateFile((Template)currWebAsset); + new TemplateLoader().invalidate((Template)currWebAsset); } else if( currWebAsset instanceof Link ) { // Removes static menues to provoke all possible dependencies be generated. if( parent instanceof Folder ) { @@ -834,6 +837,7 @@ public static List getAssetsWorkingWithPermission(Class c, int limit, PermissionAPI permAPI = APILocator.getPermissionAPI(); + DBTransformer transformer = TransformerLocator .createDBTransformer(dc.loadObjectResults(), c); @@ -845,6 +849,7 @@ public static List getAssetsWorkingWithPermission(Class c, int limit, return Collections.emptyList(); } + toReturn.addAll(permAPI.filterCollection(list, PermissionAPI.PERMISSION_READ, false, user)); if(limit > 0 && toReturn.size() >= limit + offset) done = true; @@ -950,12 +955,12 @@ public static boolean deleteAsset(WebAsset currWebAsset, User user) throws Excep List webAssetList = new ArrayList(); if(currWebAsset instanceof Container) { - ContainerServices.unpublishContainerFile((Container)currWebAsset); + new ContainerLoader().invalidate((Container)currWebAsset); webAssetList = APILocator.getVersionableAPI().findAllVersions(identifier, APILocator.getUserAPI().getSystemUser(), false); } else if(currWebAsset instanceof Template) { - TemplateServices.unpublishTemplateFile((Template)currWebAsset); + new TemplateLoader().invalidate((Template)currWebAsset); //webAssetList = APILocator.getVersionableAPI().findAllVersions(identifier, APILocator.getUserAPI().getSystemUser(), false); } else if(currWebAsset instanceof Link) @@ -984,7 +989,7 @@ else if(currWebAsset instanceof Link) List multiTrees = new ArrayList(); if (currWebAsset instanceof Container) { - multiTrees = MultiTreeFactory.getMultiTree(identifier); + multiTrees = MultiTreeFactory.getMultiTrees(identifier); } if(UtilMethods.isSet(multiTrees)) { diff --git a/dotCMS/src/main/java/com/dotmarketing/filters/CMSFilter.java b/dotCMS/src/main/java/com/dotmarketing/filters/CMSFilter.java index ef00d4c61dde..195d97870e7d 100644 --- a/dotCMS/src/main/java/com/dotmarketing/filters/CMSFilter.java +++ b/dotCMS/src/main/java/com/dotmarketing/filters/CMSFilter.java @@ -14,7 +14,8 @@ import com.dotmarketing.util.Config; import com.dotmarketing.util.Logger; import com.dotmarketing.util.NumberOfTimeVisitedCounter; -import com.dotmarketing.util.PageRequestModeUtil; +import com.dotmarketing.util.PageMode; + import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; import java.io.IOException; @@ -28,7 +29,7 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; + import org.apache.commons.logging.LogFactory; public class CMSFilter implements Filter { @@ -101,7 +102,7 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) // Get the user language final long languageId = WebAPILocator.getLanguageWebAPI().getLanguage(request).getId(); - iAm = this.resolveResourceType(iAm, uri, site, languageId); + iAm = this.urlUtil.resolveResourceType(iAm, uri, site, languageId); if (iAm == IAm.FOLDER) { @@ -149,7 +150,7 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) return; } - if (iAm == IAm.FILE) { + else if (iAm == IAm.FILE) { Identifier ident; try { //Serving the file through the /dotAsset servlet @@ -172,11 +173,16 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) return; } - if (iAm == IAm.PAGE) { + else if (iAm == IAm.PAGE) { // Serving a page through the velocity servlet StringWriter forward = new StringWriter(); - forward.append("/servlets/VelocityServlet"); - + if(PageMode.get(request).showLive) { + forward.append("/servlets/VelocityLiveServlet"); + } + else { + forward.append("/servlets/VelocityPreviewServlet"); + } + if (UtilMethods.isSet(queryString)) { if (!queryString.contains(WebKeys.HTMLPAGE_LANGUAGE)) { queryString = queryString + "&" + WebKeys.HTMLPAGE_LANGUAGE + "=" + languageId; @@ -196,26 +202,12 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) } } - // otherwise, pass - chain.doFilter(req, res); + + chain.doFilter(req, res); + } - private IAm resolveResourceType(final IAm iAm, - final String uri, - final Host site, - final long languageId) { - - final String uriWithoutQueryString = this.urlUtil.getUriWithoutQueryString (uri); - if (this.urlUtil.isFileAsset(uriWithoutQueryString, site, languageId)) { - return IAm.FILE; - } else if (this.urlUtil.isPageAsset(uriWithoutQueryString, site, languageId)) { - return IAm.PAGE; - } else if (this.urlUtil.isFolder(uriWithoutQueryString, site)) { - return IAm.FOLDER; - } - return iAm; - } // resolveResourceType. @Override public void destroy() { @@ -223,37 +215,23 @@ public void destroy() { } private void countSiteVisit(HttpServletRequest request, HttpServletResponse response) { - - HttpSession session = request.getSession(false); - boolean PAGE_MODE = true; - - if (session != null) { - PAGE_MODE = PageRequestModeUtil.isPageMode(session); - } - - if (PAGE_MODE) { + PageMode mode = PageMode.get(request); + if(mode == PageMode.LIVE) { NumberOfTimeVisitedCounter.maybeCount(request, response); - } } private void countPageVisit(HttpServletRequest request) { - HttpSession session = request.getSession(false); - boolean PAGE_MODE = true; - - if (session != null) { - PAGE_MODE = PageRequestModeUtil.isPageMode(session); - } - - if (PAGE_MODE) { + PageMode mode = PageMode.get(request); + if(mode == PageMode.LIVE) { Optional visitor = visitorAPI.getVisitor(request); if (visitor.isPresent()) { visitor.get().addPagesViewed(request.getRequestURI()); } - } + } diff --git a/dotCMS/src/main/java/com/dotmarketing/filters/CMSUrlUtil.java b/dotCMS/src/main/java/com/dotmarketing/filters/CMSUrlUtil.java index 69b591856013..5193c1bc564c 100644 --- a/dotCMS/src/main/java/com/dotmarketing/filters/CMSUrlUtil.java +++ b/dotCMS/src/main/java/com/dotmarketing/filters/CMSUrlUtil.java @@ -4,6 +4,7 @@ import com.dotmarketing.beans.Identifier; import com.dotmarketing.business.*; import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.filters.CMSFilter.IAm; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.contentlet.model.ContentletVersionInfo; import com.dotmarketing.portlets.languagesmanager.model.Language; @@ -83,7 +84,32 @@ public boolean isPageAsset(Versionable asset) { } } - + /** + * Returns the IAm value for a url + * @param iAm + * @param uri + * @param site + * @param languageId + * @return + */ + public IAm resolveResourceType(final IAm iAm, + final String uri, + final Host site, + final long languageId) { + + final String uriWithoutQueryString = this.urlUtil.getUriWithoutQueryString (uri); + if (isFileAsset(uriWithoutQueryString, site, languageId)) { + return IAm.FILE; + } else if (isPageAsset(uriWithoutQueryString, site, languageId)) { + return IAm.PAGE; + } else if (isFolder(uriWithoutQueryString, site)) { + return IAm.FOLDER; + } + else { + return IAm.NOTHING_IN_THE_CMS; + } + +} // resolveResourceType. /** * Indicates if the uri belongs to a Page Asset * diff --git a/dotCMS/src/main/java/com/dotmarketing/filters/ThreadNameFilter.java b/dotCMS/src/main/java/com/dotmarketing/filters/ThreadNameFilter.java index c5987d044920..8043b5f54f01 100644 --- a/dotCMS/src/main/java/com/dotmarketing/filters/ThreadNameFilter.java +++ b/dotCMS/src/main/java/com/dotmarketing/filters/ThreadNameFilter.java @@ -26,6 +26,7 @@ import com.dotmarketing.business.web.HostWebAPI; import com.dotmarketing.business.web.WebAPILocator; import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; public class ThreadNameFilter implements Filter { FastDateFormat df = FastDateFormat.getInstance("MM-dd-yyyy hh:mm:ss z"); @@ -59,8 +60,7 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) long languageId = WebAPILocator.getLanguageWebAPI().getLanguage(request).getId(); String queryString = request.getQueryString(); - boolean adminMode = (request.getSession(false) != null && request.getSession().getAttribute( - com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null); + boolean adminMode = PageMode.get(request) .isAdmin; String referer = request.getHeader("Referer"); StringWriter sw = new StringWriter(); sw.append("url:"); diff --git a/dotCMS/src/main/java/com/dotmarketing/filters/TimeMachineFilter.java b/dotCMS/src/main/java/com/dotmarketing/filters/TimeMachineFilter.java index 4b1e5a852d8e..edef3192edd6 100644 --- a/dotCMS/src/main/java/com/dotmarketing/filters/TimeMachineFilter.java +++ b/dotCMS/src/main/java/com/dotmarketing/filters/TimeMachineFilter.java @@ -7,8 +7,9 @@ import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.util.ConfigUtils; import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; import com.dotmarketing.util.WebKeys; -import com.dotmarketing.viewtools.LanguageWebAPI; +import com.dotcms.rendering.velocity.viewtools.LanguageWebAPI; import eu.bitwalker.useragentutils.Browser; import eu.bitwalker.useragentutils.UserAgent; import java.io.File; @@ -72,12 +73,13 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha req.getSession().removeAttribute(TM_DATE_VAR); req.getSession().removeAttribute(TM_LANG_VAR); req.getSession().removeAttribute(TM_HOST_VAR); + } // If a Time Machine request is present... if(req.getSession().getAttribute("tm_date")!=null && urlUtil.amISomething(uri,(Host)req.getSession().getAttribute("tm_host") ,Long.parseLong((String)req.getSession().getAttribute("tm_lang")))) { com.liferay.portal.model.User user = null; - + PageMode.setPageMode(req, PageMode.PREVIEW_MODE); try { user = com.liferay.portal.util.PortalUtil.getUser((HttpServletRequest) request); if(!APILocator.getLayoutAPI().doesUserHaveAccessToPortlet("time-machine", user)){ @@ -165,7 +167,7 @@ private File getFileFromTimeMachine(final Host host, String uri, final Date sele basePath.append(ConfigUtils.getTimeMachinePath()).append(sep).append("tm_").append(selectedDate.getTime()) .append(sep); // Site and language path (e.g., "live/demo.dotcms.com/1") - basePath.append("live").append(sep).append(host.getHostname()).append(sep).append(selectedLangId); + basePath.append(PageMode.PREVIEW_MODE.name()).append(sep).append(host.getHostname()).append(sep).append(selectedLangId); // URI (e.g., "/folder/your-page") uri = (java.io.File.separator.equals("\\") ? uri.replaceAll("/", "\\\\") : uri); String completePath = basePath.toString() + uri; diff --git a/dotCMS/src/main/java/com/dotmarketing/portal/struts/DotCustomLoginPostAction.java b/dotCMS/src/main/java/com/dotmarketing/portal/struts/DotCustomLoginPostAction.java index 1d2d1b7fb03b..be880834aedc 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portal/struts/DotCustomLoginPostAction.java +++ b/dotCMS/src/main/java/com/dotmarketing/portal/struts/DotCustomLoginPostAction.java @@ -12,6 +12,8 @@ import com.dotmarketing.business.APILocator; import com.dotmarketing.business.Role; import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; + import com.liferay.portal.model.User; import com.liferay.portal.struts.Action; import com.liferay.portal.struts.ActionException; @@ -84,11 +86,7 @@ public void run(HttpServletRequest request, HttpServletResponse response) Logger.warn(this, "ERROR: "+e.getMessage()); } - //Enabling pages edit mode - HttpSession session = request.getSession(); - session.setAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION, "true"); - session.setAttribute(com.dotmarketing.util.WebKeys.PREVIEW_MODE_SESSION, null); - session.setAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION, "true"); + PageMode.setPageMode(request, PageMode.EDIT_MODE); } diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/browser/ajax/BrowserAjax.java b/dotCMS/src/main/java/com/dotmarketing/portlets/browser/ajax/BrowserAjax.java index 7d3604c091bf..eb6e845537d4 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/browser/ajax/BrowserAjax.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/browser/ajax/BrowserAjax.java @@ -1,6 +1,7 @@ package com.dotmarketing.portlets.browser.ajax; import com.dotcms.contenttype.exception.NotFoundInDbException; +import com.dotcms.rendering.velocity.viewtools.BrowserAPI; import com.dotcms.repackage.org.directwebremoting.WebContext; import com.dotcms.repackage.org.directwebremoting.WebContextFactory; import com.dotmarketing.beans.*; @@ -36,7 +37,7 @@ import com.dotmarketing.portlets.workflows.business.WorkflowAPI; import com.dotmarketing.portlets.workflows.model.WorkflowAction; import com.dotmarketing.util.*; -import com.dotmarketing.viewtools.BrowserAPI; + import com.liferay.portal.PortalException; import com.liferay.portal.SystemException; import com.liferay.portal.language.LanguageUtil; @@ -1106,7 +1107,7 @@ public Map copyHTMLPage ( String inode, String newFolder ) throw newContentlet=APILocator.getContentletAPI().copyContentlet(cont, host, user, false); } /*copy page associated contentlets*/ - List pageContents = MultiTreeFactory.getMultiTree(cont.getIdentifier()); + List pageContents = MultiTreeFactory.getMultiTrees(cont.getIdentifier()); for(MultiTree m : pageContents){ MultiTree mt = new MultiTree(newContentlet.getIdentifier(), m.getParent2(), m.getChild()); MultiTreeFactory.saveMultiTree(mt); diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/calendar/ajax/CalendarAjax.java b/dotCMS/src/main/java/com/dotmarketing/portlets/calendar/ajax/CalendarAjax.java index 48c34925dfc6..e55eabb90fbf 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/calendar/ajax/CalendarAjax.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/calendar/ajax/CalendarAjax.java @@ -45,8 +45,8 @@ import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; -import com.dotmarketing.viewtools.CommentsWebAPI; -import com.dotmarketing.viewtools.DateViewWebAPI; +import com.dotcms.rendering.velocity.viewtools.CommentsWebAPI; +import com.dotcms.rendering.velocity.viewtools.DateViewWebAPI; import com.liferay.portal.PortalException; import com.liferay.portal.SystemException; import com.liferay.portal.language.LanguageException; diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/categories/model/Category.java b/dotCMS/src/main/java/com/dotmarketing/portlets/categories/model/Category.java index 4eb1c9cbdc5c..24b956cbd76e 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/categories/model/Category.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/categories/model/Category.java @@ -17,6 +17,7 @@ import com.dotmarketing.business.PermissionSummary; import com.dotmarketing.business.Permissionable; import com.dotmarketing.business.UserAPI; +import com.dotmarketing.common.db.DotConnect; import com.dotmarketing.db.DbConnectionFactory; import com.dotmarketing.db.HibernateUtil; import com.dotmarketing.exception.DotDataException; @@ -146,20 +147,15 @@ public void setKeywords(String keywords) { } - @SuppressWarnings("unchecked") + public boolean hasActiveChildren() { - HibernateUtil dh = new HibernateUtil (); - String query = "select count(*) from " + Category.class.getName() + " cat where cat.inode in (select tree.child from " + Tree.class.getName() + " tree where tree.parent = " + this.inode + ") " + - " and cat.active = " + DbConnectionFactory.getDBTrue(); - List results ; - try { - dh.setQuery(query); - results = dh.list(); - } catch (DotHibernateException e) { - Logger.error(Category.class, e.getMessage(), e); - throw new DotRuntimeException(e.getMessage(), e); - } - return ((Integer)results.get(0)).intValue() > 0; + DotConnect db = new DotConnect (); + String query = "select count(*) as test_count from category cat where cat.inode in (select tree.child from tree tree where tree.parent = ? ) and cat.active = ?"; + db.setSQL(query); + db.addParam(this.getInode()); + db.addParam(true); + return db.getInt("test_count")>0; + } public Map getMap () { diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/cmsmaintenance/action/ViewCMSMaintenanceAction.java b/dotCMS/src/main/java/com/dotmarketing/portlets/cmsmaintenance/action/ViewCMSMaintenanceAction.java index 5e3639f5eee8..7b5e39cc6275 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/cmsmaintenance/action/ViewCMSMaintenanceAction.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/cmsmaintenance/action/ViewCMSMaintenanceAction.java @@ -1,11 +1,5 @@ package com.dotmarketing.portlets.cmsmaintenance.action; -import com.dotcms.content.elasticsearch.business.ESIndexAPI; -import com.dotcms.content.elasticsearch.business.IndiciesAPI.IndiciesInfo; -import com.dotcms.contenttype.util.ContentTypeImportExportUtil; -import com.dotcms.repackage.com.thoughtworks.xstream.XStream; -import com.dotcms.repackage.com.thoughtworks.xstream.io.xml.DomDriver; -import com.dotcms.repackage.com.thoughtworks.xstream.mapper.Mapper; import com.dotcms.repackage.javax.portlet.ActionRequest; import com.dotcms.repackage.javax.portlet.ActionResponse; import com.dotcms.repackage.javax.portlet.PortletConfig; @@ -16,18 +10,10 @@ import com.dotcms.repackage.org.apache.struts.action.ActionForm; import com.dotcms.repackage.org.apache.struts.action.ActionForward; import com.dotcms.repackage.org.apache.struts.action.ActionMapping; -import com.dotcms.util.transform.TransformerLocator; -import com.dotmarketing.beans.Clickstream; -import com.dotmarketing.beans.Clickstream404; -import com.dotmarketing.beans.ClickstreamRequest; -import com.dotmarketing.beans.Identifier; -import com.dotmarketing.beans.Inode; -import com.dotmarketing.beans.MultiTree; -import com.dotmarketing.beans.PermissionReference; + import com.dotmarketing.business.APILocator; import com.dotmarketing.business.CacheLocator; import com.dotmarketing.business.NoSuchUserException; -import com.dotmarketing.cms.factories.PublicCompanyFactory; import com.dotmarketing.common.business.journal.DistributedJournalFactory; import com.dotmarketing.common.db.DotConnect; import com.dotmarketing.db.DbConnectionFactory; @@ -35,26 +21,15 @@ import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portal.struts.DotPortletAction; -import com.dotmarketing.portlets.calendar.model.CalendarReminder; import com.dotmarketing.portlets.cmsmaintenance.factories.CMSMaintenanceFactory; import com.dotmarketing.portlets.cmsmaintenance.struts.CmsMaintenanceForm; import com.dotmarketing.portlets.cmsmaintenance.util.AssetFileNameFilter; import com.dotmarketing.portlets.contentlet.business.ContentletAPI; import com.dotmarketing.portlets.contentlet.business.DotReindexStateException; -import com.dotmarketing.portlets.dashboard.model.DashboardSummary404; -import com.dotmarketing.portlets.dashboard.model.DashboardUserPreferences; -import com.dotmarketing.portlets.rules.util.RulesImportExportUtil; -import com.dotmarketing.portlets.structure.model.Field; -import com.dotmarketing.portlets.structure.model.FieldVariable; import com.dotmarketing.portlets.structure.model.Structure; -import com.dotmarketing.portlets.workflows.util.WorkflowImportExportUtil; -import com.dotmarketing.tag.model.Tag; -import com.dotmarketing.tag.model.TagInode; import com.dotmarketing.util.AdminLogger; import com.dotmarketing.util.Config; import com.dotmarketing.util.ConfigUtils; -import com.dotmarketing.util.HibernateCollectionConverter; -import com.dotmarketing.util.HibernateMapConverter; import com.dotmarketing.util.ImportExportUtil; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; @@ -63,41 +38,33 @@ import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; import com.dotmarketing.util.ZipUtil; -import com.google.common.collect.ImmutableList; -import com.liferay.portal.ejb.ImageLocalManagerUtil; -import com.liferay.portal.ejb.PortletPreferencesLocalManagerUtil; -import com.liferay.portal.model.Company; -import com.liferay.portal.model.User; -import com.liferay.portal.util.PortalUtil; -import com.liferay.portlet.ActionRequestImpl; -import com.liferay.portlet.ActionResponseImpl; -import com.liferay.util.FileUtil; -import com.liferay.util.servlet.SessionMessages; -import com.liferay.util.servlet.UploadPortletRequest; -import java.io.BufferedOutputStream; + import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigDecimal; -import java.nio.file.Files; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.ArrayList; import java.util.Date; import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.zip.ZipOutputStream; -import javax.servlet.ServletException; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.PageContext; +import com.google.common.collect.ImmutableList; +import com.liferay.portal.util.PortalUtil; +import com.liferay.portlet.ActionRequestImpl; +import com.liferay.portlet.ActionResponseImpl; +import com.liferay.util.FileUtil; +import com.liferay.util.servlet.SessionMessages; +import com.liferay.util.servlet.UploadPortletRequest; + /** * This class group all the CMS Maintenance Task * (Cache controll, search and replace, import/export content ) @@ -277,42 +244,7 @@ else if(cmd.equals("dropoldassets")){ boolean dataOnly = Parameter.getBooleanFromString(req.getParameter("dataOnly"), true); if(cmd.equals("createZip")) { - if(!dataOnly){ - moveAssetsToBackupDir(); - } - message = "Creating XML Files. "; - createXMLFiles(); - String x = UtilMethods.dateToJDBC(new Date()).replace(':', '-').replace(' ', '_'); - File zipFile = new File(backupFilePath + "/backup_" + x + "_.zip"); - message +="Zipping up to file:" + zipFile.getAbsolutePath(); - final BufferedOutputStream bout = new BufferedOutputStream(Files.newOutputStream(zipFile.toPath())); - - zipTempDirectoryToStream(bout); - message +=". Done."; - -// }else if(cmd.equals("wipeOutDotCMSDatabase")) { -// -// message = "Deleted dotCMS Database"; -// deleteDotCMS(); - - }else if(cmd.equals("downloadZip")) { - - message ="File Downloaded"; - String x = UtilMethods.dateToJDBC(new Date()).replace(':', '-').replace(' ', '_'); - File zipFile = new File(backupFilePath + "/backup_" + x + "_.zip"); - - ActionResponseImpl responseImpl = (ActionResponseImpl) res; - HttpServletResponse httpResponse = responseImpl.getHttpServletResponse(); - httpResponse.setHeader("Content-type", ""); - httpResponse.setHeader("Content-Disposition", "attachment; filename=" + zipFile.getName()); - - if(!dataOnly){ - moveAssetsToBackupDir(); - } - - createXMLFiles(); - zipTempDirectoryToStream(httpResponse.getOutputStream()); }else if(cmd.equals("upload")) { @@ -547,339 +479,7 @@ private void moveAssetsToBackupDir() throws FileNotFoundException, IOException{ /** - * This method will pull a list of all tables /classed being managed by - * hibernate and export them, one class per file to the backupTempFilePath - * as valid XML. It uses XStream to write the xml out to the files. - * - * @throws ServletException - * @throws IOException - * @author Will - * @throws DotDataException - */ - private void createXMLFiles() throws ServletException, IOException, DotDataException, DotSecurityException { - -// deleteTempFiles(); - - Logger.info(this, "Starting createXMLFiles()"); - - Set _tablesToDump = new HashSet(); - try { - - /* get a list of all our tables */ - Map map = new HashMap(); - //Including Identifier.class because it is not mapped with Hibernate anymore - map.put(Identifier.class, null); - - map.putAll(HibernateUtil.getSession().getSessionFactory().getAllClassMetadata()); - - Iterator it = map.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry pairs = (Map.Entry) it.next(); - Class x = (Class) pairs.getKey(); - if (!x.equals(Inode.class) && !x.equals(Clickstream.class) && !x.equals(ClickstreamRequest.class) && !x.equals(Clickstream404.class)) - _tablesToDump.add(x); - - } - - XStream _xstream = null; - HibernateUtil _dh = null; - DotConnect dc = null; - List _list = null; - File _writing = null; - BufferedOutputStream _bout = null; - - for (Class clazz : _tablesToDump) { - if(clazz.equals(Structure.class) || clazz.equals(Field.class) || clazz.equals(FieldVariable.class)){ - continue; - } - - //http://jira.dotmarketing.net/browse/DOTCMS-5031 - if(PermissionReference.class.equals(clazz)){ - continue; - } - - _xstream = new XStream(new DomDriver()); - - //http://jira.dotmarketing.net/browse/DOTCMS-6059 - if(clazz.equals(DashboardSummary404.class) || clazz.equals(DashboardUserPreferences.class)){ - _xstream.addDefaultImplementation(com.dotcms.repackage.net.sf.hibernate.collection.Set.class, java.util.Set.class); - _xstream.addDefaultImplementation(com.dotcms.repackage.net.sf.hibernate.collection.List.class, java.util.List.class); - _xstream.addDefaultImplementation(com.dotcms.repackage.net.sf.hibernate.collection.Map.class, java.util.Map.class); - Mapper mapper = _xstream.getMapper(); - _xstream.registerConverter(new HibernateCollectionConverter(mapper)); - _xstream.registerConverter(new HibernateMapConverter(mapper)); - } - - /* - * String _shortClassName = - * clazz.getName().substring(clazz.getName().lastIndexOf("."),clazz.getName().length()); - * xstream.alias(_shortClassName, clazz); - */ - int i= 0; - int step = 1000; - int total =0; - java.text.NumberFormat formatter = new java.text.DecimalFormat("0000000000"); - /* we will only export 10,000,000 items of any given type */ - for(i=0;i < 10000000;i=i+step){ - - _dh = new HibernateUtil(clazz); - _dh.setFirstResult(i); - _dh.setMaxResults(step); - - //This line was previously like; - //_dh.setQuery("from " + clazz.getName() + " order by 1,2"); - //This caused a problem when the database is Oracle because Oracle causes problems when the results are ordered - //by an NCLOB field. In the case of dot_containers table, the second field, CODE, is an NCLOB field. Because of this, - //ordering is done only on the first field for the tables, which is INODE - if(com.dotmarketing.beans.Tree.class.equals(clazz)){ - _dh.setQuery("from " + clazz.getName() + " order by parent, child, relation_type"); - } - else if(MultiTree.class.equals(clazz)){ - _dh.setQuery("from " + clazz.getName() + " order by parent1, parent2, child, relation_type"); - } - else if(TagInode.class.equals(clazz)){ - _dh.setQuery("from " + clazz.getName() + " order by inode, tag_id"); - } - else if(Tag.class.equals(clazz)){ - _dh.setQuery("from " + clazz.getName() + " order by tag_id, tagname"); - } - else if(CalendarReminder.class.equals(clazz)){ - _dh.setQuery("from " + clazz.getName() + " order by user_id, event_id, send_date"); - } - else if(Identifier.class.equals(clazz)){ - dc = new DotConnect(); - dc.setSQL("select * from identifier order by parent_path, id") - .setStartRow(i).setMaxRows(step); - } else { - _dh.setQuery("from " + clazz.getName() + " order by 1"); - } - - if(Identifier.class.equals(clazz)){ - _list = TransformerLocator - .createIdentifierTransformer(dc.loadObjectResults()).asList(); - }else{ - _list = _dh.list(); - } - - if(_list.size() ==0){ - try { - _bout.close(); - } - catch( java.lang.NullPointerException npe){} - _bout = null; - - break; - } - - if(_list != null && _list.size() > 0 && _list.get(0) instanceof Comparable){ - java.util.Collections.sort(_list); - } - - _writing = new File(backupTempFilePath + "/" + clazz.getName() + "_" + formatter.format(i) + ".xml"); - _bout = new BufferedOutputStream(Files.newOutputStream(_writing.toPath())); - - total = total + _list.size(); - - try { - Thread.sleep(10); - } catch (InterruptedException e) { - Logger.warn(this, "An error ocurred trying to create XML files"); - Logger.error(this,e.getMessage(),e); - } - - try { - _xstream.toXML(_list, _bout); - } finally { - _bout.close(); - } - - _bout = null; - - } - Logger.info(this, "writing : " + total + " records for " + clazz.getName()); - } - - - /* Run Liferay's Tables */ - /* Companies */ - _list = PublicCompanyFactory.getCompanies(); - List companies = new ArrayList(_list); - _xstream = new XStream(new DomDriver()); - _writing = new File(backupTempFilePath + "/" + Company.class.getName() + ".xml"); - _bout = new BufferedOutputStream(Files.newOutputStream(_writing.toPath())); - try { - _xstream.toXML(_list, _bout); - } finally { - _bout.close(); - } - - /* Users */ - _list = APILocator.getUserAPI().findAllUsers(); - _list.add(APILocator.getUserAPI().getDefaultUser()); - _xstream = new XStream(new DomDriver()); - _writing = new File(backupTempFilePath + "/" + User.class.getName() + ".xml"); - _bout = new BufferedOutputStream(Files.newOutputStream(_writing.toPath())); - try { - _xstream.toXML(_list, _bout); - } finally { - _bout.close(); - } - - /* users_roles */ - dc = new DotConnect(); - - /* counter */ - dc.setSQL("select * from counter"); - _list = dc.getResults(); - _xstream = new XStream(new DomDriver()); - _writing = new File(backupTempFilePath + "/Counter.xml"); - _bout = new BufferedOutputStream(Files.newOutputStream(_writing.toPath())); - try { - _xstream.toXML(_list, _bout); - } finally { - _bout.close(); - } - - /* counter */ - dc.setSQL("select * from address"); - _list = dc.getResults(); - _xstream = new XStream(new DomDriver()); - _writing = new File(backupTempFilePath + "/Address.xml"); - _bout = new BufferedOutputStream(Files.newOutputStream(_writing.toPath())); - try { - _xstream.toXML(_list, _bout); - } finally { - _bout.close(); - } - - /* pollschoice */ - dc.setSQL("select * from pollschoice"); - _list = dc.getResults(); - _xstream = new XStream(new DomDriver()); - _writing = new File(backupTempFilePath + "/Pollschoice.xml"); - _bout = new BufferedOutputStream(Files.newOutputStream(_writing.toPath())); - try { - _xstream.toXML(_list, _bout); - } finally { - _bout.close(); - } - - /* pollsdisplay */ - dc.setSQL("select * from pollsdisplay"); - _list = dc.getResults(); - _xstream = new XStream(new DomDriver()); - _writing = new File(backupTempFilePath + "/Pollsdisplay.xml"); - _bout = new BufferedOutputStream(Files.newOutputStream(_writing.toPath())); - try { - _xstream.toXML(_list, _bout); - } finally { - _bout.close(); - } - - /* pollsquestion */ - dc.setSQL("select * from pollsquestion"); - _list = dc.getResults(); - _xstream = new XStream(new DomDriver()); - _writing = new File(backupTempFilePath + "/Pollsquestion.xml"); - _bout = new BufferedOutputStream(Files.newOutputStream(_writing.toPath())); - try { - _xstream.toXML(_list, _bout); - } finally { - _bout.close(); - } - - /* pollsvote */ - dc.setSQL("select * from pollsvote"); - _list = dc.getResults(); - _xstream = new XStream(new DomDriver()); - _writing = new File(backupTempFilePath + "/Pollsvote.xml"); - _bout = new BufferedOutputStream(Files.newOutputStream(_writing.toPath())); - try { - _xstream.toXML(_list, _bout); - } finally { - _bout.close(); - } - - /* image */ - _list = ImageLocalManagerUtil.getImages(); - - /* - * The changes in this part were made for Oracle databases. Oracle has problems when - * getString() method is called on a LONG field on an Oracle database. Because of this, - * the object is loaded from liferay and DotConnect is not used - * http://jira.dotmarketing.net/browse/DOTCMS-1911 - */ - - _xstream = new XStream(new DomDriver()); - _writing = new File(backupTempFilePath + "/Image.xml"); - _bout = new BufferedOutputStream(Files.newOutputStream(_writing.toPath())); - try { - _xstream.toXML(_list, _bout); - } finally { - _bout.close(); - } - - /* portlet */ - - /* - * The changes in this part were made for Oracle databases. Oracle has problems when - * getString() method is called on a LONG field on an Oracle database. Because of this, - * the object is loaded from liferay and DotConnect is not used - * http://jira.dotmarketing.net/browse/DOTCMS-1911 - */ - dc.setSQL("select * from portlet"); - _list = dc.getResults(); - _xstream = new XStream(new DomDriver()); - _writing = new File(backupTempFilePath + "/Portlet.xml"); - _bout = new BufferedOutputStream(Files.newOutputStream(_writing.toPath())); - try { - _xstream.toXML(_list, _bout); - } finally { - _bout.close(); - } - - /* portlet_preferences */ - - try{ - _list = PortletPreferencesLocalManagerUtil.getPreferences(); - }catch(Exception e){ - Logger.error(this,"Error in retrieveing all portlet preferences"); - } - _xstream = new XStream(new DomDriver()); - _writing = new File(backupTempFilePath + "/Portletpreferences.xml"); - _bout = new BufferedOutputStream(Files.newOutputStream(_writing.toPath())); - try { - _xstream.toXML(_list, _bout); - } finally { - _bout.close(); - } - - //backup content types - File file = new File(backupTempFilePath + File.separator + "ContentTypes-" + ContentTypeImportExportUtil.CONTENT_TYPE_FILE_EXTENSION); - new ContentTypeImportExportUtil().exportContentTypes(file); - - file = new File(backupTempFilePath + "/WorkflowSchemeImportExportObject.json"); - WorkflowImportExportUtil.getInstance().exportWorkflows(file); - - file = new File(backupTempFilePath + "/RuleImportExportObject.json"); - RulesImportExportUtil.getInstance().export(file); - - IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); - - file = new File(backupTempFilePath + "/index_working.json"); - new ESIndexAPI().backupIndex(info.working, file); - - - file = new File(backupTempFilePath + "/index_live.json"); - new ESIndexAPI().backupIndex(info.live, file); - - } catch (Exception e) { - Logger.error(this,e.getMessage(),e); - } - } - - - /** +>>>>>>> origin/master * Will zip up all files in the tmp directory and send the result to the * given OutputStream * diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/cmsmaintenance/ajax/CMSMaintenanceAjax.java b/dotCMS/src/main/java/com/dotmarketing/portlets/cmsmaintenance/ajax/CMSMaintenanceAjax.java index e8a26e285dfe..4f2f6761f1a4 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/cmsmaintenance/ajax/CMSMaintenanceAjax.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/cmsmaintenance/ajax/CMSMaintenanceAjax.java @@ -9,13 +9,16 @@ import com.dotcms.repackage.com.thoughtworks.xstream.mapper.Mapper; import com.dotcms.repackage.org.directwebremoting.WebContextFactory; import com.dotcms.util.CloseUtils; + import com.dotcms.util.transform.TransformerLocator; + import com.dotmarketing.beans.Clickstream; import com.dotmarketing.beans.ClickstreamRequest; import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.Inode; import com.dotmarketing.beans.MultiTree; import com.dotmarketing.beans.PermissionReference; +import com.dotmarketing.beans.Tree; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.CacheLocator; import com.dotmarketing.business.DotCacheException; @@ -27,8 +30,9 @@ import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotRuntimeException; import com.dotmarketing.exception.DotSecurityException; +import com.dotmarketing.factories.DBTreeTransformer; +import com.dotmarketing.factories.MultiTreeFactory; import com.dotmarketing.fixtask.FixTasksExecutor; -import com.dotmarketing.plugin.model.Plugin; import com.dotmarketing.plugin.model.PluginProperty; import com.dotmarketing.portlets.calendar.model.CalendarReminder; import com.dotmarketing.portlets.cmsmaintenance.factories.CMSMaintenanceFactory; @@ -55,16 +59,7 @@ import com.dotmarketing.util.MaintenanceUtil; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.ZipUtil; -import com.liferay.portal.PortalException; -import com.liferay.portal.SystemException; -import com.liferay.portal.ejb.ImageLocalManagerUtil; -import com.liferay.portal.ejb.PortletPreferencesLocalManagerUtil; -import com.liferay.portal.ejb.UserLocalManagerUtil; -import com.liferay.portal.language.LanguageException; -import com.liferay.portal.language.LanguageUtil; -import com.liferay.portal.model.Company; -import com.liferay.portal.model.User; -import com.liferay.util.FileUtil; + import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; @@ -77,17 +72,29 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; -import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.ZipOutputStream; + import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; + import org.quartz.JobExecutionContext; +import com.google.common.collect.ImmutableSet; +import com.liferay.portal.PortalException; +import com.liferay.portal.SystemException; +import com.liferay.portal.ejb.ImageLocalManagerUtil; +import com.liferay.portal.ejb.PortletPreferencesLocalManagerUtil; +import com.liferay.portal.ejb.UserLocalManagerUtil; +import com.liferay.portal.language.LanguageException; +import com.liferay.portal.language.LanguageUtil; +import com.liferay.portal.model.Company; +import com.liferay.portal.model.User; +import com.liferay.util.FileUtil; + /** * This class provides access to maintenance routines that dotCMS users can run * in order to keep their environments as optimized and clean as possible. @@ -348,24 +355,7 @@ public String doBackupExport(String action, boolean dataOnly) throws IOException f.mkdirs(); deleteTempFiles(); String message = ""; - if(action.equals("createZip")) { - if(!dataOnly){ - moveAssetsToBackupDir(); - } - message = "Creating XML Files. "; - createXMLFiles(); - String x = UtilMethods.dateToJDBC(new Date()).replace(':', '-').replace(' ', '_'); - File zipFile = new File(backupFilePath + File.separator + "backup_" + x + "_.zip"); - message +="Zipping up to file:" + zipFile.getAbsolutePath(); - final BufferedOutputStream bout = new BufferedOutputStream(Files.newOutputStream(zipFile.toPath())); - Logger.info(this, "Creating zipped backup file in "+ backupFilePath + " folder. Please wait"); - zipTempDirectoryToStream(bout); - message +=". Done."; - Logger.info(this, "Backup file was created in " +zipFile.getAbsolutePath()); - - - } return message; } @@ -410,316 +400,7 @@ public void moveAssetsToBackupDir() throws FileNotFoundException, IOException{ } - /** - * This method will pull a list of all tables /classed being managed by - * hibernate and export them, one class per file to the backupTempFilePath - * as valid XML. It uses XStream to write the xml out to the files. - * - * @throws ServletException - * @throws IOException - * @author Will - * @throws DotDataException - * @throws DotCacheException - */ - @SuppressWarnings("unchecked") - public void createXMLFiles() throws ServletException, IOException, DotDataException, DotSecurityException { - validateUser(); - Logger.info(this, "Starting createXMLFiles()"); - - Set tablesToDump = new HashSet(); - try { - - /* get a list of all our tables */ - final Map map = new HashMap(); - - //Including Identifier.class because it is not mapped with Hibernate anymore - map.put(Identifier.class, null); - - map.putAll(HibernateUtil.getSession().getSessionFactory().getAllClassMetadata()); - - Iterator it = map.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry pairs = (Map.Entry) it.next(); - Class x = (Class) pairs.getKey(); - if (!x.equals(Inode.class) && !x.equals(Clickstream.class) && !x - .equals(ClickstreamRequest.class) - && !x.equals(Plugin.class) && !x.equals(PluginProperty.class)) { - tablesToDump.add(x); - } - - } - XStream xstream = null; - HibernateUtil dh = null; - DotConnect dc = null; - List list = null; - File writing = null; - BufferedOutputStream bout = null; - - for (Class clazz : tablesToDump) { - if (clazz.equals(Structure.class) || clazz.equals(Field.class) || clazz - .equals(FieldVariable.class)) { - continue; - } - //http://jira.dotmarketing.net/browse/DOTCMS-5031 - if (PermissionReference.class.equals(clazz)) { - continue; - } - - if (com.dotmarketing.portlets.contentlet.business.Contentlet.class - .equals(clazz)) { - Logger.debug(this, - "Processing contentlets. This will take a little bit longer..."); - } - - xstream = new XStream(new DomDriver()); - - //http://jira.dotmarketing.net/browse/DOTCMS-6059 - if (clazz.equals(DashboardSummary404.class) || clazz - .equals(DashboardUserPreferences.class)) { - xstream.addDefaultImplementation( - com.dotcms.repackage.net.sf.hibernate.collection.Set.class, - Set.class); - xstream.addDefaultImplementation( - com.dotcms.repackage.net.sf.hibernate.collection.List.class, - List.class); - xstream.addDefaultImplementation( - com.dotcms.repackage.net.sf.hibernate.collection.Map.class, - Map.class); - Mapper mapper = xstream.getMapper(); - xstream.registerConverter(new HibernateCollectionConverter(mapper)); - xstream.registerConverter(new HibernateMapConverter(mapper)); - } - - int i = 0; - int step = 1000; - int total = 0; - java.text.NumberFormat formatter = new java.text.DecimalFormat("0000000000"); - /* we will only export 10,000,000 items of any given type */ - for (i = 0; i < 10000000; i = i + step) { - - dh = new HibernateUtil(clazz); - dh.setFirstResult(i); - dh.setMaxResults(step); - - //This line was previously like; - //_dh.setQuery("from " + clazz.getName() + " order by 1,2"); - //This caused a problem when the database is Oracle because Oracle causes problems when the results are ordered - //by an NCLOB field. In the case of dot_containers table, the second field, CODE, is an NCLOB field. Because of this, - //ordering is done only on the first field for the tables, which is INODE - if (com.dotmarketing.beans.Tree.class.equals(clazz)) { - dh.setQuery("from " + clazz.getName() + " order by parent, child, relation_type"); - } else if (MultiTree.class.equals(clazz)) { - dh.setQuery("from " + clazz.getName() + " order by parent1, parent2, child, relation_type"); - } else if (TagInode.class.equals(clazz)) { - dh.setQuery("from " + clazz.getName() + " order by inode, tag_id"); - } else if (TemplateVersionInfo.class.equals(clazz)) { - dh.setSQLQuery("SELECT {template_version_info.*} from template_version_info template_version_info, identifier where identifier.id = template_version_info.identifier order by template_version_info.identifier "); - } else if (ContainerVersionInfo.class.equals(clazz)) { - dh.setSQLQuery("SELECT {container_version_info.*} from container_version_info container_version_info, identifier where identifier.id = container_version_info.identifier order by container_version_info.identifier "); - } else if (LinkVersionInfo.class.equals(clazz)) { - dh.setSQLQuery("SELECT {link_version_info.*} from link_version_info link_version_info, identifier where identifier.id = link_version_info.identifier order by link_version_info.identifier "); - } else if (CalendarReminder.class.equals(clazz)) { - dh.setQuery("from " + clazz.getName() + " order by user_id, event_id, send_date"); - } else if (Identifier.class.equals(clazz)) { - dc = new DotConnect(); - dc.setSQL("select * from identifier order by parent_path, id") - .setStartRow(i).setMaxRows(step); - } else { - dh.setQuery("from " + clazz.getName() + " order by 1"); - } - - if(Identifier.class.equals(clazz)){ - list = TransformerLocator - .createIdentifierTransformer(dc.loadObjectResults()).asList(); - }else{ - list = dh.list(); - } - - if (list.size() == 0) { - try { - CloseUtils.closeQuietly(bout); - } catch (java.lang.NullPointerException npe) { - } - bout = null; - - break; - } - - if (list != null && list.size() > 0 && list - .get(0) instanceof Comparable) { - java.util.Collections.sort(list); - } - - writing = new File( - backupTempFilePath + File.separator + clazz.getName() + "_" - + formatter.format(i) + ".xml"); - bout = new BufferedOutputStream(Files.newOutputStream(writing.toPath())); - - total = total + list.size(); - - try { - Thread.sleep(10); - } catch (InterruptedException e) { - Logger.warn(this, "An error occurred trying to create XML files"); - Logger.error(this, e.getMessage(), e); - } - - try { - xstream.toXML(list, bout); - } finally { - CloseUtils.closeQuietly(bout); - } - - bout = null; - - } - Logger.info(this, "writing : " + total + " records for " + clazz.getName()); - } - - /* Run Liferay's Tables */ - /* Companies */ - list = PublicCompanyFactory.getCompanies(); - List companies = new ArrayList(list); - xstream = new XStream(new DomDriver()); - writing = new File( - backupTempFilePath + File.separator + Company.class.getName() + ".xml"); - bout = new BufferedOutputStream(Files.newOutputStream(writing.toPath())); - try { - xstream.toXML(list, bout); - } finally { - CloseUtils.closeQuietly(bout); - } - list = null; - bout = null; - - /* Users */ - list = APILocator.getUserAPI().findAllUsers(); - list.add(APILocator.getUserAPI().getDefaultUser()); - xstream = new XStream(new DomDriver()); - writing = new File( - backupTempFilePath + File.separator + User.class.getName() + ".xml"); - bout = new BufferedOutputStream(Files.newOutputStream(writing.toPath())); - try { - xstream.toXML(list, bout); - } finally { - CloseUtils.closeQuietly(bout); - } - list = null; - bout = null; - - dc = new DotConnect(); - - /* counter */ - dc.setSQL("select * from counter"); - list = dc.getResults(); - xstream = new XStream(new DomDriver()); - writing = new File(backupTempFilePath + File.separator + "Counter.xml"); - bout = new BufferedOutputStream(Files.newOutputStream(writing.toPath())); - try { - xstream.toXML(list, bout); - } finally { - CloseUtils.closeQuietly(bout); - } - list = null; - bout = null; - - /* counter */ - dc.setSQL("select * from address"); - list = dc.getResults(); - xstream = new XStream(new DomDriver()); - writing = new File(backupTempFilePath + File.separator + "Address.xml"); - bout = new BufferedOutputStream(Files.newOutputStream(writing.toPath())); - try { - xstream.toXML(list, bout); - } finally { - CloseUtils.closeQuietly(bout); - } - list = null; - bout = null; - - - /* image */ - list = ImageLocalManagerUtil.getImages(); - - /* - * The changes in this part were made for Oracle databases. Oracle has problems when - * getString() method is called on a LONG field on an Oracle database. Because of this, - * the object is loaded from liferay and DotConnect is not used - * http://jira.dotmarketing.net/browse/DOTCMS-1911 - */ - - xstream = new XStream(new DomDriver()); - writing = new File(backupTempFilePath + File.separator + "Image.xml"); - bout = new BufferedOutputStream(Files.newOutputStream(writing.toPath())); - try { - xstream.toXML(list, bout); - } finally { - CloseUtils.closeQuietly(bout); - } - list = null; - bout = null; - - /* portlet */ - - /* - * The changes in this part were made for Oracle databases. Oracle has problems when - * getString() method is called on a LONG field on an Oracle database. Because of this, - * the object is loaded from liferay and DotConnect is not used - * http://jira.dotmarketing.net/browse/DOTCMS-1911 - */ - dc.setSQL("select * from portlet"); - list = dc.getResults(); - xstream = new XStream(new DomDriver()); - writing = new File(backupTempFilePath + File.separator + "Portlet.xml"); - bout = new BufferedOutputStream(Files.newOutputStream(writing.toPath())); - try { - xstream.toXML(list, bout); - } finally { - CloseUtils.closeQuietly(bout); - } - list = null; - bout = null; - - /* portlet_preferences */ - - try { - list = PortletPreferencesLocalManagerUtil.getPreferences(); - } catch (Exception e) { - Logger.error(this, "Error in retrieveing all portlet preferences"); - } - xstream = new XStream(new DomDriver()); - writing = new File(backupTempFilePath + File.separator + "Portletpreferences.xml"); - bout = new BufferedOutputStream(Files.newOutputStream(writing.toPath())); - try { - xstream.toXML(list, bout); - } finally { - CloseUtils.closeQuietly(bout); - } - list = null; - bout = null; - - //backup content types - File file = new File(backupTempFilePath + File.separator + "ContentTypes-" - + ContentTypeImportExportUtil.CONTENT_TYPE_FILE_EXTENSION); - new ContentTypeImportExportUtil().exportContentTypes(file); - - //backup workflow - file = new File(backupTempFilePath + File.separator - + "WorkflowSchemeImportExportObject.json"); - WorkflowImportExportUtil.getInstance().exportWorkflows(file); - - //Backup Rules. - file = new File( - backupTempFilePath + File.separator + "RuleImportExportObject.json"); - RulesImportExportUtil.getInstance().export(file); - - } catch (Exception e) { - Logger.error(this, e.getMessage(), e); - } finally { - DbConnectionFactory.closeSilently(); - } - - } + /** * Will zip up all files in the tmp directory and send the result to the diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/containers/action/EditContainerAction.java b/dotCMS/src/main/java/com/dotmarketing/portlets/containers/action/EditContainerAction.java index f107c324e0fc..fe3546a1f79c 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/containers/action/EditContainerAction.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/containers/action/EditContainerAction.java @@ -1,18 +1,6 @@ package com.dotmarketing.portlets.containers.action; -import com.dotmarketing.beans.MultiTree; -import com.dotmarketing.exception.DotDataException; -import com.dotmarketing.exception.DotSecurityException; -import com.dotmarketing.factories.MultiTreeFactory; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - +import com.dotcms.rendering.velocity.services.ContainerLoader; import com.dotcms.repackage.javax.portlet.ActionRequest; import com.dotcms.repackage.javax.portlet.ActionResponse; import com.dotcms.repackage.javax.portlet.PortletConfig; @@ -23,6 +11,7 @@ import com.dotcms.repackage.org.apache.struts.action.ActionForm; import com.dotcms.repackage.org.apache.struts.action.ActionMapping; import com.dotcms.repackage.org.apache.struts.action.ActionMessage; + import com.dotmarketing.beans.ContainerStructure; import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; @@ -32,6 +21,8 @@ import com.dotmarketing.business.PermissionAPI; import com.dotmarketing.business.PermissionAPI.PermissionableType; import com.dotmarketing.db.HibernateUtil; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.factories.InodeFactory; import com.dotmarketing.factories.WebAssetFactory; import com.dotmarketing.portal.struts.DotPortletAction; @@ -43,7 +34,6 @@ import com.dotmarketing.portlets.structure.factories.StructureFactory; import com.dotmarketing.portlets.structure.model.Structure; import com.dotmarketing.portlets.templates.model.Template; -import com.dotmarketing.services.ContainerServices; import com.dotmarketing.util.ActivityLogger; import com.dotmarketing.util.HostUtil; import com.dotmarketing.util.InodeUtils; @@ -51,6 +41,16 @@ import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.Validator; import com.dotmarketing.util.WebKeys; + +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + import com.liferay.portal.model.User; import com.liferay.portal.struts.ActionException; import com.liferay.portal.util.Constants; @@ -571,7 +571,7 @@ public void _saveWebAsset(ActionRequest req, ActionResponse res, SessionMessages.add(httpReq, "message", "message.containers.save"); ActivityLogger.logInfo(this.getClass(), "Save WebAsset action", "User " + user.getPrimaryKey() + " saved " + container.getTitle(), HostUtil.hostNameUtil(req, _getUser(req))); // saves to working folder under velocity - ContainerServices.invalidate(container, true); + new ContainerLoader().invalidate(container); // copies the information back into the form bean BeanUtils.copyProperties(form, req @@ -627,13 +627,7 @@ private void saveContainerStructures (ActionRequest req, Container currentContai } } - if (unused) { - List multiTreeList = MultiTreeFactory - .getContainerStructureMultiTree(oldCS.getContainerId(), oldCS.getStructureId()); - for (MultiTree mt : multiTreeList) { - MultiTreeFactory.deleteMultiTree(mt); - } - } + } } @@ -665,7 +659,7 @@ public void _getVersionBackWebAsset(ActionRequest req, ActionResponse res, Container workingContainer = (Container) super._getVersionBackWebAsset( req, res, config, form, user, Container.class, WebKeys.CONTAINER_EDIT); - ContainerServices.invalidate(workingContainer, true); + new ContainerLoader().invalidate(workingContainer); } } diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/containers/business/ContainerAPI.java b/dotCMS/src/main/java/com/dotmarketing/portlets/containers/business/ContainerAPI.java index 233aee2c2c72..d0e3d8ad3776 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/containers/business/ContainerAPI.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/containers/business/ContainerAPI.java @@ -1,19 +1,20 @@ package com.dotmarketing.portlets.containers.business; -import java.util.Date; -import java.util.List; -import java.util.Map; - import com.dotcms.contenttype.model.type.ContentType; + import com.dotmarketing.beans.ContainerStructure; import com.dotmarketing.beans.Host; import com.dotmarketing.business.DotStateException; import com.dotmarketing.exception.DotDataException; -import com.dotmarketing.exception.DotHibernateException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.containers.model.Container; +import com.dotmarketing.portlets.htmlpageasset.model.IHTMLPage; import com.dotmarketing.portlets.structure.model.Structure; -import com.dotmarketing.portlets.templates.model.Template; + +import java.util.Date; +import java.util.List; +import java.util.Map; + import com.liferay.portal.model.User; /** @@ -67,20 +68,6 @@ public interface ContainerAPI { */ public Container getLiveContainerById(String identifier, User user, boolean respectFrontendRoles) throws DotDataException, DotSecurityException; - /** - * - * Retrieves the children working containers attached to the given template - * - * @param parentTemplate - * @return - * @author David H Torres - * @throws DotHibernateException - * @throws DotSecurityException - * @throws DotDataException - * @throws DotStateException - * - */ - public List getContainersInTemplate(Template parentTemplate) throws DotHibernateException, DotStateException, DotDataException, DotSecurityException; /** * @@ -265,4 +252,6 @@ List findContainersForStructure(String structureInode, boolean workin public Container find(String inode, User user, boolean respectFrontendRoles) throws DotDataException, DotSecurityException; + public List getContainersOnPage(IHTMLPage page) throws DotStateException, DotDataException, DotSecurityException; + } diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/containers/business/ContainerAPIImpl.java b/dotCMS/src/main/java/com/dotmarketing/portlets/containers/business/ContainerAPIImpl.java index 6c8add82230f..fac179535ab1 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/containers/business/ContainerAPIImpl.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/containers/business/ContainerAPIImpl.java @@ -3,7 +3,9 @@ import com.dotcms.business.CloseDBIfOpened; import com.dotcms.business.WrapInTransaction; import com.dotcms.contenttype.model.type.ContentType; +import com.dotcms.rendering.velocity.services.ContainerLoader; import com.dotcms.util.transform.TransformerLocator; + import com.dotmarketing.beans.ContainerStructure; import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; @@ -28,12 +30,12 @@ import com.dotmarketing.factories.TreeFactory; import com.dotmarketing.portlets.containers.model.Container; import com.dotmarketing.portlets.contentlet.business.HostAPI; +import com.dotmarketing.portlets.htmlpageasset.model.IHTMLPage; import com.dotmarketing.portlets.structure.model.Structure; import com.dotmarketing.portlets.templates.model.Template; -import com.dotmarketing.services.ContainerServices; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; -import com.liferay.portal.model.User; + import java.util.ArrayList; import java.util.Date; import java.util.Iterator; @@ -41,6 +43,8 @@ import java.util.List; import java.util.Map; +import com.liferay.portal.model.User; + /** * Implementation class of the {@link ContainerAPI}. * @@ -124,7 +128,7 @@ public Container copy(Container source, Host destination, User user, boolean res permissionAPI.copyPermissions(source, newContainer); //saves to working folder under velocity - ContainerServices.invalidate(newContainer, newIdentifier, true); + new ContainerLoader().invalidate(newContainer); return newContainer; } @@ -195,6 +199,7 @@ private String getAppendToContainerTitle(final String containerTitle, Host desti containers = TransformerLocator.createContainerTransformer(dc.loadObjectResults()).asList(); + boolean isContainerTitle = false; for (; !isContainerTitle; ) { @@ -250,36 +255,38 @@ public Container getLiveContainerById(String id, User user, boolean respectFront return find(info.getLiveInode(), user, respectFrontendRoles); } - @CloseDBIfOpened - @Override - @SuppressWarnings("unchecked") - public List getContainersInTemplate(final Template parentTemplate) - throws DotStateException, DotDataException, DotSecurityException { - List identifiers = new ArrayList<>(); - DotConnect dc = new DotConnect(); - dc.setSQL( - "select template_containers_2_.* from template_containers, identifier template_containers_1_,identifier template_containers_2_ " - + - "where template_containers.template_id = template_containers_1_.id and " + - "template_containers.container_id = template_containers_2_.id " + - "and template_containers.template_id = ? "); - dc.addParam(parentTemplate.getIdentifier()); - identifiers = TransformerLocator.createIdentifierTransformer(dc.loadObjectResults()).asList(); + @CloseDBIfOpened + @Override + @SuppressWarnings("unchecked") + public List getContainersOnPage(final IHTMLPage page) + throws DotStateException, DotDataException, DotSecurityException { + + final List containers = new ArrayList<>(); + List identifiers = new ArrayList<>(); + DotConnect dc = new DotConnect(); + dc.setSQL("select * from identifier where id in (select distinct(parent2) as containers from multi_tree where parent1=?)"); + dc.addParam(page.getIdentifier()); - final List containers = new ArrayList<>(); - for (Identifier id : identifiers) { - final Container cont = (Container) APILocator.getVersionableAPI() - .findWorkingVersion(id, APILocator.getUserAPI().getSystemUser(), false); - containers.add(cont); - } - return containers; - } + identifiers = TransformerLocator.createIdentifierTransformer(dc.loadObjectResults()).asList(); + + + + + final List pageContainers = new ArrayList<>(); + for (Identifier id : identifiers) { + final Container cont = (Container) APILocator.getVersionableAPI() + .findWorkingVersion(id, APILocator.getUserAPI().getSystemUser(), false); + pageContainers.add(cont); + } + return containers; + } + @WrapInTransaction @Override public void saveContainerStructures(final List containerStructureList) throws DotStateException, DotDataException, DotSecurityException { @@ -450,7 +457,7 @@ public Container save(Container container, List containerStr } saveContainerStructures(containerStructureList); // saves to working folder under velocity - ContainerServices.invalidate(container, true); + new ContainerLoader().invalidate(container); return container; } @@ -496,11 +503,7 @@ public List findContainers(User user, boolean includeArchived, return containerFactory.findContainers(user, includeArchived, params, hostId, inode, identifier, parent, offset, limit, orderBy); } - @CloseDBIfOpened - @Override - public List findContainersForStructure(String structureInode) throws DotDataException { - return containerFactory.findContainersForStructure(structureInode); - } + @CloseDBIfOpened @Override @@ -519,18 +522,20 @@ public int deleteOldVersions(Date assetsOlderThan) throws DotStateException, Dot public void deleteContainerStructureByContentType(final ContentType type) throws DotDataException { - List containers = findContainersForStructure(type.id()); new DotConnect() .setSQL("DELETE FROM container_structures WHERE structure_id = ?") .addParam(type.id()) .loadResult(); - for(Container container : containers){ - CacheLocator.getContentTypeCache().removeContainerStructures(container.getIdentifier(), container.getInode()); - } + } + @CloseDBIfOpened + @Override + public List findContainersForStructure(String structureInode) throws DotDataException { + return containerFactory.findContainersForStructure(structureInode); + } @WrapInTransaction @Override diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/containers/business/ContainerFactoryImpl.java b/dotCMS/src/main/java/com/dotmarketing/portlets/containers/business/ContainerFactoryImpl.java index b9fe38d3968e..dc07ab6e1916 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/containers/business/ContainerFactoryImpl.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/containers/business/ContainerFactoryImpl.java @@ -3,6 +3,7 @@ import com.dotcms.contenttype.business.ContentTypeAPI; import com.dotcms.contenttype.model.type.ContentType; import com.dotcms.util.transform.TransformerLocator; + import com.dotmarketing.beans.ContainerStructure; import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Inode; @@ -26,12 +27,14 @@ import com.dotmarketing.util.Logger; import com.dotmarketing.util.PaginatedArrayList; import com.dotmarketing.util.UtilMethods; -import com.liferay.portal.model.User; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import com.liferay.portal.model.User; + public class ContainerFactoryImpl implements ContainerFactory { static IdentifierCache identifierCache = CacheLocator.getIdentifierCache(); static ContainerCache containerCache = CacheLocator.getContainerCache(); @@ -66,9 +69,9 @@ public List findContainersUnder(Host parentPermissionable) throws Dot sql.append('\''); dc.setSQL(sql.toString()); - return TransformerLocator.createContainerTransformer(dc.loadObjectResults()).asList(); + } @SuppressWarnings("unchecked") @@ -90,9 +93,9 @@ public List findAllContainers() throws DotDataException { sql.append(".title"); dc.setSQL(sql.toString()); - return TransformerLocator.createContainerTransformer(dc.loadObjectResults()).asList(); + } @Override @SuppressWarnings("unchecked") @@ -261,6 +264,7 @@ public List findContainers(User user, boolean includeArchived, dc.setStartRow(internalOffset); dc.setMaxRows(internalLimit); resultList = TransformerLocator.createContainerTransformer(dc.loadObjectResults()).asList(); + PermissionAPI permAPI = APILocator.getPermissionAPI(); toReturn.addAll(permAPI.filterCollection(resultList, PermissionAPI.PERMISSION_READ, false, user)); if(countLimit > 0 && toReturn.size() >= countLimit + offset) diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/containers/factories/ContainerFactory.java b/dotCMS/src/main/java/com/dotmarketing/portlets/containers/factories/ContainerFactory.java index 4d381f8fbc44..439a8789cfbb 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/containers/factories/ContainerFactory.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/containers/factories/ContainerFactory.java @@ -1,7 +1,6 @@ package com.dotmarketing.portlets.containers.factories; -import java.util.LinkedList; -import java.util.List; +import com.dotcms.rendering.velocity.services.ContainerLoader; import com.dotmarketing.beans.ContainerStructure; import com.dotmarketing.beans.Host; @@ -16,8 +15,10 @@ import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.containers.model.Container; import com.dotmarketing.portlets.contentlet.business.HostAPI; -import com.dotmarketing.services.ContainerServices; import com.dotmarketing.util.Logger; + +import java.util.LinkedList; +import java.util.List; /** * * @author will @@ -136,8 +137,7 @@ public static Container copyContainer (Container currentContainer) throws DotDat perAPI.copyPermissions(currentContainer, newContainer); //saves to working folder under velocity - ContainerServices.invalidate(newContainer, newIdentifier, - true); + new ContainerLoader().invalidate(newContainer); // issue-2093 Copying multiple structures per container if(currentContainer.getMaxContentlets()>0) { diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/action/OrderContentletAction.java b/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/action/OrderContentletAction.java deleted file mode 100644 index b657cb1dc93c..000000000000 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/action/OrderContentletAction.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.dotmarketing.portlets.contentlet.action; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import com.dotcms.repackage.javax.portlet.ActionRequest; -import com.dotcms.repackage.javax.portlet.ActionResponse; -import com.dotcms.repackage.javax.portlet.PortletConfig; - -import com.dotcms.repackage.org.apache.struts.action.ActionForm; -import com.dotcms.repackage.org.apache.struts.action.ActionMapping; - -import com.dotmarketing.beans.Identifier; -import com.dotmarketing.beans.MultiTree; -import com.dotmarketing.business.APILocator; -import com.dotmarketing.db.HibernateUtil; -import com.dotmarketing.factories.InodeFactory; -import com.dotmarketing.factories.MultiTreeFactory; -import com.dotmarketing.portal.struts.DotPortletAction; -import com.dotmarketing.portlets.containers.model.Container; -import com.dotmarketing.portlets.contentlet.business.ContentletAPI; -import com.dotmarketing.portlets.contentlet.model.Contentlet; -import com.dotmarketing.portlets.htmlpageasset.model.IHTMLPage; -import com.dotmarketing.util.InodeUtils; -import com.dotmarketing.util.Logger; -import com.dotmarketing.util.WebKeys; -import com.liferay.portal.struts.ActionException; -import com.liferay.portlet.ActionRequestImpl; - -public class OrderContentletAction extends DotPortletAction { - - public static boolean debug = false; - - private ContentletAPI conAPI = APILocator.getContentletAPI(); - - public void processAction( - ActionMapping mapping, ActionForm form, PortletConfig config, - ActionRequest req, ActionResponse res) - throws Exception { - - try { - String cmd = req.getParameter("cmd"); - - if (((cmd != null) && cmd.equals("generatemenu"))) { - HibernateUtil.startTransaction(); - //regenerates menu files - _orderMenuItemsDragAndDrop(req,res,config,form); - HibernateUtil.closeAndCommitTransaction(); - _sendToReferral(req,res,req.getParameter("referer")); - return; - } - - _getMenuItems(req,res,config,form); - setForward(req,"portlet.ext.contentlet.order_contentlets"); - - } catch (ActionException ae) { - _handleException(ae,req); - } - - } - - private void _getMenuItems(ActionRequest req, ActionResponse res,PortletConfig config,ActionForm form) - throws Exception { - - Container container = (Container) InodeFactory.getInode(req.getParameter("containerId"),Container.class); - IHTMLPage page= (IHTMLPage) InodeFactory.getInode(req.getParameter("pageId"),IHTMLPage.class); - String languaje_id = (String) ((ActionRequestImpl) req).getHttpServletRequest().getSession().getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE); - - Identifier containerIdentifier = APILocator.getIdentifierAPI().find(container); - Identifier pageIdentifier = APILocator.getIdentifierAPI().find(page); - - java.util.List itemsList = new ArrayList(); - //gets menu items for this folder parent - java.util.List itemsIdentifierList = MultiTreeFactory.getChildrenClass(pageIdentifier, containerIdentifier, Identifier.class); - for(Identifier ident : itemsIdentifierList){ - List fatConts = - (List) APILocator.getVersionableAPI().findWorkingVersion(ident,APILocator.getUserAPI().getSystemUser(),false); - for(com.dotmarketing.portlets.contentlet.business.Contentlet fatCont : fatConts) - { - if(InodeUtils.isSet(fatCont.getInode())) - { - Contentlet cont = conAPI.convertFatContentletToContentlet(fatCont); - if(cont.getLanguageId() == Long.parseLong(languaje_id)) - { - itemsList.add(cont); - } - } - } - } - req.setAttribute(WebKeys.MENU_ITEMS,itemsList); - - } - - private void _orderMenuItemsDragAndDrop(ActionRequest req, ActionResponse res,PortletConfig config,ActionForm form) - throws Exception { - try - { - Container container = (Container) InodeFactory.getInode(req.getParameter("containerId"),Container.class); - IHTMLPage page= (IHTMLPage) InodeFactory.getInode(req.getParameter("pageId"),IHTMLPage.class); - - Enumeration parameterNames = req.getParameterNames(); - HashMap> hashMap = new HashMap>(); - while(parameterNames.hasMoreElements()) - { - String parameterName = (String) parameterNames.nextElement(); - if(parameterName.startsWith("list")) - { - String value = req.getParameter(parameterName); - String smallParameterName = parameterName.substring(0,parameterName.indexOf("[")); - String indexString = parameterName.substring(parameterName.indexOf("[") + 1,parameterName.indexOf("]")); - int index = Integer.parseInt(indexString); - if(hashMap.get(smallParameterName) == null) - { - HashMap hashInodes = new HashMap(); - hashInodes.put(index,value); - hashMap.put(smallParameterName,hashInodes); - } - else - { - HashMap hashInodes = (HashMap) hashMap.get(smallParameterName); - hashInodes.put(index,value); - } - } - } - - Set keys = hashMap.keySet(); - Iterator keysIterator = keys.iterator(); - while(keysIterator.hasNext()) - { - String key = (String) keysIterator.next(); - HashMap hashInodes = (HashMap) hashMap.get(key); - for(int i = 0;i < hashInodes.size();i++) - { - String inode = (String) hashInodes.get(i); - Contentlet c = conAPI.find(inode, APILocator.getUserAPI().getSystemUser(), false); - - Identifier containerIdentifier = APILocator.getIdentifierAPI().find(container); - Identifier pageIdentifier = APILocator.getIdentifierAPI().find(page); - Identifier iden = APILocator.getIdentifierAPI().find(c); - - MultiTree multiTree = MultiTreeFactory.getMultiTree(pageIdentifier,containerIdentifier,iden); - multiTree.setTreeOrder(i); - MultiTreeFactory.saveMultiTree(multiTree); - } - } - } - catch(Exception ex) - { - Logger.error(this, "_orderContentletItemsDragAndDrop: Exception ocurred.", ex); - throw ex; - } - } - - -} diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/ajax/ContentletAjax.java b/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/ajax/ContentletAjax.java index 8a5ec48acc61..07d9a04d219c 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/ajax/ContentletAjax.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/ajax/ContentletAjax.java @@ -71,7 +71,8 @@ import com.dotmarketing.util.DateUtil; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; -import com.dotmarketing.util.PageRequestModeUtil; +import com.dotmarketing.util.PageMode; + import com.dotmarketing.util.PaginatedArrayList; import com.dotmarketing.util.RegEX; import com.dotmarketing.util.RegExMatch; @@ -1426,8 +1427,8 @@ public Map saveContent(List formData, boolean isAutoSave, iCanLock=false; contentLocked = false; } - - PageRequestModeUtil.setBackEndModeInSession(req, contentLocked, iCanLock); + PageMode.setPageMode(req, contentLocked, iCanLock); + } } diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/business/ContentletFactory.java b/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/business/ContentletFactory.java index ed7c811dcbde..23214c46de8e 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/business/ContentletFactory.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/business/ContentletFactory.java @@ -361,4 +361,10 @@ public abstract class ContentletFactory { */ public abstract List> getMostViewedContent(String structureInode,Date startDate, Date endDate, User user) throws DotDataException; + protected List findPageContentlets(String HTMLPageIdentifier, String containerId, String uniqueId, String orderby, + boolean working, long languageId) throws DotDataException, DotStateException, DotSecurityException { + // TODO Auto-generated method stub + return null; + } + } \ No newline at end of file diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/business/web/ContentletWebAPIImpl.java b/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/business/web/ContentletWebAPIImpl.java index b12ea208bfa6..fedd534bcc9f 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/business/web/ContentletWebAPIImpl.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/contentlet/business/web/ContentletWebAPIImpl.java @@ -282,13 +282,13 @@ private void _addToParents(Map contentletFormData, User user,boo Identifier containerIdentifier = identifierAPI.find(containerParent); Identifier contenletIdentifier = identifierAPI.find(contentlet); MultiTree multiTree = MultiTreeFactory.getMultiTree(htmlParentId, containerIdentifier, - contenletIdentifier); + contenletIdentifier, MultiTree.LEGACY_RELATION_TYPE); Logger.debug(this, "Getting multitree for=" + htmlpage_inode + " ," + containerParent.getInode() + " ," + contentlet.getIdentifier()); Logger.debug(this, "Coming from multitree parent1=" + multiTree.getParent1() + " parent2=" + multiTree.getParent2()); - int contentletCount = MultiTreeFactory.getMultiTree(htmlParentId).size(); + int contentletCount = MultiTreeFactory.getMultiTrees(htmlParentId).size(); if (!InodeUtils.isSet(multiTree.getParent1()) && !InodeUtils.isSet(multiTree.getParent2()) && !InodeUtils.isSet(multiTree.getChild())) { Logger.debug(this, "MTree is null!!! Creating new one!"); diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/director/action/DirectorAction.java b/dotCMS/src/main/java/com/dotmarketing/portlets/director/action/DirectorAction.java index d55ff934977f..9b146f598b8f 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/director/action/DirectorAction.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/director/action/DirectorAction.java @@ -500,7 +500,7 @@ else if (workingLink.isLocked()) { if (InodeUtils.isSet(identifier.getInode()) && InodeUtils.isSet(htmlPageIdentifier.getInode()) && InodeUtils.isSet(containerIdentifier.getInode())) { MultiTree mTree = new MultiTree(htmlPageIdentifier.getInode(),containerIdentifier.getInode(),identifier.getInode()); - java.util.List treeList= MultiTreeFactory.getMultiTree(htmlPage, container); + java.util.List treeList= MultiTreeFactory.getMultiTrees(htmlPage.getIdentifier(), container.getIdentifier()); for (int i = 0; i < treeList.size(); i++) { if(treeList.get(i).getChild().equals(identifier.getInode())){ duplicateContentCheck = true; @@ -594,7 +594,7 @@ else if (workingLink.isLocked()) { Identifier htmlPageIdentifier = APILocator.getIdentifierAPI().find(htmlPage); Identifier containerIdentifier = APILocator.getIdentifierAPI().find(container); - MultiTree multiTree = MultiTreeFactory.getMultiTree(htmlPageIdentifier,containerIdentifier,identifier); + MultiTree multiTree = MultiTreeFactory.getMultiTree(htmlPageIdentifier,containerIdentifier,identifier, MultiTree.LEGACY_RELATION_TYPE); Logger.debug(DirectorAction.class, "multiTree=" + multiTree); MultiTreeFactory.deleteMultiTree(multiTree); } catch (DotRuntimeException e) { @@ -688,7 +688,7 @@ else if (workingLink.isLocked()) { if( newPosition == x ) { iden = APILocator.getIdentifierAPI().find(contentlet); - multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage,idenContainer,iden); + multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage,idenContainer,iden, MultiTree.LEGACY_RELATION_TYPE); multiTree.setTreeOrder(x); MultiTreeFactory.saveMultiTree(multiTree, htmlPage.getLanguageId()); x++; @@ -696,7 +696,7 @@ else if (workingLink.isLocked()) { if (!c.getInode().equalsIgnoreCase(contentlet.getInode())) { iden = APILocator.getIdentifierAPI().find(c); - multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage,idenContainer,iden); + multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage,idenContainer,iden, MultiTree.LEGACY_RELATION_TYPE); multiTree.setTreeOrder(x); MultiTreeFactory.saveMultiTree(multiTree, htmlPage.getLanguageId()); x++; @@ -757,7 +757,7 @@ else if (workingLink.isLocked()) { if (!c.getInode().equalsIgnoreCase(contentlet.getInode())) { iden = APILocator.getIdentifierAPI().find(c); - multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage,idenContainer,iden); + multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage,idenContainer,iden, MultiTree.LEGACY_RELATION_TYPE); multiTree.setTreeOrder(x); MultiTreeFactory.saveMultiTree(multiTree, htmlPage.getLanguageId()); x++; @@ -765,7 +765,7 @@ else if (workingLink.isLocked()) { if( newPosition == x ) { iden = APILocator.getIdentifierAPI().find(contentlet); - multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage,idenContainer,iden); + multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage,idenContainer,iden, MultiTree.LEGACY_RELATION_TYPE); multiTree.setTreeOrder(x); MultiTreeFactory.saveMultiTree(multiTree, htmlPage.getLanguageId()); x++; diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/folders/business/FolderFactoryImpl.java b/dotCMS/src/main/java/com/dotmarketing/portlets/folders/business/FolderFactoryImpl.java index 87979088fd81..ff6735553da3 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/folders/business/FolderFactoryImpl.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/folders/business/FolderFactoryImpl.java @@ -170,7 +170,9 @@ private List getSubFolders(Boolean showOnMenu, String path, final String dc.addParam(hostId); try{ + return TransformerLocator.createFolderTransformer(dc.loadObjectResults()).asList(); + }catch(DotDataException e){ Logger.error(this, e.getMessage(), e); } @@ -225,8 +227,10 @@ protected Folder findFolderByPath(String path, Host host) throws DotDataExceptio dc.addParam(parentPath.toLowerCase()); dc.addParam(hostId); + result = TransformerLocator.createFolderTransformer(dc.loadObjectResults()).asList(); + if (result != null && !result.isEmpty()){ folder = result.get(0); }else{ @@ -274,9 +278,11 @@ protected Folder findFolderByPath(String path, Host host) throws DotDataExceptio dc.addParam(parentPath.toLowerCase()); dc.addParam(hostId); + result = TransformerLocator.createFolderTransformer(dc.loadObjectResults()) .asList(); + if (result != null && !result.isEmpty()){ folder = result.get(0); } @@ -530,7 +536,7 @@ private void saveCopiedFolder(Folder source, Folder newFolder, Hashtable copiedO for(IHTMLPage page : pageAssetList) { Contentlet cont = APILocator.getContentletAPI().find(page.getInode(), APILocator.getUserAPI().getSystemUser(), false); Contentlet newContent = APILocator.getContentletAPI().copyContentlet(cont, newFolder, APILocator.getUserAPI().getSystemUser(), false); - List pageContents = MultiTreeFactory.getMultiTree(cont.getIdentifier()); + List pageContents = MultiTreeFactory.getMultiTrees(cont.getIdentifier()); for(MultiTree m : pageContents){ MultiTree mt = new MultiTree(newContent.getIdentifier(), m.getParent2(), m.getChild()); MultiTreeFactory.saveMultiTree(mt); @@ -1120,12 +1126,14 @@ protected List getChildrenClass ( Identifier identifier, Class clazz, } try { + DBTransformer transformer = TransformerLocator.createDBTransformer(dc.loadObjectResults(), clazz); if (transformer != null){ return transformer.asList(); } + }catch(Exception e){ Logger.warn(this, e.getMessage(), e); } diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/form/business/FormAPIImpl.java b/dotCMS/src/main/java/com/dotmarketing/portlets/form/business/FormAPIImpl.java index 1569649642a4..e36cbb459ab0 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/form/business/FormAPIImpl.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/form/business/FormAPIImpl.java @@ -1,10 +1,9 @@ package com.dotmarketing.portlets.form.business; -import java.util.ArrayList; -import java.util.List; - import com.dotcms.business.CloseDBIfOpened; import com.dotcms.business.WrapInTransaction; +import com.dotcms.rendering.velocity.services.ContentTypeLoader; + import com.dotmarketing.beans.Permission; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.CacheLocator; @@ -20,11 +19,13 @@ import com.dotmarketing.portlets.structure.factories.StructureFactory; import com.dotmarketing.portlets.structure.model.Field; import com.dotmarketing.portlets.structure.model.Structure; -import com.dotmarketing.services.StructureServices; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; import com.dotmarketing.util.StringUtils; -import com.dotmarketing.util.VelocityUtil; + +import java.util.ArrayList; +import java.util.List; + import com.liferay.portal.model.User; /** @@ -145,7 +146,7 @@ public void createFormWidgetInstanceStructure() throws DotDataException,DotState /*Saving the structure in cache*/ CacheLocator.getContentTypeCache().remove(structure); CacheLocator.getContentTypeCache().add(structure); - StructureServices.removeStructureFile(structure); + new ContentTypeLoader().invalidate(structure); /*Adding Widget Fields*/ Field formIdField = new Field(FORM_WIDGET_FORM_ID_FIELD_NAME,Field.FieldType.TEXT,Field.DataType.TEXT,structure,true,true,true,1,"", "", "", true, false, true); diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/hostvariable/bussiness/HostVariableAPIImpl.java b/dotCMS/src/main/java/com/dotmarketing/portlets/hostvariable/bussiness/HostVariableAPIImpl.java index f9c15d7c0ba5..66cf29f996c7 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/hostvariable/bussiness/HostVariableAPIImpl.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/hostvariable/bussiness/HostVariableAPIImpl.java @@ -1,10 +1,9 @@ package com.dotmarketing.portlets.hostvariable.bussiness; -import java.util.Date; -import java.util.List; - import com.dotcms.business.CloseDBIfOpened; import com.dotcms.business.WrapInTransaction; +import com.dotcms.rendering.velocity.services.SiteLoader; + import com.dotmarketing.beans.Host; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.FactoryLocator; @@ -13,7 +12,10 @@ import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.contentlet.business.HostAPI; import com.dotmarketing.portlets.hostvariable.model.HostVariable; -import com.dotmarketing.services.HostServices; + +import java.util.Date; +import java.util.List; + import com.liferay.portal.model.User; public class HostVariableAPIImpl implements HostVariableAPI { @@ -35,7 +37,7 @@ public void delete(HostVariable object, User user, boolean respectFrontendRoles) throw new DotSecurityException("User doesn't have permission to edit the host variable= " + object.getId()); hostVariableFactory.delete(object); - HostServices.invalidate(host); + new SiteLoader().invalidate(host); } @@ -83,7 +85,8 @@ public void save( HostVariable object, User user, boolean respectFrontendRoles) throw new DotSecurityException("User doesn't have permission to edit the host = " + object.getId()); hostVariableFactory.save(object); - HostServices.invalidate(host); + new SiteLoader().invalidate(host); + } diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/htmlpageasset/business/HTMLPageAssetAPIImpl.java b/dotCMS/src/main/java/com/dotmarketing/portlets/htmlpageasset/business/HTMLPageAssetAPIImpl.java index 8ba3e74f01ec..b928895e023f 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/htmlpageasset/business/HTMLPageAssetAPIImpl.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/htmlpageasset/business/HTMLPageAssetAPIImpl.java @@ -12,6 +12,8 @@ import com.dotcms.mock.request.MockHttpRequest; import com.dotcms.mock.request.MockSessionRequest; import com.dotcms.mock.response.BaseResponse; +import com.dotcms.rendering.velocity.services.VelocityType; + import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.UserProxy; @@ -45,17 +47,13 @@ import com.dotmarketing.util.CookieUtil; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; +import com.dotmarketing.util.PageMode; import com.dotmarketing.util.RegEX; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.VelocityUtil; import com.dotmarketing.util.WebKeys; -import com.dotmarketing.velocity.VelocityServlet; -import com.liferay.portal.model.User; - -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.context.Context; -import org.apache.velocity.exception.ResourceNotFoundException; +import java.io.File; import java.io.StringWriter; import java.util.ArrayList; import java.util.Date; @@ -69,6 +67,13 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.context.Context; +import org.apache.velocity.exception.ResourceNotFoundException; +import org.apache.velocity.servlet.VelocityServlet; + +import com.liferay.portal.model.User; + public class HTMLPageAssetAPIImpl implements HTMLPageAssetAPI { @@ -720,10 +725,7 @@ public String getHTML(String uri, Host host, boolean liveMode, String contentId, if (!liveMode) { - requestProxy.setAttribute(WebKeys.PREVIEW_MODE_SESSION, "true"); - requestProxy.getSession().setAttribute(WebKeys.PREVIEW_MODE_SESSION, "true"); - requestProxy.setAttribute(WebKeys.ADMIN_MODE_SESSION, "true"); - requestProxy.getSession().setAttribute(WebKeys.ADMIN_MODE_SESSION, "true"); + PageMode.setPageMode(requestProxy, PageMode.PREVIEW_MODE); } boolean signedIn = false; @@ -816,9 +818,9 @@ public String getHTML(String uri, Host host, boolean liveMode, String contentId, langStr = "_" + langId; } - String VELOCITY_HTMLPAGE_EXTENSION = Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION"); - String vTempalate = (liveMode) ? "/live/" + idInode + langStr + "." + VELOCITY_HTMLPAGE_EXTENSION - : "/working/" + idInode + langStr + "." + VELOCITY_HTMLPAGE_EXTENSION; + String VELOCITY_HTMLPAGE_EXTENSION = VelocityType.HTMLPAGE.fileExtension; + String vTempalate = (liveMode) ? File.separator+PageMode.LIVE.name() + File.separator+ idInode + langStr + "." + VELOCITY_HTMLPAGE_EXTENSION + : File.separator+PageMode.PREVIEW_MODE.name() + File.separator + idInode + langStr + "." + VELOCITY_HTMLPAGE_EXTENSION; ve.getTemplate(vTempalate).merge(context, out); @@ -826,7 +828,7 @@ public String getHTML(String uri, Host host, boolean liveMode, String contentId, Logger.error(this, e1.getMessage(), e1); } finally { context = null; - VelocityServlet.velocityCtx.remove(); + } if (Config.getBooleanProperty("ENABLE_CLICKSTREAM_TRACKING", false)) { diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/htmlpages/action/PreviewHTMLPageAction.java b/dotCMS/src/main/java/com/dotmarketing/portlets/htmlpages/action/PreviewHTMLPageAction.java index a4ef711f7da5..6667cfa95aa2 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/htmlpages/action/PreviewHTMLPageAction.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/htmlpages/action/PreviewHTMLPageAction.java @@ -1,7 +1,7 @@ package com.dotmarketing.portlets.htmlpages.action; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; + import com.dotcms.repackage.javax.portlet.ActionRequest; import com.dotcms.repackage.javax.portlet.ActionResponse; @@ -20,7 +20,8 @@ import com.dotmarketing.util.ActivityLogger; import com.dotmarketing.util.HostUtil; import com.dotmarketing.util.Logger; -import com.dotmarketing.util.PageRequestModeUtil; +import com.dotmarketing.util.PageMode; + import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; import com.liferay.portal.language.LanguageUtil; @@ -87,7 +88,8 @@ public void processAction(ActionMapping mapping, ActionForm form, PortletConfig HttpServletRequest hreq = reqImpl.getHttpServletRequest(); // gets the session object for the messages - PageRequestModeUtil.setBackEndModeInSession(hreq, contentLocked, iCanLock); + PageMode.setPageMode(hreq, contentLocked, iCanLock); + IHTMLPage htmlPage = _previewHTMLPages(req, user); diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/links/action/EditLinkAction.java b/dotCMS/src/main/java/com/dotmarketing/portlets/links/action/EditLinkAction.java index af7b3895d46f..b6ac214a2fa0 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/links/action/EditLinkAction.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/links/action/EditLinkAction.java @@ -1,12 +1,6 @@ package com.dotmarketing.portlets.links.action; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.Iterator; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - +import com.dotcms.rendering.velocity.services.ContentletLoader; import com.dotcms.repackage.javax.portlet.ActionRequest; import com.dotcms.repackage.javax.portlet.ActionResponse; import com.dotcms.repackage.javax.portlet.PortletConfig; @@ -14,6 +8,7 @@ import com.dotcms.repackage.org.apache.commons.beanutils.BeanUtils; import com.dotcms.repackage.org.apache.struts.action.ActionForm; import com.dotcms.repackage.org.apache.struts.action.ActionMapping; + import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.Inode; @@ -44,12 +39,19 @@ import com.dotmarketing.portlets.links.model.Link.LinkType; import com.dotmarketing.portlets.links.struts.LinkForm; import com.dotmarketing.portlets.structure.model.Structure; -import com.dotmarketing.services.ContentletServices; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.Validator; import com.dotmarketing.util.WebKeys; + +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.Iterator; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + import com.liferay.portal.model.User; import com.liferay.portal.util.Constants; import com.liferay.portlet.ActionRequestImpl; @@ -739,7 +741,7 @@ public void _getVersionBackWebAsset(ActionRequest req, ActionResponse res, if (cont.isWorking()) { com.dotmarketing.portlets.contentlet.model.Contentlet newFormatContentlet = conAPI.convertFatContentletToContentlet(cont); - ContentletServices.invalidateWorking(newFormatContentlet); + new ContentletLoader().invalidate(cont); } } } diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/links/business/MenuLinkFactoryImpl.java b/dotCMS/src/main/java/com/dotmarketing/portlets/links/business/MenuLinkFactoryImpl.java index c70aae02c726..53b6645f7dca 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/links/business/MenuLinkFactoryImpl.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/links/business/MenuLinkFactoryImpl.java @@ -205,7 +205,9 @@ public List findLinks(User user, boolean includeArchived, while(!done) { dc.setStartRow(internalOffset); dc.setMaxRows(internalLimit); + resultList = TransformerLocator.createLinkTransformer(dc.loadObjectResults()).asList(); + PermissionAPI permAPI = APILocator.getPermissionAPI(); toReturn.addAll(permAPI.filterCollection(resultList, PermissionAPI.PERMISSION_READ, false, user)); if(countLimit > 0 && toReturn.size() >= countLimit + offset) diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/links/factories/LinkFactory.java b/dotCMS/src/main/java/com/dotmarketing/portlets/links/factories/LinkFactory.java index e3771e66bd6f..c1d6972f7d00 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/links/factories/LinkFactory.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/links/factories/LinkFactory.java @@ -129,7 +129,9 @@ public static java.util.List getLinkChildrenByCondition(Inode o,String condition dc.addParam(APILocator.getIdentifierAPI().find(o).getPath()); dc.addParam(o.getIdentifier()); + return TransformerLocator.createLinkTransformer(dc.loadObjectResults()).asList(); + } catch (Exception e) { Logger.error(LinkFactory.class, "getLinkChildrenByCondition failed:" + e, e); } diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/rules/business/RulesEngine.java b/dotCMS/src/main/java/com/dotmarketing/portlets/rules/business/RulesEngine.java index ae59a236235b..1d788126daa2 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/rules/business/RulesEngine.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/rules/business/RulesEngine.java @@ -2,6 +2,9 @@ import com.dotcms.enterprise.LicenseUtil; import com.dotcms.enterprise.license.LicenseLevel; +import com.dotcms.rendering.velocity.servlet.VelocityLiveServlet; +import com.dotcms.visitor.domain.Visitor; + import com.dotmarketing.beans.Host; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.Ruleable; @@ -12,6 +15,7 @@ import com.dotmarketing.portlets.rules.exception.RuleEngineException; import com.dotmarketing.portlets.rules.model.Rule; import com.dotmarketing.util.Config; +import com.dotmarketing.util.CookieUtil; import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; @@ -19,6 +23,7 @@ import java.util.*; +import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @@ -68,6 +73,75 @@ public static void fireRules(HttpServletRequest req, HttpServletResponse res, Ru fireRules(req, res, host, fireOn); } + + + + + public static void fireRules(final HttpServletRequest request, final HttpServletResponse response) { + + Optional visitor = APILocator.getVisitorAPI().getVisitor(request); + + boolean newVisitor = false; + boolean newVisit = false; + + /* + * JIRA http://jira.dotmarketing.net/browse/DOTCMS-4659 //Set long lived cookie + * regardless of who this is + */ + String _dotCMSID = + UtilMethods.getCookieValue(request.getCookies(), com.dotmarketing.util.WebKeys.LONG_LIVED_DOTCMS_ID_COOKIE); + + if (!UtilMethods.isSet(_dotCMSID)) { + // create unique generator engine + Cookie idCookie = CookieUtil.createCookie(); + _dotCMSID = idCookie.getValue(); + response.addCookie(idCookie); + newVisitor = true; + + if (visitor.isPresent()) { + visitor.get() + .setDmid(UUID.fromString(_dotCMSID)); + } + + } + + String _oncePerVisitCookie = UtilMethods.getCookieValue(request.getCookies(), WebKeys.ONCE_PER_VISIT_COOKIE); + + if (!UtilMethods.isSet(_oncePerVisitCookie)) { + newVisit = true; + } + + if (newVisitor) { + fireRules(request, response, Rule.FireOn.ONCE_PER_VISITOR); + if (response.isCommitted()) { + /* + * Some form of redirect, error, or the request has already been fulfilled in + * some fashion by one or more of the actionlets. + */ + Logger.debug(VelocityLiveServlet.class, "A ONCE_PER_VISITOR RuleEngine Action has committed the response."); + return; + } + } + + if (newVisit) { + fireRules(request, response, Rule.FireOn.ONCE_PER_VISIT); + if (response.isCommitted()) { + /* + * Some form of redirect, error, or the request has already been fulfilled in + * some fashion by one or more of the actionlets. + */ + Logger.debug(VelocityLiveServlet.class, "A ONCE_PER_VISIT RuleEngine Action has committed the response."); + return; + } + } + + fireRules(request, response, Rule.FireOn.EVERY_PAGE); + + } + + + + /** * Triggers a specific category of Rules associated to the specified parent * object based on the requested resource. diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/rules/conditionlet/VisitorOperatingSystemConditionlet.java b/dotCMS/src/main/java/com/dotmarketing/portlets/rules/conditionlet/VisitorOperatingSystemConditionlet.java index fe42b2b1e701..df744e93c35b 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/rules/conditionlet/VisitorOperatingSystemConditionlet.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/rules/conditionlet/VisitorOperatingSystemConditionlet.java @@ -11,7 +11,7 @@ import com.dotmarketing.portlets.rules.parameter.display.DropdownInput; import com.dotmarketing.portlets.rules.parameter.type.TextType; import com.dotmarketing.util.Logger; -import com.dotmarketing.viewtools.UserAgentTool; +import com.dotcms.rendering.velocity.viewtools.UserAgentTool; import eu.bitwalker.useragentutils.OperatingSystem; import javax.servlet.http.HttpServletRequest; @@ -24,7 +24,7 @@ /** * This conditionlet will allow CMS users to check the SO name a user - * request is issued from. The information is obtained by {@link com.dotmarketing.viewtools.UserAgentTool}, + * request is issued from. The information is obtained by {@link com.dotcms.rendering.velocity.viewtools.UserAgentTool}, * the list of possible values is in {@link eu.bitwalker.useragentutils.OperatingSystem}. * * diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/structure/action/EditFieldAction.java b/dotCMS/src/main/java/com/dotmarketing/portlets/structure/action/EditFieldAction.java index dc0d92e784ab..e582c5f1e5b0 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/structure/action/EditFieldAction.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/structure/action/EditFieldAction.java @@ -5,14 +5,16 @@ import com.dotcms.contenttype.model.field.DataTypes; import com.dotcms.contenttype.model.field.LegacyFieldTypes; import com.dotcms.contenttype.transform.field.LegacyFieldTransformer; +import com.dotcms.rendering.velocity.services.ContentTypeLoader; +import com.dotcms.rendering.velocity.services.ContentletLoader; import com.dotcms.repackage.com.google.common.annotations.VisibleForTesting; import com.dotcms.repackage.javax.portlet.ActionRequest; import com.dotcms.repackage.javax.portlet.ActionResponse; import com.dotcms.repackage.javax.portlet.PortletConfig; import com.dotcms.repackage.org.apache.commons.beanutils.BeanUtils; -import com.dotcms.repackage.org.apache.commons.lang.BooleanUtils; import com.dotcms.repackage.org.apache.struts.action.ActionForm; import com.dotcms.repackage.org.apache.struts.action.ActionMapping; + import com.dotmarketing.beans.Host; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.CacheLocator; @@ -34,9 +36,6 @@ import com.dotmarketing.portlets.structure.model.Structure; import com.dotmarketing.portlets.structure.struts.FieldForm; import com.dotmarketing.quartz.job.DeleteFieldJob; -import com.dotmarketing.services.ContentletMapServices; -import com.dotmarketing.services.ContentletServices; -import com.dotmarketing.services.StructureServices; import com.dotmarketing.util.ActivityLogger; import com.dotmarketing.util.AdminLogger; import com.dotmarketing.util.HostUtil; @@ -45,18 +44,21 @@ import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.Validator; import com.dotmarketing.util.WebKeys; -import com.liferay.portal.model.User; -import com.liferay.portal.util.Constants; -import com.liferay.portlet.ActionRequestImpl; -import com.liferay.util.StringUtil; -import com.liferay.util.servlet.SessionMessages; + import java.net.URLDecoder; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; +import com.liferay.portal.model.User; +import com.liferay.portal.util.Constants; +import com.liferay.portlet.ActionRequestImpl; +import com.liferay.util.StringUtil; +import com.liferay.util.servlet.SessionMessages; + /** * This Struts action will handle all the requests related to adding, updating * or deleting a field in a Content Type. This action is called from the Content @@ -365,7 +367,7 @@ private boolean _saveField(ActionForm form, ActionRequest req, ActionResponse re FieldsCache.removeFields(structure); CacheLocator.getContentTypeCache().remove(structure); - StructureServices.removeStructureFile(structure); + new ContentTypeLoader().invalidate(structure); StructureFactory.saveStructure(structure); FieldsCache.addFields(structure, structure.getFields()); @@ -382,8 +384,7 @@ private boolean _saveField(ActionForm form, ActionRequest req, ActionResponse re } if (fAPI.isElementConstant(field)) { - ContentletServices.removeContentletFile(structure); - ContentletMapServices.removeContentletMapFile(structure); + new ContentletLoader().invalidate(structure); conAPI.refresh(structure); } diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/structure/action/EditStructureAction.java b/dotCMS/src/main/java/com/dotmarketing/portlets/structure/action/EditStructureAction.java index 76858028dc60..c40cdf3b3212 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/structure/action/EditStructureAction.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/structure/action/EditStructureAction.java @@ -2,20 +2,13 @@ import static com.dotmarketing.business.PermissionAPI.PERMISSION_PUBLISH; -import com.google.common.collect.ImmutableList; -import java.net.URLDecoder; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.servlet.http.HttpServletRequest; - import com.dotcms.contenttype.exception.NotFoundInDbException; import com.dotcms.contenttype.model.type.BaseContentType; import com.dotcms.contenttype.model.type.ContentType; import com.dotcms.contenttype.model.type.ContentTypeBuilder; import com.dotcms.contenttype.model.type.SimpleContentType; import com.dotcms.contenttype.transform.contenttype.StructureTransformer; +import com.dotcms.rendering.velocity.services.ContentTypeLoader; import com.dotcms.repackage.javax.portlet.ActionRequest; import com.dotcms.repackage.javax.portlet.ActionResponse; import com.dotcms.repackage.javax.portlet.PortletConfig; @@ -23,6 +16,7 @@ import com.dotcms.repackage.org.apache.commons.beanutils.BeanUtils; import com.dotcms.repackage.org.apache.struts.action.ActionForm; import com.dotcms.repackage.org.apache.struts.action.ActionMapping; + import com.dotmarketing.beans.Identifier; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.CacheLocator; @@ -43,7 +37,6 @@ import com.dotmarketing.portlets.structure.struts.StructureForm; import com.dotmarketing.portlets.widget.business.WidgetAPI; import com.dotmarketing.portlets.workflows.model.WorkflowScheme; -import com.dotmarketing.services.StructureServices; import com.dotmarketing.util.ActivityLogger; import com.dotmarketing.util.HostUtil; import com.dotmarketing.util.InodeUtils; @@ -52,6 +45,15 @@ import com.dotmarketing.util.Validator; import com.dotmarketing.util.VelocityUtil; import com.dotmarketing.util.WebKeys; + +import java.net.URLDecoder; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; + +import com.google.common.collect.ImmutableList; import com.liferay.portal.model.User; import com.liferay.portal.struts.ActionException; import com.liferay.portal.util.Constants; @@ -423,7 +425,7 @@ private void _saveStructure(ActionForm form, ActionRequest req, ActionResponse r // Saving the structure in cache CacheLocator.getContentTypeCache().remove(structure); CacheLocator.getContentTypeCache().add(structure); - StructureServices.removeStructureFile(structure); + new ContentTypeLoader().invalidate(structure); String message = "message.structure.savestructure"; if (structure.getStructureType() == 3) { diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/templates/action/EditTemplateAction.java b/dotCMS/src/main/java/com/dotmarketing/portlets/templates/action/EditTemplateAction.java index a399aa9a1dfb..3f4338ead240 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/templates/action/EditTemplateAction.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/templates/action/EditTemplateAction.java @@ -1,34 +1,23 @@ package com.dotmarketing.portlets.templates.action; import com.dotcms.contenttype.model.type.BaseContentType; -import com.dotmarketing.exception.DotDataException; -import com.dotmarketing.exception.DotSecurityException; -import com.dotmarketing.portlets.htmlpageasset.model.HTMLPageAsset; -import com.dotmarketing.portlets.templates.business.TemplateConstants; -import com.liferay.portal.language.LanguageException; -import com.liferay.portal.language.LanguageUtil; -import com.liferay.util.servlet.SessionDialogMessage; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.List; - +import com.dotcms.rendering.velocity.services.TemplateLoader; import com.dotcms.repackage.javax.portlet.ActionRequest; import com.dotcms.repackage.javax.portlet.ActionResponse; import com.dotcms.repackage.javax.portlet.PortletConfig; import com.dotcms.repackage.javax.portlet.WindowState; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - import com.dotcms.repackage.org.apache.commons.beanutils.BeanUtils; import com.dotcms.repackage.org.apache.struts.action.ActionForm; import com.dotcms.repackage.org.apache.struts.action.ActionMapping; + import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.WebAsset; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.PermissionAPI; import com.dotmarketing.db.HibernateUtil; +import com.dotmarketing.exception.DotDataException; +import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.factories.InodeFactory; import com.dotmarketing.factories.WebAssetFactory; import com.dotmarketing.portal.struts.DotPortletAction; @@ -36,12 +25,13 @@ import com.dotmarketing.portlets.contentlet.business.HostAPI; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.folders.model.Folder; +import com.dotmarketing.portlets.htmlpageasset.model.HTMLPageAsset; import com.dotmarketing.portlets.templates.business.TemplateAPI; +import com.dotmarketing.portlets.templates.business.TemplateConstants; import com.dotmarketing.portlets.templates.design.bean.TemplateLayout; import com.dotmarketing.portlets.templates.design.util.DesignTemplateUtil; import com.dotmarketing.portlets.templates.model.Template; import com.dotmarketing.portlets.templates.struts.TemplateForm; -import com.dotmarketing.services.TemplateServices; import com.dotmarketing.util.ActivityLogger; import com.dotmarketing.util.HostUtil; import com.dotmarketing.util.InodeUtils; @@ -50,10 +40,21 @@ import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.Validator; import com.dotmarketing.util.WebKeys; + +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import com.liferay.portal.language.LanguageException; +import com.liferay.portal.language.LanguageUtil; import com.liferay.portal.model.User; import com.liferay.portal.struts.ActionException; import com.liferay.portal.util.Constants; import com.liferay.portlet.ActionRequestImpl; +import com.liferay.util.servlet.SessionDialogMessage; import com.liferay.util.servlet.SessionMessages; /** @@ -762,7 +763,7 @@ public void _getVersionBackWebAsset(ActionRequest req, ActionResponse res, APILocator.getVersionableAPI().setWorking(versionTemplate); //Template newWorkingTemplate = (Template) super._getVersionBackWebAsset(req, res, config, form, user, Template.class, WebKeys.TEMPLATE_EDIT); - TemplateServices.invalidate(versionTemplate, true); + new TemplateLoader().invalidate(versionTemplate); } // private void updateParseContainerSyntax(Template template){ diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/templates/action/PublishTemplatesAction.java b/dotCMS/src/main/java/com/dotmarketing/portlets/templates/action/PublishTemplatesAction.java index 6f51fcbb1636..a5d2d4d9d5e1 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/templates/action/PublishTemplatesAction.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/templates/action/PublishTemplatesAction.java @@ -1,30 +1,23 @@ package com.dotmarketing.portlets.templates.action; -import java.net.URLDecoder; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - import com.dotcms.repackage.javax.portlet.ActionRequest; import com.dotcms.repackage.javax.portlet.ActionResponse; import com.dotcms.repackage.javax.portlet.PortletConfig; - import com.dotcms.repackage.org.apache.struts.action.ActionForm; import com.dotcms.repackage.org.apache.struts.action.ActionMapping; -import com.dotmarketing.business.APILocator; import com.dotmarketing.exception.WebAssetException; import com.dotmarketing.factories.InodeFactory; import com.dotmarketing.factories.PublishFactory; import com.dotmarketing.portal.struts.DotPortletAction; -import com.dotmarketing.portlets.htmlpageasset.model.HTMLPageAsset; import com.dotmarketing.portlets.templates.model.Template; -import com.dotmarketing.services.PageServices; import com.dotmarketing.util.ActivityLogger; import com.dotmarketing.util.HostUtil; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; + +import java.net.URLDecoder; + import com.liferay.portal.model.User; import com.liferay.portlet.ActionRequestImpl; import com.liferay.util.servlet.SessionMessages; diff --git a/dotCMS/src/main/java/com/dotmarketing/portlets/templates/business/TemplateAPI.java b/dotCMS/src/main/java/com/dotmarketing/portlets/templates/business/TemplateAPI.java index 4dc3e68db133..903b54913b3a 100644 --- a/dotCMS/src/main/java/com/dotmarketing/portlets/templates/business/TemplateAPI.java +++ b/dotCMS/src/main/java/com/dotmarketing/portlets/templates/business/TemplateAPI.java @@ -171,7 +171,6 @@ Template copy(Template sourceTemplate, Host destinationHost, boolean forceOverwr */ public List